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