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