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 (const char *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       if (getContext()->getOrLoadDialect(dialectName)) {
994         result.name = OperationName(name, getContext());
995       } else if (!getContext()->allowsUnregisteredDialects()) {
996         // Emit an error if the dialect couldn't be loaded (i.e., it was not
997         // registered) and unregistered dialects aren't allowed.
998         return emitError(
999                    "operation being parsed with an unregistered dialect. If "
1000                    "this is intended, please use -allow-unregistered-dialect "
1001                    "with the MLIR tool used"),
1002                nullptr;
1003       }
1004     }
1005   }
1006 
1007   // If we are populating the parser state, start a new operation definition.
1008   if (state.asmState)
1009     state.asmState->startOperationDefinition(result.name);
1010 
1011   // Parse the operand list.
1012   SmallVector<SSAUseInfo, 8> operandInfos;
1013   if (parseToken(Token::l_paren, "expected '(' to start operand list") ||
1014       parseOptionalSSAUseList(operandInfos) ||
1015       parseToken(Token::r_paren, "expected ')' to end operand list")) {
1016     return nullptr;
1017   }
1018 
1019   // Parse the successor list.
1020   if (getToken().is(Token::l_square)) {
1021     // Check if the operation is a known terminator.
1022     const AbstractOperation *abstractOp = result.name.getAbstractOperation();
1023     if (abstractOp && !abstractOp->hasTrait<OpTrait::IsTerminator>())
1024       return emitError("successors in non-terminator"), nullptr;
1025 
1026     SmallVector<Block *, 2> successors;
1027     if (parseSuccessors(successors))
1028       return nullptr;
1029     result.addSuccessors(successors);
1030   }
1031 
1032   // Parse the region list.
1033   CleanupOpStateRegions guard{result};
1034   if (consumeIf(Token::l_paren)) {
1035     do {
1036       // Create temporary regions with the top level region as parent.
1037       result.regions.emplace_back(new Region(topLevelOp));
1038       if (parseRegion(*result.regions.back(), /*entryArguments=*/{}))
1039         return nullptr;
1040     } while (consumeIf(Token::comma));
1041     if (parseToken(Token::r_paren, "expected ')' to end region list"))
1042       return nullptr;
1043   }
1044 
1045   if (getToken().is(Token::l_brace)) {
1046     if (parseAttributeDict(result.attributes))
1047       return nullptr;
1048   }
1049 
1050   if (parseToken(Token::colon, "expected ':' followed by operation type"))
1051     return nullptr;
1052 
1053   auto typeLoc = getToken().getLoc();
1054   auto type = parseType();
1055   if (!type)
1056     return nullptr;
1057   auto fnType = type.dyn_cast<FunctionType>();
1058   if (!fnType)
1059     return (emitError(typeLoc, "expected function type"), nullptr);
1060 
1061   result.addTypes(fnType.getResults());
1062 
1063   // Check that we have the right number of types for the operands.
1064   auto operandTypes = fnType.getInputs();
1065   if (operandTypes.size() != operandInfos.size()) {
1066     auto plural = "s"[operandInfos.size() == 1];
1067     return (emitError(typeLoc, "expected ")
1068                 << operandInfos.size() << " operand type" << plural
1069                 << " but had " << operandTypes.size(),
1070             nullptr);
1071   }
1072 
1073   // Resolve all of the operands.
1074   for (unsigned i = 0, e = operandInfos.size(); i != e; ++i) {
1075     result.operands.push_back(resolveSSAUse(operandInfos[i], operandTypes[i]));
1076     if (!result.operands.back())
1077       return nullptr;
1078   }
1079 
1080   // Create the operation and try to parse a location for it.
1081   Operation *op = opBuilder.createOperation(result);
1082   if (parseTrailingLocationSpecifier(op))
1083     return nullptr;
1084   return op;
1085 }
1086 
1087 Operation *OperationParser::parseGenericOperation(Block *insertBlock,
1088                                                   Block::iterator insertPt) {
1089   Token nameToken = getToken();
1090 
1091   OpBuilder::InsertionGuard restoreInsertionPoint(opBuilder);
1092   opBuilder.setInsertionPoint(insertBlock, insertPt);
1093   Operation *op = parseGenericOperation();
1094   if (!op)
1095     return nullptr;
1096 
1097   // If we are populating the parser asm state, finalize this operation
1098   // definition.
1099   if (state.asmState)
1100     state.asmState->finalizeOperationDefinition(op, nameToken.getLocRange(),
1101                                                 /*endLoc=*/getToken().getLoc());
1102   return op;
1103 }
1104 
1105 namespace {
1106 class CustomOpAsmParser : public AsmParserImpl<OpAsmParser> {
1107 public:
1108   CustomOpAsmParser(
1109       SMLoc nameLoc, ArrayRef<OperationParser::ResultRecord> resultIDs,
1110       function_ref<ParseResult(OpAsmParser &, OperationState &)> parseAssembly,
1111       bool isIsolatedFromAbove, StringRef opName, OperationParser &parser)
1112       : AsmParserImpl<OpAsmParser>(nameLoc, parser), resultIDs(resultIDs),
1113         parseAssembly(parseAssembly), isIsolatedFromAbove(isIsolatedFromAbove),
1114         opName(opName), parser(parser) {
1115     (void)isIsolatedFromAbove; // Only used in assert, silence unused warning.
1116   }
1117 
1118   /// Parse an instance of the operation described by 'opDefinition' into the
1119   /// provided operation state.
1120   ParseResult parseOperation(OperationState &opState) {
1121     if (parseAssembly(*this, opState))
1122       return failure();
1123     // Verify that the parsed attributes does not have duplicate attributes.
1124     // This can happen if an attribute set during parsing is also specified in
1125     // the attribute dictionary in the assembly, or the attribute is set
1126     // multiple during parsing.
1127     Optional<NamedAttribute> duplicate = opState.attributes.findDuplicate();
1128     if (duplicate)
1129       return emitError(getNameLoc(), "attribute '")
1130              << duplicate->first
1131              << "' occurs more than once in the attribute list";
1132     return success();
1133   }
1134 
1135   Operation *parseGenericOperation(Block *insertBlock,
1136                                    Block::iterator insertPt) final {
1137     return parser.parseGenericOperation(insertBlock, insertPt);
1138   }
1139 
1140   //===--------------------------------------------------------------------===//
1141   // Utilities
1142   //===--------------------------------------------------------------------===//
1143 
1144   /// Return the name of the specified result in the specified syntax, as well
1145   /// as the subelement in the name.  For example, in this operation:
1146   ///
1147   ///  %x, %y:2, %z = foo.op
1148   ///
1149   ///    getResultName(0) == {"x", 0 }
1150   ///    getResultName(1) == {"y", 0 }
1151   ///    getResultName(2) == {"y", 1 }
1152   ///    getResultName(3) == {"z", 0 }
1153   std::pair<StringRef, unsigned>
1154   getResultName(unsigned resultNo) const override {
1155     // Scan for the resultID that contains this result number.
1156     for (unsigned nameID = 0, e = resultIDs.size(); nameID != e; ++nameID) {
1157       const auto &entry = resultIDs[nameID];
1158       if (resultNo < std::get<1>(entry)) {
1159         // Don't pass on the leading %.
1160         StringRef name = std::get<0>(entry).drop_front();
1161         return {name, resultNo};
1162       }
1163       resultNo -= std::get<1>(entry);
1164     }
1165 
1166     // Invalid result number.
1167     return {"", ~0U};
1168   }
1169 
1170   /// Return the number of declared SSA results.  This returns 4 for the foo.op
1171   /// example in the comment for getResultName.
1172   size_t getNumResults() const override {
1173     size_t count = 0;
1174     for (auto &entry : resultIDs)
1175       count += std::get<1>(entry);
1176     return count;
1177   }
1178 
1179   /// Emit a diagnostic at the specified location and return failure.
1180   InFlightDiagnostic emitError(llvm::SMLoc loc, const Twine &message) override {
1181     return AsmParserImpl<OpAsmParser>::emitError(loc, "custom op '" + opName +
1182                                                           "' " + message);
1183   }
1184 
1185   //===--------------------------------------------------------------------===//
1186   // Operand Parsing
1187   //===--------------------------------------------------------------------===//
1188 
1189   /// Parse a single operand.
1190   ParseResult parseOperand(OperandType &result) override {
1191     OperationParser::SSAUseInfo useInfo;
1192     if (parser.parseSSAUse(useInfo))
1193       return failure();
1194 
1195     result = {useInfo.loc, useInfo.name, useInfo.number};
1196     return success();
1197   }
1198 
1199   /// Parse a single operand if present.
1200   OptionalParseResult parseOptionalOperand(OperandType &result) override {
1201     if (parser.getToken().is(Token::percent_identifier))
1202       return parseOperand(result);
1203     return llvm::None;
1204   }
1205 
1206   /// Parse zero or more SSA comma-separated operand references with a specified
1207   /// surrounding delimiter, and an optional required operand count.
1208   ParseResult parseOperandList(SmallVectorImpl<OperandType> &result,
1209                                int requiredOperandCount = -1,
1210                                Delimiter delimiter = Delimiter::None) override {
1211     return parseOperandOrRegionArgList(result, /*isOperandList=*/true,
1212                                        requiredOperandCount, delimiter);
1213   }
1214 
1215   /// Parse zero or more SSA comma-separated operand or region arguments with
1216   ///  optional surrounding delimiter and required operand count.
1217   ParseResult
1218   parseOperandOrRegionArgList(SmallVectorImpl<OperandType> &result,
1219                               bool isOperandList, int requiredOperandCount = -1,
1220                               Delimiter delimiter = Delimiter::None) {
1221     auto startLoc = parser.getToken().getLoc();
1222 
1223     // The no-delimiter case has some special handling for better diagnostics.
1224     if (delimiter == Delimiter::None) {
1225       // parseCommaSeparatedList doesn't handle the missing case for "none",
1226       // so we handle it custom here.
1227       if (parser.getToken().isNot(Token::percent_identifier)) {
1228         // If we didn't require any operands or required exactly zero (weird)
1229         // then this is success.
1230         if (requiredOperandCount == -1 || requiredOperandCount == 0)
1231           return success();
1232 
1233         // Otherwise, try to produce a nice error message.
1234         if (parser.getToken().is(Token::l_paren) ||
1235             parser.getToken().is(Token::l_square))
1236           return emitError(startLoc, "unexpected delimiter");
1237         return emitError(startLoc, "invalid operand");
1238       }
1239     }
1240 
1241     auto parseOneOperand = [&]() -> ParseResult {
1242       OperandType operandOrArg;
1243       if (isOperandList ? parseOperand(operandOrArg)
1244                         : parseRegionArgument(operandOrArg))
1245         return failure();
1246       result.push_back(operandOrArg);
1247       return success();
1248     };
1249 
1250     if (parseCommaSeparatedList(delimiter, parseOneOperand, " in operand list"))
1251       return failure();
1252 
1253     // Check that we got the expected # of elements.
1254     if (requiredOperandCount != -1 &&
1255         result.size() != static_cast<size_t>(requiredOperandCount))
1256       return emitError(startLoc, "expected ")
1257              << requiredOperandCount << " operands";
1258     return success();
1259   }
1260 
1261   /// Parse zero or more trailing SSA comma-separated trailing operand
1262   /// references with a specified surrounding delimiter, and an optional
1263   /// required operand count. A leading comma is expected before the operands.
1264   ParseResult parseTrailingOperandList(SmallVectorImpl<OperandType> &result,
1265                                        int requiredOperandCount,
1266                                        Delimiter delimiter) override {
1267     if (parser.getToken().is(Token::comma)) {
1268       parseComma();
1269       return parseOperandList(result, requiredOperandCount, delimiter);
1270     }
1271     if (requiredOperandCount != -1)
1272       return emitError(parser.getToken().getLoc(), "expected ")
1273              << requiredOperandCount << " operands";
1274     return success();
1275   }
1276 
1277   /// Resolve an operand to an SSA value, emitting an error on failure.
1278   ParseResult resolveOperand(const OperandType &operand, Type type,
1279                              SmallVectorImpl<Value> &result) override {
1280     OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number,
1281                                                operand.location};
1282     if (auto value = parser.resolveSSAUse(operandInfo, type)) {
1283       result.push_back(value);
1284       return success();
1285     }
1286     return failure();
1287   }
1288 
1289   /// Parse an AffineMap of SSA ids.
1290   ParseResult parseAffineMapOfSSAIds(SmallVectorImpl<OperandType> &operands,
1291                                      Attribute &mapAttr, StringRef attrName,
1292                                      NamedAttrList &attrs,
1293                                      Delimiter delimiter) override {
1294     SmallVector<OperandType, 2> dimOperands;
1295     SmallVector<OperandType, 1> symOperands;
1296 
1297     auto parseElement = [&](bool isSymbol) -> ParseResult {
1298       OperandType operand;
1299       if (parseOperand(operand))
1300         return failure();
1301       if (isSymbol)
1302         symOperands.push_back(operand);
1303       else
1304         dimOperands.push_back(operand);
1305       return success();
1306     };
1307 
1308     AffineMap map;
1309     if (parser.parseAffineMapOfSSAIds(map, parseElement, delimiter))
1310       return failure();
1311     // Add AffineMap attribute.
1312     if (map) {
1313       mapAttr = AffineMapAttr::get(map);
1314       attrs.push_back(parser.builder.getNamedAttr(attrName, mapAttr));
1315     }
1316 
1317     // Add dim operands before symbol operands in 'operands'.
1318     operands.assign(dimOperands.begin(), dimOperands.end());
1319     operands.append(symOperands.begin(), symOperands.end());
1320     return success();
1321   }
1322 
1323   /// Parse an AffineExpr of SSA ids.
1324   ParseResult
1325   parseAffineExprOfSSAIds(SmallVectorImpl<OperandType> &dimOperands,
1326                           SmallVectorImpl<OperandType> &symbOperands,
1327                           AffineExpr &expr) override {
1328     auto parseElement = [&](bool isSymbol) -> ParseResult {
1329       OperandType operand;
1330       if (parseOperand(operand))
1331         return failure();
1332       if (isSymbol)
1333         symbOperands.push_back(operand);
1334       else
1335         dimOperands.push_back(operand);
1336       return success();
1337     };
1338 
1339     return parser.parseAffineExprOfSSAIds(expr, parseElement);
1340   }
1341 
1342   //===--------------------------------------------------------------------===//
1343   // Region Parsing
1344   //===--------------------------------------------------------------------===//
1345 
1346   /// Parse a region that takes `arguments` of `argTypes` types.  This
1347   /// effectively defines the SSA values of `arguments` and assigns their type.
1348   ParseResult parseRegion(Region &region, ArrayRef<OperandType> arguments,
1349                           ArrayRef<Type> argTypes,
1350                           bool enableNameShadowing) override {
1351     assert(arguments.size() == argTypes.size() &&
1352            "mismatching number of arguments and types");
1353 
1354     SmallVector<std::pair<OperationParser::SSAUseInfo, Type>, 2>
1355         regionArguments;
1356     for (auto pair : llvm::zip(arguments, argTypes)) {
1357       const OperandType &operand = std::get<0>(pair);
1358       Type type = std::get<1>(pair);
1359       OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number,
1360                                                  operand.location};
1361       regionArguments.emplace_back(operandInfo, type);
1362     }
1363 
1364     // Try to parse the region.
1365     (void)isIsolatedFromAbove;
1366     assert((!enableNameShadowing || isIsolatedFromAbove) &&
1367            "name shadowing is only allowed on isolated regions");
1368     if (parser.parseRegion(region, regionArguments, enableNameShadowing))
1369       return failure();
1370     return success();
1371   }
1372 
1373   /// Parses a region if present.
1374   OptionalParseResult parseOptionalRegion(Region &region,
1375                                           ArrayRef<OperandType> arguments,
1376                                           ArrayRef<Type> argTypes,
1377                                           bool enableNameShadowing) override {
1378     if (parser.getToken().isNot(Token::l_brace))
1379       return llvm::None;
1380     return parseRegion(region, arguments, argTypes, enableNameShadowing);
1381   }
1382 
1383   /// Parses a region if present. If the region is present, a new region is
1384   /// allocated and placed in `region`. If no region is present, `region`
1385   /// remains untouched.
1386   OptionalParseResult
1387   parseOptionalRegion(std::unique_ptr<Region> &region,
1388                       ArrayRef<OperandType> arguments, ArrayRef<Type> argTypes,
1389                       bool enableNameShadowing = false) override {
1390     if (parser.getToken().isNot(Token::l_brace))
1391       return llvm::None;
1392     std::unique_ptr<Region> newRegion = std::make_unique<Region>();
1393     if (parseRegion(*newRegion, arguments, argTypes, enableNameShadowing))
1394       return failure();
1395 
1396     region = std::move(newRegion);
1397     return success();
1398   }
1399 
1400   /// Parse a region argument. The type of the argument will be resolved later
1401   /// by a call to `parseRegion`.
1402   ParseResult parseRegionArgument(OperandType &argument) override {
1403     return parseOperand(argument);
1404   }
1405 
1406   /// Parse a region argument if present.
1407   ParseResult parseOptionalRegionArgument(OperandType &argument) override {
1408     if (parser.getToken().isNot(Token::percent_identifier))
1409       return success();
1410     return parseRegionArgument(argument);
1411   }
1412 
1413   ParseResult
1414   parseRegionArgumentList(SmallVectorImpl<OperandType> &result,
1415                           int requiredOperandCount = -1,
1416                           Delimiter delimiter = Delimiter::None) override {
1417     return parseOperandOrRegionArgList(result, /*isOperandList=*/false,
1418                                        requiredOperandCount, delimiter);
1419   }
1420 
1421   //===--------------------------------------------------------------------===//
1422   // Successor Parsing
1423   //===--------------------------------------------------------------------===//
1424 
1425   /// Parse a single operation successor.
1426   ParseResult parseSuccessor(Block *&dest) override {
1427     return parser.parseSuccessor(dest);
1428   }
1429 
1430   /// Parse an optional operation successor and its operand list.
1431   OptionalParseResult parseOptionalSuccessor(Block *&dest) override {
1432     if (parser.getToken().isNot(Token::caret_identifier))
1433       return llvm::None;
1434     return parseSuccessor(dest);
1435   }
1436 
1437   /// Parse a single operation successor and its operand list.
1438   ParseResult
1439   parseSuccessorAndUseList(Block *&dest,
1440                            SmallVectorImpl<Value> &operands) override {
1441     if (parseSuccessor(dest))
1442       return failure();
1443 
1444     // Handle optional arguments.
1445     if (succeeded(parseOptionalLParen()) &&
1446         (parser.parseOptionalSSAUseAndTypeList(operands) || parseRParen())) {
1447       return failure();
1448     }
1449     return success();
1450   }
1451 
1452   //===--------------------------------------------------------------------===//
1453   // Type Parsing
1454   //===--------------------------------------------------------------------===//
1455 
1456   /// Parse a list of assignments of the form
1457   ///   (%x1 = %y1, %x2 = %y2, ...).
1458   OptionalParseResult
1459   parseOptionalAssignmentList(SmallVectorImpl<OperandType> &lhs,
1460                               SmallVectorImpl<OperandType> &rhs) override {
1461     if (failed(parseOptionalLParen()))
1462       return llvm::None;
1463 
1464     auto parseElt = [&]() -> ParseResult {
1465       OperandType regionArg, operand;
1466       if (parseRegionArgument(regionArg) || parseEqual() ||
1467           parseOperand(operand))
1468         return failure();
1469       lhs.push_back(regionArg);
1470       rhs.push_back(operand);
1471       return success();
1472     };
1473     return parser.parseCommaSeparatedListUntil(Token::r_paren, parseElt);
1474   }
1475 
1476   /// Parse a list of assignments of the form
1477   ///   (%x1 = %y1 : type1, %x2 = %y2 : type2, ...).
1478   OptionalParseResult
1479   parseOptionalAssignmentListWithTypes(SmallVectorImpl<OperandType> &lhs,
1480                                        SmallVectorImpl<OperandType> &rhs,
1481                                        SmallVectorImpl<Type> &types) override {
1482     if (failed(parseOptionalLParen()))
1483       return llvm::None;
1484 
1485     auto parseElt = [&]() -> ParseResult {
1486       OperandType regionArg, operand;
1487       Type type;
1488       if (parseRegionArgument(regionArg) || parseEqual() ||
1489           parseOperand(operand) || parseColon() || parseType(type))
1490         return failure();
1491       lhs.push_back(regionArg);
1492       rhs.push_back(operand);
1493       types.push_back(type);
1494       return success();
1495     };
1496     return parser.parseCommaSeparatedListUntil(Token::r_paren, parseElt);
1497   }
1498 
1499 private:
1500   /// Information about the result name specifiers.
1501   ArrayRef<OperationParser::ResultRecord> resultIDs;
1502 
1503   /// The abstract information of the operation.
1504   function_ref<ParseResult(OpAsmParser &, OperationState &)> parseAssembly;
1505   bool isIsolatedFromAbove;
1506   StringRef opName;
1507 
1508   /// The backing operation parser.
1509   OperationParser &parser;
1510 };
1511 } // end anonymous namespace.
1512 
1513 Operation *
1514 OperationParser::parseCustomOperation(ArrayRef<ResultRecord> resultIDs) {
1515   llvm::SMLoc opLoc = getToken().getLoc();
1516   std::string opName = getTokenSpelling().str();
1517   auto *opDefinition = AbstractOperation::lookup(opName, getContext());
1518   StringRef defaultDialect = getState().defaultDialectStack.back();
1519   Dialect *dialect = nullptr;
1520   if (opDefinition) {
1521     dialect = &opDefinition->dialect;
1522   } else {
1523     if (StringRef(opName).contains('.')) {
1524       // This op has a dialect, we try to check if we can register it in the
1525       // context on the fly.
1526       StringRef dialectName = StringRef(opName).split('.').first;
1527       dialect = getContext()->getLoadedDialect(dialectName);
1528       if (!dialect && (dialect = getContext()->getOrLoadDialect(dialectName)))
1529         opDefinition = AbstractOperation::lookup(opName, getContext());
1530     } else {
1531       // If the operation name has no namespace prefix we lookup the current
1532       // default dialect (set through OpAsmOpInterface).
1533       opDefinition = AbstractOperation::lookup(
1534           Twine(defaultDialect + "." + opName).str(), getContext());
1535       if (!opDefinition && getContext()->getOrLoadDialect("std")) {
1536         opDefinition = AbstractOperation::lookup(Twine("std." + opName).str(),
1537                                                  getContext());
1538       }
1539       if (opDefinition) {
1540         dialect = &opDefinition->dialect;
1541         opName = opDefinition->name.str();
1542       } else if (!defaultDialect.empty()) {
1543         dialect = getContext()->getOrLoadDialect(defaultDialect);
1544         opName = (defaultDialect + "." + opName).str();
1545       }
1546     }
1547   }
1548 
1549   // This is the actual hook for the custom op parsing, usually implemented by
1550   // the op itself (`Op::parse()`). We retrieve it either from the
1551   // AbstractOperation or from the Dialect.
1552   function_ref<ParseResult(OpAsmParser &, OperationState &)> parseAssemblyFn;
1553   bool isIsolatedFromAbove = false;
1554 
1555   defaultDialect = "";
1556   if (opDefinition) {
1557     parseAssemblyFn = opDefinition->getParseAssemblyFn();
1558     isIsolatedFromAbove =
1559         opDefinition->hasTrait<OpTrait::IsIsolatedFromAbove>();
1560     auto *iface = opDefinition->getInterface<OpAsmOpInterface>();
1561     if (iface && !iface->getDefaultDialect().empty())
1562       defaultDialect = iface->getDefaultDialect();
1563   } else {
1564     Optional<Dialect::ParseOpHook> dialectHook;
1565     if (dialect)
1566       dialectHook = dialect->getParseOperationHook(opName);
1567     if (!dialectHook.hasValue()) {
1568       emitError(opLoc) << "custom op '" << opName << "' is unknown";
1569       return nullptr;
1570     }
1571     parseAssemblyFn = *dialectHook;
1572   }
1573   getState().defaultDialectStack.push_back(defaultDialect);
1574   auto restoreDefaultDialect = llvm::make_scope_exit(
1575       [&]() { getState().defaultDialectStack.pop_back(); });
1576 
1577   consumeToken();
1578 
1579   // If the custom op parser crashes, produce some indication to help
1580   // debugging.
1581   llvm::PrettyStackTraceFormat fmt("MLIR Parser: custom op parser '%s'",
1582                                    opName.c_str());
1583 
1584   // Get location information for the operation.
1585   auto srcLocation = getEncodedSourceLocation(opLoc);
1586   OperationState opState(srcLocation, opName);
1587 
1588   // If we are populating the parser state, start a new operation definition.
1589   if (state.asmState)
1590     state.asmState->startOperationDefinition(opState.name);
1591 
1592   // Have the op implementation take a crack and parsing this.
1593   CleanupOpStateRegions guard{opState};
1594   CustomOpAsmParser opAsmParser(opLoc, resultIDs, parseAssemblyFn,
1595                                 isIsolatedFromAbove, opName, *this);
1596   if (opAsmParser.parseOperation(opState))
1597     return nullptr;
1598 
1599   // If it emitted an error, we failed.
1600   if (opAsmParser.didEmitError())
1601     return nullptr;
1602 
1603   // Otherwise, create the operation and try to parse a location for it.
1604   Operation *op = opBuilder.createOperation(opState);
1605   if (parseTrailingLocationSpecifier(op))
1606     return nullptr;
1607   return op;
1608 }
1609 
1610 ParseResult
1611 OperationParser::parseTrailingLocationSpecifier(OpOrArgument opOrArgument) {
1612   // If there is a 'loc' we parse a trailing location.
1613   if (!consumeIf(Token::kw_loc))
1614     return success();
1615   if (parseToken(Token::l_paren, "expected '(' in location"))
1616     return failure();
1617   Token tok = getToken();
1618 
1619   // Check to see if we are parsing a location alias.
1620   LocationAttr directLoc;
1621   if (tok.is(Token::hash_identifier)) {
1622     consumeToken();
1623 
1624     StringRef identifier = tok.getSpelling().drop_front();
1625     if (identifier.contains('.')) {
1626       return emitError(tok.getLoc())
1627              << "expected location, but found dialect attribute: '#"
1628              << identifier << "'";
1629     }
1630 
1631     // If this alias can be resolved, do it now.
1632     Attribute attr = state.symbols.attributeAliasDefinitions.lookup(identifier);
1633     if (attr) {
1634       if (!(directLoc = attr.dyn_cast<LocationAttr>()))
1635         return emitError(tok.getLoc())
1636                << "expected location, but found '" << attr << "'";
1637     } else {
1638       // Otherwise, remember this operation and resolve its location later.
1639       opsAndArgumentsWithDeferredLocs.emplace_back(opOrArgument, tok);
1640     }
1641 
1642     // Otherwise, we parse the location directly.
1643   } else if (parseLocationInstance(directLoc)) {
1644     return failure();
1645   }
1646 
1647   if (parseToken(Token::r_paren, "expected ')' in location"))
1648     return failure();
1649 
1650   if (directLoc) {
1651     if (auto *op = opOrArgument.dyn_cast<Operation *>())
1652       op->setLoc(directLoc);
1653     else
1654       opOrArgument.get<BlockArgument>().setLoc(directLoc);
1655   }
1656   return success();
1657 }
1658 
1659 //===----------------------------------------------------------------------===//
1660 // Region Parsing
1661 //===----------------------------------------------------------------------===//
1662 
1663 ParseResult OperationParser::parseRegion(
1664     Region &region,
1665     ArrayRef<std::pair<OperationParser::SSAUseInfo, Type>> entryArguments,
1666     bool isIsolatedNameScope) {
1667   // Parse the '{'.
1668   Token lBraceTok = getToken();
1669   if (parseToken(Token::l_brace, "expected '{' to begin a region"))
1670     return failure();
1671 
1672   // If we are populating the parser state, start a new region definition.
1673   if (state.asmState)
1674     state.asmState->startRegionDefinition();
1675 
1676   // Parse the region body.
1677   if ((!entryArguments.empty() || getToken().isNot(Token::r_brace)) &&
1678       parseRegionBody(region, lBraceTok.getLoc(), entryArguments,
1679                       isIsolatedNameScope)) {
1680     return failure();
1681   }
1682   consumeToken(Token::r_brace);
1683 
1684   // If we are populating the parser state, finalize this region.
1685   if (state.asmState)
1686     state.asmState->finalizeRegionDefinition();
1687 
1688   return success();
1689 }
1690 
1691 ParseResult OperationParser::parseRegionBody(
1692     Region &region, llvm::SMLoc startLoc,
1693     ArrayRef<std::pair<OperationParser::SSAUseInfo, Type>> entryArguments,
1694     bool isIsolatedNameScope) {
1695   auto currentPt = opBuilder.saveInsertionPoint();
1696 
1697   // Push a new named value scope.
1698   pushSSANameScope(isIsolatedNameScope);
1699 
1700   // Parse the first block directly to allow for it to be unnamed.
1701   auto owningBlock = std::make_unique<Block>();
1702   Block *block = owningBlock.get();
1703 
1704   // If this block is not defined in the source file, add a definition for it
1705   // now in the assembly state. Blocks with a name will be defined when the name
1706   // is parsed.
1707   if (state.asmState && getToken().isNot(Token::caret_identifier))
1708     state.asmState->addDefinition(block, startLoc);
1709 
1710   // Add arguments to the entry block.
1711   if (!entryArguments.empty()) {
1712     // If we had named arguments, then don't allow a block name.
1713     if (getToken().is(Token::caret_identifier))
1714       return emitError("invalid block name in region with named arguments");
1715 
1716     for (auto &placeholderArgPair : entryArguments) {
1717       auto &argInfo = placeholderArgPair.first;
1718 
1719       // Ensure that the argument was not already defined.
1720       if (auto defLoc = getReferenceLoc(argInfo.name, argInfo.number)) {
1721         return emitError(argInfo.loc, "region entry argument '" + argInfo.name +
1722                                           "' is already in use")
1723                    .attachNote(getEncodedSourceLocation(*defLoc))
1724                << "previously referenced here";
1725       }
1726       auto loc = getEncodedSourceLocation(placeholderArgPair.first.loc);
1727       BlockArgument arg = block->addArgument(placeholderArgPair.second, loc);
1728 
1729       // Add a definition of this arg to the assembly state if provided.
1730       if (state.asmState)
1731         state.asmState->addDefinition(arg, argInfo.loc);
1732 
1733       // Record the definition for this argument.
1734       if (addDefinition(argInfo, arg))
1735         return failure();
1736     }
1737   }
1738 
1739   if (parseBlock(block))
1740     return failure();
1741 
1742   // Verify that no other arguments were parsed.
1743   if (!entryArguments.empty() &&
1744       block->getNumArguments() > entryArguments.size()) {
1745     return emitError("entry block arguments were already defined");
1746   }
1747 
1748   // Parse the rest of the region.
1749   region.push_back(owningBlock.release());
1750   while (getToken().isNot(Token::r_brace)) {
1751     Block *newBlock = nullptr;
1752     if (parseBlock(newBlock))
1753       return failure();
1754     region.push_back(newBlock);
1755   }
1756 
1757   // Pop the SSA value scope for this region.
1758   if (popSSANameScope())
1759     return failure();
1760 
1761   // Reset the original insertion point.
1762   opBuilder.restoreInsertionPoint(currentPt);
1763   return success();
1764 }
1765 
1766 //===----------------------------------------------------------------------===//
1767 // Block Parsing
1768 //===----------------------------------------------------------------------===//
1769 
1770 /// Block declaration.
1771 ///
1772 ///   block ::= block-label? operation*
1773 ///   block-label    ::= block-id block-arg-list? `:`
1774 ///   block-id       ::= caret-id
1775 ///   block-arg-list ::= `(` ssa-id-and-type-list? `)`
1776 ///
1777 ParseResult OperationParser::parseBlock(Block *&block) {
1778   // The first block of a region may already exist, if it does the caret
1779   // identifier is optional.
1780   if (block && getToken().isNot(Token::caret_identifier))
1781     return parseBlockBody(block);
1782 
1783   SMLoc nameLoc = getToken().getLoc();
1784   auto name = getTokenSpelling();
1785   if (parseToken(Token::caret_identifier, "expected block name"))
1786     return failure();
1787 
1788   block = defineBlockNamed(name, nameLoc, block);
1789 
1790   // Fail if the block was already defined.
1791   if (!block)
1792     return emitError(nameLoc, "redefinition of block '") << name << "'";
1793 
1794   // If an argument list is present, parse it.
1795   if (consumeIf(Token::l_paren)) {
1796     if (parseOptionalBlockArgList(block) ||
1797         parseToken(Token::r_paren, "expected ')' to end argument list"))
1798       return failure();
1799   }
1800 
1801   if (parseToken(Token::colon, "expected ':' after block name"))
1802     return failure();
1803 
1804   return parseBlockBody(block);
1805 }
1806 
1807 ParseResult OperationParser::parseBlockBody(Block *block) {
1808   // Set the insertion point to the end of the block to parse.
1809   opBuilder.setInsertionPointToEnd(block);
1810 
1811   // Parse the list of operations that make up the body of the block.
1812   while (getToken().isNot(Token::caret_identifier, Token::r_brace))
1813     if (parseOperation())
1814       return failure();
1815 
1816   return success();
1817 }
1818 
1819 /// Get the block with the specified name, creating it if it doesn't already
1820 /// exist.  The location specified is the point of use, which allows
1821 /// us to diagnose references to blocks that are not defined precisely.
1822 Block *OperationParser::getBlockNamed(StringRef name, SMLoc loc) {
1823   BlockDefinition &blockDef = getBlockInfoByName(name);
1824   if (!blockDef.block) {
1825     blockDef = {new Block(), loc};
1826     insertForwardRef(blockDef.block, blockDef.loc);
1827   }
1828 
1829   // Populate the high level assembly state if necessary.
1830   if (state.asmState)
1831     state.asmState->addUses(blockDef.block, loc);
1832 
1833   return blockDef.block;
1834 }
1835 
1836 /// Define the block with the specified name. Returns the Block* or nullptr in
1837 /// the case of redefinition.
1838 Block *OperationParser::defineBlockNamed(StringRef name, SMLoc loc,
1839                                          Block *existing) {
1840   auto &blockAndLoc = getBlockInfoByName(name);
1841   blockAndLoc.loc = loc;
1842 
1843   // If a block has yet to be set, this is a new definition. If the caller
1844   // provided a block, use it. Otherwise create a new one.
1845   if (!blockAndLoc.block) {
1846     blockAndLoc.block = existing ? existing : new Block();
1847 
1848     // Otherwise, the block has a forward declaration. Forward declarations are
1849     // removed once defined, so if we are defining a existing block and it is
1850     // not a forward declaration, then it is a redeclaration.
1851   } else if (!eraseForwardRef(blockAndLoc.block)) {
1852     return nullptr;
1853   }
1854 
1855   // Populate the high level assembly state if necessary.
1856   if (state.asmState)
1857     state.asmState->addDefinition(blockAndLoc.block, loc);
1858 
1859   return blockAndLoc.block;
1860 }
1861 
1862 /// Parse a (possibly empty) list of SSA operands with types as block arguments.
1863 ///
1864 ///   ssa-id-and-type-list ::= ssa-id-and-type (`,` ssa-id-and-type)*
1865 ///
1866 ParseResult OperationParser::parseOptionalBlockArgList(Block *owner) {
1867   if (getToken().is(Token::r_brace))
1868     return success();
1869 
1870   // If the block already has arguments, then we're handling the entry block.
1871   // Parse and register the names for the arguments, but do not add them.
1872   bool definingExistingArgs = owner->getNumArguments() != 0;
1873   unsigned nextArgument = 0;
1874 
1875   return parseCommaSeparatedList([&]() -> ParseResult {
1876     return parseSSADefOrUseAndType(
1877         [&](SSAUseInfo useInfo, Type type) -> ParseResult {
1878           BlockArgument arg;
1879 
1880           // If we are defining existing arguments, ensure that the argument
1881           // has already been created with the right type.
1882           if (definingExistingArgs) {
1883             // Otherwise, ensure that this argument has already been created.
1884             if (nextArgument >= owner->getNumArguments())
1885               return emitError("too many arguments specified in argument list");
1886 
1887             // Finally, make sure the existing argument has the correct type.
1888             arg = owner->getArgument(nextArgument++);
1889             if (arg.getType() != type)
1890               return emitError("argument and block argument type mismatch");
1891           } else {
1892             auto loc = getEncodedSourceLocation(useInfo.loc);
1893             arg = owner->addArgument(type, loc);
1894           }
1895 
1896           // If the argument has an explicit loc(...) specifier, parse and apply
1897           // it.
1898           if (parseTrailingLocationSpecifier(arg))
1899             return failure();
1900 
1901           // Mark this block argument definition in the parser state if it was
1902           // provided.
1903           if (state.asmState)
1904             state.asmState->addDefinition(arg, useInfo.loc);
1905 
1906           return addDefinition(useInfo, arg);
1907         });
1908   });
1909 }
1910 
1911 //===----------------------------------------------------------------------===//
1912 // Top-level entity parsing.
1913 //===----------------------------------------------------------------------===//
1914 
1915 namespace {
1916 /// This parser handles entities that are only valid at the top level of the
1917 /// file.
1918 class TopLevelOperationParser : public Parser {
1919 public:
1920   explicit TopLevelOperationParser(ParserState &state) : Parser(state) {}
1921 
1922   /// Parse a set of operations into the end of the given Block.
1923   ParseResult parse(Block *topLevelBlock, Location parserLoc);
1924 
1925 private:
1926   /// Parse an attribute alias declaration.
1927   ParseResult parseAttributeAliasDef();
1928 
1929   /// Parse an attribute alias declaration.
1930   ParseResult parseTypeAliasDef();
1931 };
1932 } // end anonymous namespace
1933 
1934 /// Parses an attribute alias declaration.
1935 ///
1936 ///   attribute-alias-def ::= '#' alias-name `=` attribute-value
1937 ///
1938 ParseResult TopLevelOperationParser::parseAttributeAliasDef() {
1939   assert(getToken().is(Token::hash_identifier));
1940   StringRef aliasName = getTokenSpelling().drop_front();
1941 
1942   // Check for redefinitions.
1943   if (state.symbols.attributeAliasDefinitions.count(aliasName) > 0)
1944     return emitError("redefinition of attribute alias id '" + aliasName + "'");
1945 
1946   // Make sure this isn't invading the dialect attribute namespace.
1947   if (aliasName.contains('.'))
1948     return emitError("attribute names with a '.' are reserved for "
1949                      "dialect-defined names");
1950 
1951   consumeToken(Token::hash_identifier);
1952 
1953   // Parse the '='.
1954   if (parseToken(Token::equal, "expected '=' in attribute alias definition"))
1955     return failure();
1956 
1957   // Parse the attribute value.
1958   Attribute attr = parseAttribute();
1959   if (!attr)
1960     return failure();
1961 
1962   state.symbols.attributeAliasDefinitions[aliasName] = attr;
1963   return success();
1964 }
1965 
1966 /// Parse a type alias declaration.
1967 ///
1968 ///   type-alias-def ::= '!' alias-name `=` 'type' type
1969 ///
1970 ParseResult TopLevelOperationParser::parseTypeAliasDef() {
1971   assert(getToken().is(Token::exclamation_identifier));
1972   StringRef aliasName = getTokenSpelling().drop_front();
1973 
1974   // Check for redefinitions.
1975   if (state.symbols.typeAliasDefinitions.count(aliasName) > 0)
1976     return emitError("redefinition of type alias id '" + aliasName + "'");
1977 
1978   // Make sure this isn't invading the dialect type namespace.
1979   if (aliasName.contains('.'))
1980     return emitError("type names with a '.' are reserved for "
1981                      "dialect-defined names");
1982 
1983   consumeToken(Token::exclamation_identifier);
1984 
1985   // Parse the '=' and 'type'.
1986   if (parseToken(Token::equal, "expected '=' in type alias definition") ||
1987       parseToken(Token::kw_type, "expected 'type' in type alias definition"))
1988     return failure();
1989 
1990   // Parse the type.
1991   Type aliasedType = parseType();
1992   if (!aliasedType)
1993     return failure();
1994 
1995   // Register this alias with the parser state.
1996   state.symbols.typeAliasDefinitions.try_emplace(aliasName, aliasedType);
1997   return success();
1998 }
1999 
2000 ParseResult TopLevelOperationParser::parse(Block *topLevelBlock,
2001                                            Location parserLoc) {
2002   // Create a top-level operation to contain the parsed state.
2003   OwningOpRef<ModuleOp> topLevelOp(ModuleOp::create(parserLoc));
2004   OperationParser opParser(state, topLevelOp.get());
2005   while (true) {
2006     switch (getToken().getKind()) {
2007     default:
2008       // Parse a top-level operation.
2009       if (opParser.parseOperation())
2010         return failure();
2011       break;
2012 
2013     // If we got to the end of the file, then we're done.
2014     case Token::eof: {
2015       if (opParser.finalize())
2016         return failure();
2017 
2018       // Splice the blocks of the parsed operation over to the provided
2019       // top-level block.
2020       auto &parsedOps = topLevelOp->getBody()->getOperations();
2021       auto &destOps = topLevelBlock->getOperations();
2022       destOps.splice(destOps.empty() ? destOps.end() : std::prev(destOps.end()),
2023                      parsedOps, parsedOps.begin(), parsedOps.end());
2024       return success();
2025     }
2026 
2027     // If we got an error token, then the lexer already emitted an error, just
2028     // stop.  Someday we could introduce error recovery if there was demand
2029     // for it.
2030     case Token::error:
2031       return failure();
2032 
2033     // Parse an attribute alias.
2034     case Token::hash_identifier:
2035       if (parseAttributeAliasDef())
2036         return failure();
2037       break;
2038 
2039     // Parse a type alias.
2040     case Token::exclamation_identifier:
2041       if (parseTypeAliasDef())
2042         return failure();
2043       break;
2044     }
2045   }
2046 }
2047 
2048 //===----------------------------------------------------------------------===//
2049 
2050 LogicalResult mlir::parseSourceFile(const llvm::SourceMgr &sourceMgr,
2051                                     Block *block, MLIRContext *context,
2052                                     LocationAttr *sourceFileLoc,
2053                                     AsmParserState *asmState) {
2054   const auto *sourceBuf = sourceMgr.getMemoryBuffer(sourceMgr.getMainFileID());
2055 
2056   Location parserLoc = FileLineColLoc::get(
2057       context, sourceBuf->getBufferIdentifier(), /*line=*/0, /*column=*/0);
2058   if (sourceFileLoc)
2059     *sourceFileLoc = parserLoc;
2060 
2061   SymbolState aliasState;
2062   ParserState state(sourceMgr, context, aliasState, asmState);
2063   return TopLevelOperationParser(state).parse(block, parserLoc);
2064 }
2065 
2066 LogicalResult mlir::parseSourceFile(llvm::StringRef filename, Block *block,
2067                                     MLIRContext *context,
2068                                     LocationAttr *sourceFileLoc) {
2069   llvm::SourceMgr sourceMgr;
2070   return parseSourceFile(filename, sourceMgr, block, context, sourceFileLoc);
2071 }
2072 
2073 LogicalResult mlir::parseSourceFile(llvm::StringRef filename,
2074                                     llvm::SourceMgr &sourceMgr, Block *block,
2075                                     MLIRContext *context,
2076                                     LocationAttr *sourceFileLoc,
2077                                     AsmParserState *asmState) {
2078   if (sourceMgr.getNumBuffers() != 0) {
2079     // TODO: Extend to support multiple buffers.
2080     return emitError(mlir::UnknownLoc::get(context),
2081                      "only main buffer parsed at the moment");
2082   }
2083   auto fileOrErr = llvm::MemoryBuffer::getFileOrSTDIN(filename);
2084   if (std::error_code error = fileOrErr.getError())
2085     return emitError(mlir::UnknownLoc::get(context),
2086                      "could not open input file " + filename);
2087 
2088   // Load the MLIR source file.
2089   sourceMgr.AddNewSourceBuffer(std::move(*fileOrErr), llvm::SMLoc());
2090   return parseSourceFile(sourceMgr, block, context, sourceFileLoc, asmState);
2091 }
2092 
2093 LogicalResult mlir::parseSourceString(llvm::StringRef sourceStr, Block *block,
2094                                       MLIRContext *context,
2095                                       LocationAttr *sourceFileLoc) {
2096   auto memBuffer = MemoryBuffer::getMemBuffer(sourceStr);
2097   if (!memBuffer)
2098     return failure();
2099 
2100   SourceMgr sourceMgr;
2101   sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc());
2102   return parseSourceFile(sourceMgr, block, context, sourceFileLoc);
2103 }
2104