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 "mlir/Parser.h" 14 #include "Lexer.h" 15 #include "mlir/Analysis/Verifier.h" 16 #include "mlir/IR/AffineExpr.h" 17 #include "mlir/IR/AffineMap.h" 18 #include "mlir/IR/Attributes.h" 19 #include "mlir/IR/Builders.h" 20 #include "mlir/IR/Dialect.h" 21 #include "mlir/IR/DialectImplementation.h" 22 #include "mlir/IR/IntegerSet.h" 23 #include "mlir/IR/Location.h" 24 #include "mlir/IR/MLIRContext.h" 25 #include "mlir/IR/Module.h" 26 #include "mlir/IR/OpImplementation.h" 27 #include "mlir/IR/StandardTypes.h" 28 #include "mlir/Support/STLExtras.h" 29 #include "llvm/ADT/APInt.h" 30 #include "llvm/ADT/DenseMap.h" 31 #include "llvm/ADT/StringExtras.h" 32 #include "llvm/ADT/StringSet.h" 33 #include "llvm/ADT/bit.h" 34 #include "llvm/Support/PrettyStackTrace.h" 35 #include "llvm/Support/SMLoc.h" 36 #include "llvm/Support/SourceMgr.h" 37 #include <algorithm> 38 using namespace mlir; 39 using llvm::MemoryBuffer; 40 using llvm::SMLoc; 41 using llvm::SourceMgr; 42 43 namespace { 44 class Parser; 45 46 //===----------------------------------------------------------------------===// 47 // SymbolState 48 //===----------------------------------------------------------------------===// 49 50 /// This class contains record of any parsed top-level symbols. 51 struct SymbolState { 52 // A map from attribute alias identifier to Attribute. 53 llvm::StringMap<Attribute> attributeAliasDefinitions; 54 55 // A map from type alias identifier to Type. 56 llvm::StringMap<Type> typeAliasDefinitions; 57 58 /// A set of locations into the main parser memory buffer for each of the 59 /// active nested parsers. Given that some nested parsers, i.e. custom dialect 60 /// parsers, operate on a temporary memory buffer, this provides an anchor 61 /// point for emitting diagnostics. 62 SmallVector<llvm::SMLoc, 1> nestedParserLocs; 63 64 /// The top-level lexer that contains the original memory buffer provided by 65 /// the user. This is used by nested parsers to get a properly encoded source 66 /// location. 67 Lexer *topLevelLexer = nullptr; 68 }; 69 70 //===----------------------------------------------------------------------===// 71 // ParserState 72 //===----------------------------------------------------------------------===// 73 74 /// This class refers to all of the state maintained globally by the parser, 75 /// such as the current lexer position etc. 76 struct ParserState { 77 ParserState(const llvm::SourceMgr &sourceMgr, MLIRContext *ctx, 78 SymbolState &symbols) 79 : context(ctx), lex(sourceMgr, ctx), curToken(lex.lexToken()), 80 symbols(symbols), parserDepth(symbols.nestedParserLocs.size()) { 81 // Set the top level lexer for the symbol state if one doesn't exist. 82 if (!symbols.topLevelLexer) 83 symbols.topLevelLexer = &lex; 84 } 85 ~ParserState() { 86 // Reset the top level lexer if it refers the lexer in our state. 87 if (symbols.topLevelLexer == &lex) 88 symbols.topLevelLexer = nullptr; 89 } 90 ParserState(const ParserState &) = delete; 91 void operator=(const ParserState &) = delete; 92 93 /// The context we're parsing into. 94 MLIRContext *const context; 95 96 /// The lexer for the source file we're parsing. 97 Lexer lex; 98 99 /// This is the next token that hasn't been consumed yet. 100 Token curToken; 101 102 /// The current state for symbol parsing. 103 SymbolState &symbols; 104 105 /// The depth of this parser in the nested parsing stack. 106 size_t parserDepth; 107 }; 108 109 //===----------------------------------------------------------------------===// 110 // Parser 111 //===----------------------------------------------------------------------===// 112 113 /// This class implement support for parsing global entities like types and 114 /// shared entities like SSA names. It is intended to be subclassed by 115 /// specialized subparsers that include state, e.g. when a local symbol table. 116 class Parser { 117 public: 118 Builder builder; 119 120 Parser(ParserState &state) : builder(state.context), state(state) {} 121 122 // Helper methods to get stuff from the parser-global state. 123 ParserState &getState() const { return state; } 124 MLIRContext *getContext() const { return state.context; } 125 const llvm::SourceMgr &getSourceMgr() { return state.lex.getSourceMgr(); } 126 127 /// Parse a comma-separated list of elements up until the specified end token. 128 ParseResult 129 parseCommaSeparatedListUntil(Token::Kind rightToken, 130 const std::function<ParseResult()> &parseElement, 131 bool allowEmptyList = true); 132 133 /// Parse a comma separated list of elements that must have at least one entry 134 /// in it. 135 ParseResult 136 parseCommaSeparatedList(const std::function<ParseResult()> &parseElement); 137 138 ParseResult parsePrettyDialectSymbolName(StringRef &prettyName); 139 140 // We have two forms of parsing methods - those that return a non-null 141 // pointer on success, and those that return a ParseResult to indicate whether 142 // they returned a failure. The second class fills in by-reference arguments 143 // as the results of their action. 144 145 //===--------------------------------------------------------------------===// 146 // Error Handling 147 //===--------------------------------------------------------------------===// 148 149 /// Emit an error and return failure. 150 InFlightDiagnostic emitError(const Twine &message = {}) { 151 return emitError(state.curToken.getLoc(), message); 152 } 153 InFlightDiagnostic emitError(SMLoc loc, const Twine &message = {}); 154 155 /// Encode the specified source location information into an attribute for 156 /// attachment to the IR. 157 Location getEncodedSourceLocation(llvm::SMLoc loc) { 158 // If there are no active nested parsers, we can get the encoded source 159 // location directly. 160 if (state.parserDepth == 0) 161 return state.lex.getEncodedSourceLocation(loc); 162 // Otherwise, we need to re-encode it to point to the top level buffer. 163 return state.symbols.topLevelLexer->getEncodedSourceLocation( 164 remapLocationToTopLevelBuffer(loc)); 165 } 166 167 /// Remaps the given SMLoc to the top level lexer of the parser. This is used 168 /// to adjust locations of potentially nested parsers to ensure that they can 169 /// be emitted properly as diagnostics. 170 llvm::SMLoc remapLocationToTopLevelBuffer(llvm::SMLoc loc) { 171 // If there are no active nested parsers, we can return location directly. 172 SymbolState &symbols = state.symbols; 173 if (state.parserDepth == 0) 174 return loc; 175 assert(symbols.topLevelLexer && "expected valid top-level lexer"); 176 177 // Otherwise, we need to remap the location to the main parser. This is 178 // simply offseting the location onto the location of the last nested 179 // parser. 180 size_t offset = loc.getPointer() - state.lex.getBufferBegin(); 181 auto *rawLoc = 182 symbols.nestedParserLocs[state.parserDepth - 1].getPointer() + offset; 183 return llvm::SMLoc::getFromPointer(rawLoc); 184 } 185 186 //===--------------------------------------------------------------------===// 187 // Token Parsing 188 //===--------------------------------------------------------------------===// 189 190 /// Return the current token the parser is inspecting. 191 const Token &getToken() const { return state.curToken; } 192 StringRef getTokenSpelling() const { return state.curToken.getSpelling(); } 193 194 /// If the current token has the specified kind, consume it and return true. 195 /// If not, return false. 196 bool consumeIf(Token::Kind kind) { 197 if (state.curToken.isNot(kind)) 198 return false; 199 consumeToken(kind); 200 return true; 201 } 202 203 /// Advance the current lexer onto the next token. 204 void consumeToken() { 205 assert(state.curToken.isNot(Token::eof, Token::error) && 206 "shouldn't advance past EOF or errors"); 207 state.curToken = state.lex.lexToken(); 208 } 209 210 /// Advance the current lexer onto the next token, asserting what the expected 211 /// current token is. This is preferred to the above method because it leads 212 /// to more self-documenting code with better checking. 213 void consumeToken(Token::Kind kind) { 214 assert(state.curToken.is(kind) && "consumed an unexpected token"); 215 consumeToken(); 216 } 217 218 /// Consume the specified token if present and return success. On failure, 219 /// output a diagnostic and return failure. 220 ParseResult parseToken(Token::Kind expectedToken, const Twine &message); 221 222 //===--------------------------------------------------------------------===// 223 // Type Parsing 224 //===--------------------------------------------------------------------===// 225 226 ParseResult parseFunctionResultTypes(SmallVectorImpl<Type> &elements); 227 ParseResult parseTypeListNoParens(SmallVectorImpl<Type> &elements); 228 ParseResult parseTypeListParens(SmallVectorImpl<Type> &elements); 229 230 /// Parse an arbitrary type. 231 Type parseType(); 232 233 /// Parse a complex type. 234 Type parseComplexType(); 235 236 /// Parse an extended type. 237 Type parseExtendedType(); 238 239 /// Parse a function type. 240 Type parseFunctionType(); 241 242 /// Parse a memref type. 243 Type parseMemRefType(); 244 245 /// Parse a non function type. 246 Type parseNonFunctionType(); 247 248 /// Parse a tensor type. 249 Type parseTensorType(); 250 251 /// Parse a tuple type. 252 Type parseTupleType(); 253 254 /// Parse a vector type. 255 VectorType parseVectorType(); 256 ParseResult parseDimensionListRanked(SmallVectorImpl<int64_t> &dimensions, 257 bool allowDynamic = true); 258 ParseResult parseXInDimensionList(); 259 260 /// Parse strided layout specification. 261 ParseResult parseStridedLayout(int64_t &offset, 262 SmallVectorImpl<int64_t> &strides); 263 264 // Parse a brace-delimiter list of comma-separated integers with `?` as an 265 // unknown marker. 266 ParseResult parseStrideList(SmallVectorImpl<int64_t> &dimensions); 267 268 //===--------------------------------------------------------------------===// 269 // Attribute Parsing 270 //===--------------------------------------------------------------------===// 271 272 /// Parse an arbitrary attribute with an optional type. 273 Attribute parseAttribute(Type type = {}); 274 275 /// Parse an attribute dictionary. 276 ParseResult parseAttributeDict(SmallVectorImpl<NamedAttribute> &attributes); 277 278 /// Parse an extended attribute. 279 Attribute parseExtendedAttr(Type type); 280 281 /// Parse a float attribute. 282 Attribute parseFloatAttr(Type type, bool isNegative); 283 284 /// Parse a decimal or a hexadecimal literal, which can be either an integer 285 /// or a float attribute. 286 Attribute parseDecOrHexAttr(Type type, bool isNegative); 287 288 /// Parse an opaque elements attribute. 289 Attribute parseOpaqueElementsAttr(Type attrType); 290 291 /// Parse a dense elements attribute. 292 Attribute parseDenseElementsAttr(Type attrType); 293 ShapedType parseElementsLiteralType(Type type); 294 295 /// Parse a sparse elements attribute. 296 Attribute parseSparseElementsAttr(Type attrType); 297 298 //===--------------------------------------------------------------------===// 299 // Location Parsing 300 //===--------------------------------------------------------------------===// 301 302 /// Parse an inline location. 303 ParseResult parseLocation(LocationAttr &loc); 304 305 /// Parse a raw location instance. 306 ParseResult parseLocationInstance(LocationAttr &loc); 307 308 /// Parse a callsite location instance. 309 ParseResult parseCallSiteLocation(LocationAttr &loc); 310 311 /// Parse a fused location instance. 312 ParseResult parseFusedLocation(LocationAttr &loc); 313 314 /// Parse a name or FileLineCol location instance. 315 ParseResult parseNameOrFileLineColLocation(LocationAttr &loc); 316 317 /// Parse an optional trailing location. 318 /// 319 /// trailing-location ::= (`loc` `(` location `)`)? 320 /// 321 ParseResult parseOptionalTrailingLocation(Location &loc) { 322 // If there is a 'loc' we parse a trailing location. 323 if (!getToken().is(Token::kw_loc)) 324 return success(); 325 326 // Parse the location. 327 LocationAttr directLoc; 328 if (parseLocation(directLoc)) 329 return failure(); 330 loc = directLoc; 331 return success(); 332 } 333 334 //===--------------------------------------------------------------------===// 335 // Affine Parsing 336 //===--------------------------------------------------------------------===// 337 338 /// Parse a reference to either an affine map, or an integer set. 339 ParseResult parseAffineMapOrIntegerSetReference(AffineMap &map, 340 IntegerSet &set); 341 ParseResult parseAffineMapReference(AffineMap &map); 342 ParseResult parseIntegerSetReference(IntegerSet &set); 343 344 /// Parse an AffineMap where the dim and symbol identifiers are SSA ids. 345 ParseResult 346 parseAffineMapOfSSAIds(AffineMap &map, 347 function_ref<ParseResult(bool)> parseElement, 348 OpAsmParser::Delimiter delimiter); 349 350 private: 351 /// The Parser is subclassed and reinstantiated. Do not add additional 352 /// non-trivial state here, add it to the ParserState class. 353 ParserState &state; 354 }; 355 } // end anonymous namespace 356 357 //===----------------------------------------------------------------------===// 358 // Helper methods. 359 //===----------------------------------------------------------------------===// 360 361 /// Parse a comma separated list of elements that must have at least one entry 362 /// in it. 363 ParseResult Parser::parseCommaSeparatedList( 364 const std::function<ParseResult()> &parseElement) { 365 // Non-empty case starts with an element. 366 if (parseElement()) 367 return failure(); 368 369 // Otherwise we have a list of comma separated elements. 370 while (consumeIf(Token::comma)) { 371 if (parseElement()) 372 return failure(); 373 } 374 return success(); 375 } 376 377 /// Parse a comma-separated list of elements, terminated with an arbitrary 378 /// token. This allows empty lists if allowEmptyList is true. 379 /// 380 /// abstract-list ::= rightToken // if allowEmptyList == true 381 /// abstract-list ::= element (',' element)* rightToken 382 /// 383 ParseResult Parser::parseCommaSeparatedListUntil( 384 Token::Kind rightToken, const std::function<ParseResult()> &parseElement, 385 bool allowEmptyList) { 386 // Handle the empty case. 387 if (getToken().is(rightToken)) { 388 if (!allowEmptyList) 389 return emitError("expected list element"); 390 consumeToken(rightToken); 391 return success(); 392 } 393 394 if (parseCommaSeparatedList(parseElement) || 395 parseToken(rightToken, "expected ',' or '" + 396 Token::getTokenSpelling(rightToken) + "'")) 397 return failure(); 398 399 return success(); 400 } 401 402 //===----------------------------------------------------------------------===// 403 // DialectAsmParser 404 //===----------------------------------------------------------------------===// 405 406 namespace { 407 /// This class provides the main implementation of the DialectAsmParser that 408 /// allows for dialects to parse attributes and types. This allows for dialect 409 /// hooking into the main MLIR parsing logic. 410 class CustomDialectAsmParser : public DialectAsmParser { 411 public: 412 CustomDialectAsmParser(StringRef fullSpec, Parser &parser) 413 : fullSpec(fullSpec), nameLoc(parser.getToken().getLoc()), 414 parser(parser) {} 415 ~CustomDialectAsmParser() override {} 416 417 /// Emit a diagnostic at the specified location and return failure. 418 InFlightDiagnostic emitError(llvm::SMLoc loc, const Twine &message) override { 419 return parser.emitError(loc, message); 420 } 421 422 /// Return a builder which provides useful access to MLIRContext, global 423 /// objects like types and attributes. 424 Builder &getBuilder() const override { return parser.builder; } 425 426 /// Get the location of the next token and store it into the argument. This 427 /// always succeeds. 428 llvm::SMLoc getCurrentLocation() override { 429 return parser.getToken().getLoc(); 430 } 431 432 /// Return the location of the original name token. 433 llvm::SMLoc getNameLoc() const override { return nameLoc; } 434 435 /// Re-encode the given source location as an MLIR location and return it. 436 Location getEncodedSourceLoc(llvm::SMLoc loc) override { 437 return parser.getEncodedSourceLocation(loc); 438 } 439 440 /// Returns the full specification of the symbol being parsed. This allows 441 /// for using a separate parser if necessary. 442 StringRef getFullSymbolSpec() const override { return fullSpec; } 443 444 /// Parse a floating point value from the stream. 445 ParseResult parseFloat(double &result) override { 446 bool negative = parser.consumeIf(Token::minus); 447 Token curTok = parser.getToken(); 448 449 // Check for a floating point value. 450 if (curTok.is(Token::floatliteral)) { 451 auto val = curTok.getFloatingPointValue(); 452 if (!val.hasValue()) 453 return emitError(curTok.getLoc(), "floating point value too large"); 454 parser.consumeToken(Token::floatliteral); 455 result = negative ? -*val : *val; 456 return success(); 457 } 458 459 // TODO(riverriddle) support hex floating point values. 460 return emitError(getCurrentLocation(), "expected floating point literal"); 461 } 462 463 /// Parse an optional integer value from the stream. 464 OptionalParseResult parseOptionalInteger(uint64_t &result) override { 465 Token curToken = parser.getToken(); 466 if (curToken.isNot(Token::integer, Token::minus)) 467 return llvm::None; 468 469 bool negative = parser.consumeIf(Token::minus); 470 Token curTok = parser.getToken(); 471 if (parser.parseToken(Token::integer, "expected integer value")) 472 return failure(); 473 474 auto val = curTok.getUInt64IntegerValue(); 475 if (!val) 476 return emitError(curTok.getLoc(), "integer value too large"); 477 result = negative ? -*val : *val; 478 return success(); 479 } 480 481 //===--------------------------------------------------------------------===// 482 // Token Parsing 483 //===--------------------------------------------------------------------===// 484 485 /// Parse a `->` token. 486 ParseResult parseArrow() override { 487 return parser.parseToken(Token::arrow, "expected '->'"); 488 } 489 490 /// Parses a `->` if present. 491 ParseResult parseOptionalArrow() override { 492 return success(parser.consumeIf(Token::arrow)); 493 } 494 495 /// Parse a '{' token. 496 ParseResult parseLBrace() override { 497 return parser.parseToken(Token::l_brace, "expected '{'"); 498 } 499 500 /// Parse a '{' token if present 501 ParseResult parseOptionalLBrace() override { 502 return success(parser.consumeIf(Token::l_brace)); 503 } 504 505 /// Parse a `}` token. 506 ParseResult parseRBrace() override { 507 return parser.parseToken(Token::r_brace, "expected '}'"); 508 } 509 510 /// Parse a `}` token if present 511 ParseResult parseOptionalRBrace() override { 512 return success(parser.consumeIf(Token::r_brace)); 513 } 514 515 /// Parse a `:` token. 516 ParseResult parseColon() override { 517 return parser.parseToken(Token::colon, "expected ':'"); 518 } 519 520 /// Parse a `:` token if present. 521 ParseResult parseOptionalColon() override { 522 return success(parser.consumeIf(Token::colon)); 523 } 524 525 /// Parse a `,` token. 526 ParseResult parseComma() override { 527 return parser.parseToken(Token::comma, "expected ','"); 528 } 529 530 /// Parse a `,` token if present. 531 ParseResult parseOptionalComma() override { 532 return success(parser.consumeIf(Token::comma)); 533 } 534 535 /// Parses a `...` if present. 536 ParseResult parseOptionalEllipsis() override { 537 return success(parser.consumeIf(Token::ellipsis)); 538 } 539 540 /// Parse a `=` token. 541 ParseResult parseEqual() override { 542 return parser.parseToken(Token::equal, "expected '='"); 543 } 544 545 /// Parse a '<' token. 546 ParseResult parseLess() override { 547 return parser.parseToken(Token::less, "expected '<'"); 548 } 549 550 /// Parse a `<` token if present. 551 ParseResult parseOptionalLess() override { 552 return success(parser.consumeIf(Token::less)); 553 } 554 555 /// Parse a '>' token. 556 ParseResult parseGreater() override { 557 return parser.parseToken(Token::greater, "expected '>'"); 558 } 559 560 /// Parse a `>` token if present. 561 ParseResult parseOptionalGreater() override { 562 return success(parser.consumeIf(Token::greater)); 563 } 564 565 /// Parse a `(` token. 566 ParseResult parseLParen() override { 567 return parser.parseToken(Token::l_paren, "expected '('"); 568 } 569 570 /// Parses a '(' if present. 571 ParseResult parseOptionalLParen() override { 572 return success(parser.consumeIf(Token::l_paren)); 573 } 574 575 /// Parse a `)` token. 576 ParseResult parseRParen() override { 577 return parser.parseToken(Token::r_paren, "expected ')'"); 578 } 579 580 /// Parses a ')' if present. 581 ParseResult parseOptionalRParen() override { 582 return success(parser.consumeIf(Token::r_paren)); 583 } 584 585 /// Parse a `[` token. 586 ParseResult parseLSquare() override { 587 return parser.parseToken(Token::l_square, "expected '['"); 588 } 589 590 /// Parses a '[' if present. 591 ParseResult parseOptionalLSquare() override { 592 return success(parser.consumeIf(Token::l_square)); 593 } 594 595 /// Parse a `]` token. 596 ParseResult parseRSquare() override { 597 return parser.parseToken(Token::r_square, "expected ']'"); 598 } 599 600 /// Parses a ']' if present. 601 ParseResult parseOptionalRSquare() override { 602 return success(parser.consumeIf(Token::r_square)); 603 } 604 605 /// Parses a '?' if present. 606 ParseResult parseOptionalQuestion() override { 607 return success(parser.consumeIf(Token::question)); 608 } 609 610 /// Parses a '*' if present. 611 ParseResult parseOptionalStar() override { 612 return success(parser.consumeIf(Token::star)); 613 } 614 615 /// Returns if the current token corresponds to a keyword. 616 bool isCurrentTokenAKeyword() const { 617 return parser.getToken().is(Token::bare_identifier) || 618 parser.getToken().isKeyword(); 619 } 620 621 /// Parse the given keyword if present. 622 ParseResult parseOptionalKeyword(StringRef keyword) override { 623 // Check that the current token has the same spelling. 624 if (!isCurrentTokenAKeyword() || parser.getTokenSpelling() != keyword) 625 return failure(); 626 parser.consumeToken(); 627 return success(); 628 } 629 630 /// Parse a keyword, if present, into 'keyword'. 631 ParseResult parseOptionalKeyword(StringRef *keyword) override { 632 // Check that the current token is a keyword. 633 if (!isCurrentTokenAKeyword()) 634 return failure(); 635 636 *keyword = parser.getTokenSpelling(); 637 parser.consumeToken(); 638 return success(); 639 } 640 641 //===--------------------------------------------------------------------===// 642 // Attribute Parsing 643 //===--------------------------------------------------------------------===// 644 645 /// Parse an arbitrary attribute and return it in result. 646 ParseResult parseAttribute(Attribute &result, Type type) override { 647 result = parser.parseAttribute(type); 648 return success(static_cast<bool>(result)); 649 } 650 651 /// Parse an affine map instance into 'map'. 652 ParseResult parseAffineMap(AffineMap &map) override { 653 return parser.parseAffineMapReference(map); 654 } 655 656 /// Parse an integer set instance into 'set'. 657 ParseResult printIntegerSet(IntegerSet &set) override { 658 return parser.parseIntegerSetReference(set); 659 } 660 661 //===--------------------------------------------------------------------===// 662 // Type Parsing 663 //===--------------------------------------------------------------------===// 664 665 ParseResult parseType(Type &result) override { 666 result = parser.parseType(); 667 return success(static_cast<bool>(result)); 668 } 669 670 ParseResult parseDimensionList(SmallVectorImpl<int64_t> &dimensions, 671 bool allowDynamic) override { 672 return parser.parseDimensionListRanked(dimensions, allowDynamic); 673 } 674 675 private: 676 /// The full symbol specification. 677 StringRef fullSpec; 678 679 /// The source location of the dialect symbol. 680 SMLoc nameLoc; 681 682 /// The main parser. 683 Parser &parser; 684 }; 685 } // namespace 686 687 /// Parse the body of a pretty dialect symbol, which starts and ends with <>'s, 688 /// and may be recursive. Return with the 'prettyName' StringRef encompassing 689 /// the entire pretty name. 690 /// 691 /// pretty-dialect-sym-body ::= '<' pretty-dialect-sym-contents+ '>' 692 /// pretty-dialect-sym-contents ::= pretty-dialect-sym-body 693 /// | '(' pretty-dialect-sym-contents+ ')' 694 /// | '[' pretty-dialect-sym-contents+ ']' 695 /// | '{' pretty-dialect-sym-contents+ '}' 696 /// | '[^[<({>\])}\0]+' 697 /// 698 ParseResult Parser::parsePrettyDialectSymbolName(StringRef &prettyName) { 699 // Pretty symbol names are a relatively unstructured format that contains a 700 // series of properly nested punctuation, with anything else in the middle. 701 // Scan ahead to find it and consume it if successful, otherwise emit an 702 // error. 703 auto *curPtr = getTokenSpelling().data(); 704 705 SmallVector<char, 8> nestedPunctuation; 706 707 // Scan over the nested punctuation, bailing out on error and consuming until 708 // we find the end. We know that we're currently looking at the '<', so we 709 // can go until we find the matching '>' character. 710 assert(*curPtr == '<'); 711 do { 712 char c = *curPtr++; 713 switch (c) { 714 case '\0': 715 // This also handles the EOF case. 716 return emitError("unexpected nul or EOF in pretty dialect name"); 717 case '<': 718 case '[': 719 case '(': 720 case '{': 721 nestedPunctuation.push_back(c); 722 continue; 723 724 case '-': 725 // The sequence `->` is treated as special token. 726 if (*curPtr == '>') 727 ++curPtr; 728 continue; 729 730 case '>': 731 if (nestedPunctuation.pop_back_val() != '<') 732 return emitError("unbalanced '>' character in pretty dialect name"); 733 break; 734 case ']': 735 if (nestedPunctuation.pop_back_val() != '[') 736 return emitError("unbalanced ']' character in pretty dialect name"); 737 break; 738 case ')': 739 if (nestedPunctuation.pop_back_val() != '(') 740 return emitError("unbalanced ')' character in pretty dialect name"); 741 break; 742 case '}': 743 if (nestedPunctuation.pop_back_val() != '{') 744 return emitError("unbalanced '}' character in pretty dialect name"); 745 break; 746 747 default: 748 continue; 749 } 750 } while (!nestedPunctuation.empty()); 751 752 // Ok, we succeeded, remember where we stopped, reset the lexer to know it is 753 // consuming all this stuff, and return. 754 state.lex.resetPointer(curPtr); 755 756 unsigned length = curPtr - prettyName.begin(); 757 prettyName = StringRef(prettyName.begin(), length); 758 consumeToken(); 759 return success(); 760 } 761 762 /// Parse an extended dialect symbol. 763 template <typename Symbol, typename SymbolAliasMap, typename CreateFn> 764 static Symbol parseExtendedSymbol(Parser &p, Token::Kind identifierTok, 765 SymbolAliasMap &aliases, 766 CreateFn &&createSymbol) { 767 // Parse the dialect namespace. 768 StringRef identifier = p.getTokenSpelling().drop_front(); 769 auto loc = p.getToken().getLoc(); 770 p.consumeToken(identifierTok); 771 772 // If there is no '<' token following this, and if the typename contains no 773 // dot, then we are parsing a symbol alias. 774 if (p.getToken().isNot(Token::less) && !identifier.contains('.')) { 775 // Check for an alias for this type. 776 auto aliasIt = aliases.find(identifier); 777 if (aliasIt == aliases.end()) 778 return (p.emitError("undefined symbol alias id '" + identifier + "'"), 779 nullptr); 780 return aliasIt->second; 781 } 782 783 // Otherwise, we are parsing a dialect-specific symbol. If the name contains 784 // a dot, then this is the "pretty" form. If not, it is the verbose form that 785 // looks like <"...">. 786 std::string symbolData; 787 auto dialectName = identifier; 788 789 // Handle the verbose form, where "identifier" is a simple dialect name. 790 if (!identifier.contains('.')) { 791 // Consume the '<'. 792 if (p.parseToken(Token::less, "expected '<' in dialect type")) 793 return nullptr; 794 795 // Parse the symbol specific data. 796 if (p.getToken().isNot(Token::string)) 797 return (p.emitError("expected string literal data in dialect symbol"), 798 nullptr); 799 symbolData = p.getToken().getStringValue(); 800 loc = llvm::SMLoc::getFromPointer(p.getToken().getLoc().getPointer() + 1); 801 p.consumeToken(Token::string); 802 803 // Consume the '>'. 804 if (p.parseToken(Token::greater, "expected '>' in dialect symbol")) 805 return nullptr; 806 } else { 807 // Ok, the dialect name is the part of the identifier before the dot, the 808 // part after the dot is the dialect's symbol, or the start thereof. 809 auto dotHalves = identifier.split('.'); 810 dialectName = dotHalves.first; 811 auto prettyName = dotHalves.second; 812 loc = llvm::SMLoc::getFromPointer(prettyName.data()); 813 814 // If the dialect's symbol is followed immediately by a <, then lex the body 815 // of it into prettyName. 816 if (p.getToken().is(Token::less) && 817 prettyName.bytes_end() == p.getTokenSpelling().bytes_begin()) { 818 if (p.parsePrettyDialectSymbolName(prettyName)) 819 return nullptr; 820 } 821 822 symbolData = prettyName.str(); 823 } 824 825 // Record the name location of the type remapped to the top level buffer. 826 llvm::SMLoc locInTopLevelBuffer = p.remapLocationToTopLevelBuffer(loc); 827 p.getState().symbols.nestedParserLocs.push_back(locInTopLevelBuffer); 828 829 // Call into the provided symbol construction function. 830 Symbol sym = createSymbol(dialectName, symbolData, loc); 831 832 // Pop the last parser location. 833 p.getState().symbols.nestedParserLocs.pop_back(); 834 return sym; 835 } 836 837 /// Parses a symbol, of type 'T', and returns it if parsing was successful. If 838 /// parsing failed, nullptr is returned. The number of bytes read from the input 839 /// string is returned in 'numRead'. 840 template <typename T, typename ParserFn> 841 static T parseSymbol(StringRef inputStr, MLIRContext *context, 842 SymbolState &symbolState, ParserFn &&parserFn, 843 size_t *numRead = nullptr) { 844 SourceMgr sourceMgr; 845 auto memBuffer = MemoryBuffer::getMemBuffer( 846 inputStr, /*BufferName=*/"<mlir_parser_buffer>", 847 /*RequiresNullTerminator=*/false); 848 sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc()); 849 ParserState state(sourceMgr, context, symbolState); 850 Parser parser(state); 851 852 Token startTok = parser.getToken(); 853 T symbol = parserFn(parser); 854 if (!symbol) 855 return T(); 856 857 // If 'numRead' is valid, then provide the number of bytes that were read. 858 Token endTok = parser.getToken(); 859 if (numRead) { 860 *numRead = static_cast<size_t>(endTok.getLoc().getPointer() - 861 startTok.getLoc().getPointer()); 862 863 // Otherwise, ensure that all of the tokens were parsed. 864 } else if (startTok.getLoc() != endTok.getLoc() && endTok.isNot(Token::eof)) { 865 parser.emitError(endTok.getLoc(), "encountered unexpected token"); 866 return T(); 867 } 868 return symbol; 869 } 870 871 //===----------------------------------------------------------------------===// 872 // Error Handling 873 //===----------------------------------------------------------------------===// 874 875 InFlightDiagnostic Parser::emitError(SMLoc loc, const Twine &message) { 876 auto diag = mlir::emitError(getEncodedSourceLocation(loc), message); 877 878 // If we hit a parse error in response to a lexer error, then the lexer 879 // already reported the error. 880 if (getToken().is(Token::error)) 881 diag.abandon(); 882 return diag; 883 } 884 885 //===----------------------------------------------------------------------===// 886 // Token Parsing 887 //===----------------------------------------------------------------------===// 888 889 /// Consume the specified token if present and return success. On failure, 890 /// output a diagnostic and return failure. 891 ParseResult Parser::parseToken(Token::Kind expectedToken, 892 const Twine &message) { 893 if (consumeIf(expectedToken)) 894 return success(); 895 return emitError(message); 896 } 897 898 //===----------------------------------------------------------------------===// 899 // Type Parsing 900 //===----------------------------------------------------------------------===// 901 902 /// Parse an arbitrary type. 903 /// 904 /// type ::= function-type 905 /// | non-function-type 906 /// 907 Type Parser::parseType() { 908 if (getToken().is(Token::l_paren)) 909 return parseFunctionType(); 910 return parseNonFunctionType(); 911 } 912 913 /// Parse a function result type. 914 /// 915 /// function-result-type ::= type-list-parens 916 /// | non-function-type 917 /// 918 ParseResult Parser::parseFunctionResultTypes(SmallVectorImpl<Type> &elements) { 919 if (getToken().is(Token::l_paren)) 920 return parseTypeListParens(elements); 921 922 Type t = parseNonFunctionType(); 923 if (!t) 924 return failure(); 925 elements.push_back(t); 926 return success(); 927 } 928 929 /// Parse a list of types without an enclosing parenthesis. The list must have 930 /// at least one member. 931 /// 932 /// type-list-no-parens ::= type (`,` type)* 933 /// 934 ParseResult Parser::parseTypeListNoParens(SmallVectorImpl<Type> &elements) { 935 auto parseElt = [&]() -> ParseResult { 936 auto elt = parseType(); 937 elements.push_back(elt); 938 return elt ? success() : failure(); 939 }; 940 941 return parseCommaSeparatedList(parseElt); 942 } 943 944 /// Parse a parenthesized list of types. 945 /// 946 /// type-list-parens ::= `(` `)` 947 /// | `(` type-list-no-parens `)` 948 /// 949 ParseResult Parser::parseTypeListParens(SmallVectorImpl<Type> &elements) { 950 if (parseToken(Token::l_paren, "expected '('")) 951 return failure(); 952 953 // Handle empty lists. 954 if (getToken().is(Token::r_paren)) 955 return consumeToken(), success(); 956 957 if (parseTypeListNoParens(elements) || 958 parseToken(Token::r_paren, "expected ')'")) 959 return failure(); 960 return success(); 961 } 962 963 /// Parse a complex type. 964 /// 965 /// complex-type ::= `complex` `<` type `>` 966 /// 967 Type Parser::parseComplexType() { 968 consumeToken(Token::kw_complex); 969 970 // Parse the '<'. 971 if (parseToken(Token::less, "expected '<' in complex type")) 972 return nullptr; 973 974 llvm::SMLoc elementTypeLoc = getToken().getLoc(); 975 auto elementType = parseType(); 976 if (!elementType || 977 parseToken(Token::greater, "expected '>' in complex type")) 978 return nullptr; 979 if (!elementType.isa<FloatType>() && !elementType.isa<IntegerType>()) 980 return emitError(elementTypeLoc, "invalid element type for complex"), 981 nullptr; 982 983 return ComplexType::get(elementType); 984 } 985 986 /// Parse an extended type. 987 /// 988 /// extended-type ::= (dialect-type | type-alias) 989 /// dialect-type ::= `!` dialect-namespace `<` `"` type-data `"` `>` 990 /// dialect-type ::= `!` alias-name pretty-dialect-attribute-body? 991 /// type-alias ::= `!` alias-name 992 /// 993 Type Parser::parseExtendedType() { 994 return parseExtendedSymbol<Type>( 995 *this, Token::exclamation_identifier, state.symbols.typeAliasDefinitions, 996 [&](StringRef dialectName, StringRef symbolData, 997 llvm::SMLoc loc) -> Type { 998 // If we found a registered dialect, then ask it to parse the type. 999 if (auto *dialect = state.context->getRegisteredDialect(dialectName)) { 1000 return parseSymbol<Type>( 1001 symbolData, state.context, state.symbols, [&](Parser &parser) { 1002 CustomDialectAsmParser customParser(symbolData, parser); 1003 return dialect->parseType(customParser); 1004 }); 1005 } 1006 1007 // Otherwise, form a new opaque type. 1008 return OpaqueType::getChecked( 1009 Identifier::get(dialectName, state.context), symbolData, 1010 state.context, getEncodedSourceLocation(loc)); 1011 }); 1012 } 1013 1014 /// Parse a function type. 1015 /// 1016 /// function-type ::= type-list-parens `->` function-result-type 1017 /// 1018 Type Parser::parseFunctionType() { 1019 assert(getToken().is(Token::l_paren)); 1020 1021 SmallVector<Type, 4> arguments, results; 1022 if (parseTypeListParens(arguments) || 1023 parseToken(Token::arrow, "expected '->' in function type") || 1024 parseFunctionResultTypes(results)) 1025 return nullptr; 1026 1027 return builder.getFunctionType(arguments, results); 1028 } 1029 1030 /// Parse the offset and strides from a strided layout specification. 1031 /// 1032 /// strided-layout ::= `offset:` dimension `,` `strides: ` stride-list 1033 /// 1034 ParseResult Parser::parseStridedLayout(int64_t &offset, 1035 SmallVectorImpl<int64_t> &strides) { 1036 // Parse offset. 1037 consumeToken(Token::kw_offset); 1038 if (!consumeIf(Token::colon)) 1039 return emitError("expected colon after `offset` keyword"); 1040 auto maybeOffset = getToken().getUnsignedIntegerValue(); 1041 bool question = getToken().is(Token::question); 1042 if (!maybeOffset && !question) 1043 return emitError("invalid offset"); 1044 offset = maybeOffset ? static_cast<int64_t>(maybeOffset.getValue()) 1045 : MemRefType::getDynamicStrideOrOffset(); 1046 consumeToken(); 1047 1048 if (!consumeIf(Token::comma)) 1049 return emitError("expected comma after offset value"); 1050 1051 // Parse stride list. 1052 if (!consumeIf(Token::kw_strides)) 1053 return emitError("expected `strides` keyword after offset specification"); 1054 if (!consumeIf(Token::colon)) 1055 return emitError("expected colon after `strides` keyword"); 1056 if (failed(parseStrideList(strides))) 1057 return emitError("invalid braces-enclosed stride list"); 1058 if (llvm::any_of(strides, [](int64_t st) { return st == 0; })) 1059 return emitError("invalid memref stride"); 1060 1061 return success(); 1062 } 1063 1064 /// Parse a memref type. 1065 /// 1066 /// memref-type ::= ranked-memref-type | unranked-memref-type 1067 /// 1068 /// ranked-memref-type ::= `memref` `<` dimension-list-ranked type 1069 /// (`,` semi-affine-map-composition)? (`,` 1070 /// memory-space)? `>` 1071 /// 1072 /// unranked-memref-type ::= `memref` `<*x` type (`,` memory-space)? `>` 1073 /// 1074 /// semi-affine-map-composition ::= (semi-affine-map `,` )* semi-affine-map 1075 /// memory-space ::= integer-literal /* | TODO: address-space-id */ 1076 /// 1077 Type Parser::parseMemRefType() { 1078 consumeToken(Token::kw_memref); 1079 1080 if (parseToken(Token::less, "expected '<' in memref type")) 1081 return nullptr; 1082 1083 bool isUnranked; 1084 SmallVector<int64_t, 4> dimensions; 1085 1086 if (consumeIf(Token::star)) { 1087 // This is an unranked memref type. 1088 isUnranked = true; 1089 if (parseXInDimensionList()) 1090 return nullptr; 1091 1092 } else { 1093 isUnranked = false; 1094 if (parseDimensionListRanked(dimensions)) 1095 return nullptr; 1096 } 1097 1098 // Parse the element type. 1099 auto typeLoc = getToken().getLoc(); 1100 auto elementType = parseType(); 1101 if (!elementType) 1102 return nullptr; 1103 1104 // Check that memref is formed from allowed types. 1105 if (!elementType.isIntOrFloat() && !elementType.isa<VectorType>() && 1106 !elementType.isa<ComplexType>()) 1107 return emitError(typeLoc, "invalid memref element type"), nullptr; 1108 1109 // Parse semi-affine-map-composition. 1110 SmallVector<AffineMap, 2> affineMapComposition; 1111 Optional<unsigned> memorySpace; 1112 unsigned numDims = dimensions.size(); 1113 1114 auto parseElt = [&]() -> ParseResult { 1115 // Check for the memory space. 1116 if (getToken().is(Token::integer)) { 1117 if (memorySpace) 1118 return emitError("multiple memory spaces specified in memref type"); 1119 memorySpace = getToken().getUnsignedIntegerValue(); 1120 if (!memorySpace.hasValue()) 1121 return emitError("invalid memory space in memref type"); 1122 consumeToken(Token::integer); 1123 return success(); 1124 } 1125 if (isUnranked) 1126 return emitError("cannot have affine map for unranked memref type"); 1127 if (memorySpace) 1128 return emitError("expected memory space to be last in memref type"); 1129 1130 AffineMap map; 1131 llvm::SMLoc mapLoc = getToken().getLoc(); 1132 if (getToken().is(Token::kw_offset)) { 1133 int64_t offset; 1134 SmallVector<int64_t, 4> strides; 1135 if (failed(parseStridedLayout(offset, strides))) 1136 return failure(); 1137 // Construct strided affine map. 1138 map = makeStridedLinearLayoutMap(strides, offset, state.context); 1139 } else { 1140 // Parse an affine map attribute. 1141 auto affineMap = parseAttribute(); 1142 if (!affineMap) 1143 return failure(); 1144 auto affineMapAttr = affineMap.dyn_cast<AffineMapAttr>(); 1145 if (!affineMapAttr) 1146 return emitError("expected affine map in memref type"); 1147 map = affineMapAttr.getValue(); 1148 } 1149 1150 if (map.getNumDims() != numDims) { 1151 size_t i = affineMapComposition.size(); 1152 return emitError(mapLoc, "memref affine map dimension mismatch between ") 1153 << (i == 0 ? Twine("memref rank") : "affine map " + Twine(i)) 1154 << " and affine map" << i + 1 << ": " << numDims 1155 << " != " << map.getNumDims(); 1156 } 1157 numDims = map.getNumResults(); 1158 affineMapComposition.push_back(map); 1159 return success(); 1160 }; 1161 1162 // Parse a list of mappings and address space if present. 1163 if (!consumeIf(Token::greater)) { 1164 // Parse comma separated list of affine maps, followed by memory space. 1165 if (parseToken(Token::comma, "expected ',' or '>' in memref type") || 1166 parseCommaSeparatedListUntil(Token::greater, parseElt, 1167 /*allowEmptyList=*/false)) { 1168 return nullptr; 1169 } 1170 } 1171 1172 if (isUnranked) 1173 return UnrankedMemRefType::get(elementType, memorySpace.getValueOr(0)); 1174 1175 return MemRefType::get(dimensions, elementType, affineMapComposition, 1176 memorySpace.getValueOr(0)); 1177 } 1178 1179 /// Parse any type except the function type. 1180 /// 1181 /// non-function-type ::= integer-type 1182 /// | index-type 1183 /// | float-type 1184 /// | extended-type 1185 /// | vector-type 1186 /// | tensor-type 1187 /// | memref-type 1188 /// | complex-type 1189 /// | tuple-type 1190 /// | none-type 1191 /// 1192 /// index-type ::= `index` 1193 /// float-type ::= `f16` | `bf16` | `f32` | `f64` 1194 /// none-type ::= `none` 1195 /// 1196 Type Parser::parseNonFunctionType() { 1197 switch (getToken().getKind()) { 1198 default: 1199 return (emitError("expected non-function type"), nullptr); 1200 case Token::kw_memref: 1201 return parseMemRefType(); 1202 case Token::kw_tensor: 1203 return parseTensorType(); 1204 case Token::kw_complex: 1205 return parseComplexType(); 1206 case Token::kw_tuple: 1207 return parseTupleType(); 1208 case Token::kw_vector: 1209 return parseVectorType(); 1210 // integer-type 1211 case Token::inttype: { 1212 auto width = getToken().getIntTypeBitwidth(); 1213 if (!width.hasValue()) 1214 return (emitError("invalid integer width"), nullptr); 1215 if (width.getValue() > IntegerType::kMaxWidth) { 1216 emitError(getToken().getLoc(), "integer bitwidth is limited to ") 1217 << IntegerType::kMaxWidth << " bits"; 1218 return nullptr; 1219 } 1220 1221 IntegerType::SignednessSemantics signSemantics = IntegerType::Signless; 1222 if (Optional<bool> signedness = getToken().getIntTypeSignedness()) 1223 signSemantics = *signedness ? IntegerType::Signed : IntegerType::Unsigned; 1224 1225 auto loc = getEncodedSourceLocation(getToken().getLoc()); 1226 consumeToken(Token::inttype); 1227 return IntegerType::getChecked(width.getValue(), signSemantics, loc); 1228 } 1229 1230 // float-type 1231 case Token::kw_bf16: 1232 consumeToken(Token::kw_bf16); 1233 return builder.getBF16Type(); 1234 case Token::kw_f16: 1235 consumeToken(Token::kw_f16); 1236 return builder.getF16Type(); 1237 case Token::kw_f32: 1238 consumeToken(Token::kw_f32); 1239 return builder.getF32Type(); 1240 case Token::kw_f64: 1241 consumeToken(Token::kw_f64); 1242 return builder.getF64Type(); 1243 1244 // index-type 1245 case Token::kw_index: 1246 consumeToken(Token::kw_index); 1247 return builder.getIndexType(); 1248 1249 // none-type 1250 case Token::kw_none: 1251 consumeToken(Token::kw_none); 1252 return builder.getNoneType(); 1253 1254 // extended type 1255 case Token::exclamation_identifier: 1256 return parseExtendedType(); 1257 } 1258 } 1259 1260 /// Parse a tensor type. 1261 /// 1262 /// tensor-type ::= `tensor` `<` dimension-list type `>` 1263 /// dimension-list ::= dimension-list-ranked | `*x` 1264 /// 1265 Type Parser::parseTensorType() { 1266 consumeToken(Token::kw_tensor); 1267 1268 if (parseToken(Token::less, "expected '<' in tensor type")) 1269 return nullptr; 1270 1271 bool isUnranked; 1272 SmallVector<int64_t, 4> dimensions; 1273 1274 if (consumeIf(Token::star)) { 1275 // This is an unranked tensor type. 1276 isUnranked = true; 1277 1278 if (parseXInDimensionList()) 1279 return nullptr; 1280 1281 } else { 1282 isUnranked = false; 1283 if (parseDimensionListRanked(dimensions)) 1284 return nullptr; 1285 } 1286 1287 // Parse the element type. 1288 auto elementTypeLoc = getToken().getLoc(); 1289 auto elementType = parseType(); 1290 if (!elementType || parseToken(Token::greater, "expected '>' in tensor type")) 1291 return nullptr; 1292 if (!TensorType::isValidElementType(elementType)) 1293 return emitError(elementTypeLoc, "invalid tensor element type"), nullptr; 1294 1295 if (isUnranked) 1296 return UnrankedTensorType::get(elementType); 1297 return RankedTensorType::get(dimensions, elementType); 1298 } 1299 1300 /// Parse a tuple type. 1301 /// 1302 /// tuple-type ::= `tuple` `<` (type (`,` type)*)? `>` 1303 /// 1304 Type Parser::parseTupleType() { 1305 consumeToken(Token::kw_tuple); 1306 1307 // Parse the '<'. 1308 if (parseToken(Token::less, "expected '<' in tuple type")) 1309 return nullptr; 1310 1311 // Check for an empty tuple by directly parsing '>'. 1312 if (consumeIf(Token::greater)) 1313 return TupleType::get(getContext()); 1314 1315 // Parse the element types and the '>'. 1316 SmallVector<Type, 4> types; 1317 if (parseTypeListNoParens(types) || 1318 parseToken(Token::greater, "expected '>' in tuple type")) 1319 return nullptr; 1320 1321 return TupleType::get(types, getContext()); 1322 } 1323 1324 /// Parse a vector type. 1325 /// 1326 /// vector-type ::= `vector` `<` non-empty-static-dimension-list type `>` 1327 /// non-empty-static-dimension-list ::= decimal-literal `x` 1328 /// static-dimension-list 1329 /// static-dimension-list ::= (decimal-literal `x`)* 1330 /// 1331 VectorType Parser::parseVectorType() { 1332 consumeToken(Token::kw_vector); 1333 1334 if (parseToken(Token::less, "expected '<' in vector type")) 1335 return nullptr; 1336 1337 SmallVector<int64_t, 4> dimensions; 1338 if (parseDimensionListRanked(dimensions, /*allowDynamic=*/false)) 1339 return nullptr; 1340 if (dimensions.empty()) 1341 return (emitError("expected dimension size in vector type"), nullptr); 1342 if (any_of(dimensions, [](int64_t i) { return i <= 0; })) 1343 return emitError(getToken().getLoc(), 1344 "vector types must have positive constant sizes"), 1345 nullptr; 1346 1347 // Parse the element type. 1348 auto typeLoc = getToken().getLoc(); 1349 auto elementType = parseType(); 1350 if (!elementType || parseToken(Token::greater, "expected '>' in vector type")) 1351 return nullptr; 1352 if (!VectorType::isValidElementType(elementType)) 1353 return emitError(typeLoc, "vector elements must be int or float type"), 1354 nullptr; 1355 1356 return VectorType::get(dimensions, elementType); 1357 } 1358 1359 /// Parse a dimension list of a tensor or memref type. This populates the 1360 /// dimension list, using -1 for the `?` dimensions if `allowDynamic` is set and 1361 /// errors out on `?` otherwise. 1362 /// 1363 /// dimension-list-ranked ::= (dimension `x`)* 1364 /// dimension ::= `?` | decimal-literal 1365 /// 1366 /// When `allowDynamic` is not set, this is used to parse: 1367 /// 1368 /// static-dimension-list ::= (decimal-literal `x`)* 1369 ParseResult 1370 Parser::parseDimensionListRanked(SmallVectorImpl<int64_t> &dimensions, 1371 bool allowDynamic) { 1372 while (getToken().isAny(Token::integer, Token::question)) { 1373 if (consumeIf(Token::question)) { 1374 if (!allowDynamic) 1375 return emitError("expected static shape"); 1376 dimensions.push_back(-1); 1377 } else { 1378 // Hexadecimal integer literals (starting with `0x`) are not allowed in 1379 // aggregate type declarations. Therefore, `0xf32` should be processed as 1380 // a sequence of separate elements `0`, `x`, `f32`. 1381 if (getTokenSpelling().size() > 1 && getTokenSpelling()[1] == 'x') { 1382 // We can get here only if the token is an integer literal. Hexadecimal 1383 // integer literals can only start with `0x` (`1x` wouldn't lex as a 1384 // literal, just `1` would, at which point we don't get into this 1385 // branch). 1386 assert(getTokenSpelling()[0] == '0' && "invalid integer literal"); 1387 dimensions.push_back(0); 1388 state.lex.resetPointer(getTokenSpelling().data() + 1); 1389 consumeToken(); 1390 } else { 1391 // Make sure this integer value is in bound and valid. 1392 auto dimension = getToken().getUnsignedIntegerValue(); 1393 if (!dimension.hasValue()) 1394 return emitError("invalid dimension"); 1395 dimensions.push_back((int64_t)dimension.getValue()); 1396 consumeToken(Token::integer); 1397 } 1398 } 1399 1400 // Make sure we have an 'x' or something like 'xbf32'. 1401 if (parseXInDimensionList()) 1402 return failure(); 1403 } 1404 1405 return success(); 1406 } 1407 1408 /// Parse an 'x' token in a dimension list, handling the case where the x is 1409 /// juxtaposed with an element type, as in "xf32", leaving the "f32" as the next 1410 /// token. 1411 ParseResult Parser::parseXInDimensionList() { 1412 if (getToken().isNot(Token::bare_identifier) || getTokenSpelling()[0] != 'x') 1413 return emitError("expected 'x' in dimension list"); 1414 1415 // If we had a prefix of 'x', lex the next token immediately after the 'x'. 1416 if (getTokenSpelling().size() != 1) 1417 state.lex.resetPointer(getTokenSpelling().data() + 1); 1418 1419 // Consume the 'x'. 1420 consumeToken(Token::bare_identifier); 1421 1422 return success(); 1423 } 1424 1425 // Parse a comma-separated list of dimensions, possibly empty: 1426 // stride-list ::= `[` (dimension (`,` dimension)*)? `]` 1427 ParseResult Parser::parseStrideList(SmallVectorImpl<int64_t> &dimensions) { 1428 if (!consumeIf(Token::l_square)) 1429 return failure(); 1430 // Empty list early exit. 1431 if (consumeIf(Token::r_square)) 1432 return success(); 1433 while (true) { 1434 if (consumeIf(Token::question)) { 1435 dimensions.push_back(MemRefType::getDynamicStrideOrOffset()); 1436 } else { 1437 // This must be an integer value. 1438 int64_t val; 1439 if (getToken().getSpelling().getAsInteger(10, val)) 1440 return emitError("invalid integer value: ") << getToken().getSpelling(); 1441 // Make sure it is not the one value for `?`. 1442 if (ShapedType::isDynamic(val)) 1443 return emitError("invalid integer value: ") 1444 << getToken().getSpelling() 1445 << ", use `?` to specify a dynamic dimension"; 1446 dimensions.push_back(val); 1447 consumeToken(Token::integer); 1448 } 1449 if (!consumeIf(Token::comma)) 1450 break; 1451 } 1452 if (!consumeIf(Token::r_square)) 1453 return failure(); 1454 return success(); 1455 } 1456 1457 //===----------------------------------------------------------------------===// 1458 // Attribute parsing. 1459 //===----------------------------------------------------------------------===// 1460 1461 /// Return the symbol reference referred to by the given token, that is known to 1462 /// be an @-identifier. 1463 static std::string extractSymbolReference(Token tok) { 1464 assert(tok.is(Token::at_identifier) && "expected valid @-identifier"); 1465 StringRef nameStr = tok.getSpelling().drop_front(); 1466 1467 // Check to see if the reference is a string literal, or a bare identifier. 1468 if (nameStr.front() == '"') 1469 return tok.getStringValue(); 1470 return std::string(nameStr); 1471 } 1472 1473 /// Parse an arbitrary attribute. 1474 /// 1475 /// attribute-value ::= `unit` 1476 /// | bool-literal 1477 /// | integer-literal (`:` (index-type | integer-type))? 1478 /// | float-literal (`:` float-type)? 1479 /// | string-literal (`:` type)? 1480 /// | type 1481 /// | `[` (attribute-value (`,` attribute-value)*)? `]` 1482 /// | `{` (attribute-entry (`,` attribute-entry)*)? `}` 1483 /// | symbol-ref-id (`::` symbol-ref-id)* 1484 /// | `dense` `<` attribute-value `>` `:` 1485 /// (tensor-type | vector-type) 1486 /// | `sparse` `<` attribute-value `,` attribute-value `>` 1487 /// `:` (tensor-type | vector-type) 1488 /// | `opaque` `<` dialect-namespace `,` hex-string-literal 1489 /// `>` `:` (tensor-type | vector-type) 1490 /// | extended-attribute 1491 /// 1492 Attribute Parser::parseAttribute(Type type) { 1493 switch (getToken().getKind()) { 1494 // Parse an AffineMap or IntegerSet attribute. 1495 case Token::kw_affine_map: { 1496 consumeToken(Token::kw_affine_map); 1497 1498 AffineMap map; 1499 if (parseToken(Token::less, "expected '<' in affine map") || 1500 parseAffineMapReference(map) || 1501 parseToken(Token::greater, "expected '>' in affine map")) 1502 return Attribute(); 1503 return AffineMapAttr::get(map); 1504 } 1505 case Token::kw_affine_set: { 1506 consumeToken(Token::kw_affine_set); 1507 1508 IntegerSet set; 1509 if (parseToken(Token::less, "expected '<' in integer set") || 1510 parseIntegerSetReference(set) || 1511 parseToken(Token::greater, "expected '>' in integer set")) 1512 return Attribute(); 1513 return IntegerSetAttr::get(set); 1514 } 1515 1516 // Parse an array attribute. 1517 case Token::l_square: { 1518 consumeToken(Token::l_square); 1519 1520 SmallVector<Attribute, 4> elements; 1521 auto parseElt = [&]() -> ParseResult { 1522 elements.push_back(parseAttribute()); 1523 return elements.back() ? success() : failure(); 1524 }; 1525 1526 if (parseCommaSeparatedListUntil(Token::r_square, parseElt)) 1527 return nullptr; 1528 return builder.getArrayAttr(elements); 1529 } 1530 1531 // Parse a boolean attribute. 1532 case Token::kw_false: 1533 consumeToken(Token::kw_false); 1534 return builder.getBoolAttr(false); 1535 case Token::kw_true: 1536 consumeToken(Token::kw_true); 1537 return builder.getBoolAttr(true); 1538 1539 // Parse a dense elements attribute. 1540 case Token::kw_dense: 1541 return parseDenseElementsAttr(type); 1542 1543 // Parse a dictionary attribute. 1544 case Token::l_brace: { 1545 SmallVector<NamedAttribute, 4> elements; 1546 if (parseAttributeDict(elements)) 1547 return nullptr; 1548 return builder.getDictionaryAttr(elements); 1549 } 1550 1551 // Parse an extended attribute, i.e. alias or dialect attribute. 1552 case Token::hash_identifier: 1553 return parseExtendedAttr(type); 1554 1555 // Parse floating point and integer attributes. 1556 case Token::floatliteral: 1557 return parseFloatAttr(type, /*isNegative=*/false); 1558 case Token::integer: 1559 return parseDecOrHexAttr(type, /*isNegative=*/false); 1560 case Token::minus: { 1561 consumeToken(Token::minus); 1562 if (getToken().is(Token::integer)) 1563 return parseDecOrHexAttr(type, /*isNegative=*/true); 1564 if (getToken().is(Token::floatliteral)) 1565 return parseFloatAttr(type, /*isNegative=*/true); 1566 1567 return (emitError("expected constant integer or floating point value"), 1568 nullptr); 1569 } 1570 1571 // Parse a location attribute. 1572 case Token::kw_loc: { 1573 LocationAttr attr; 1574 return failed(parseLocation(attr)) ? Attribute() : attr; 1575 } 1576 1577 // Parse an opaque elements attribute. 1578 case Token::kw_opaque: 1579 return parseOpaqueElementsAttr(type); 1580 1581 // Parse a sparse elements attribute. 1582 case Token::kw_sparse: 1583 return parseSparseElementsAttr(type); 1584 1585 // Parse a string attribute. 1586 case Token::string: { 1587 auto val = getToken().getStringValue(); 1588 consumeToken(Token::string); 1589 // Parse the optional trailing colon type if one wasn't explicitly provided. 1590 if (!type && consumeIf(Token::colon) && !(type = parseType())) 1591 return Attribute(); 1592 1593 return type ? StringAttr::get(val, type) 1594 : StringAttr::get(val, getContext()); 1595 } 1596 1597 // Parse a symbol reference attribute. 1598 case Token::at_identifier: { 1599 std::string nameStr = extractSymbolReference(getToken()); 1600 consumeToken(Token::at_identifier); 1601 1602 // Parse any nested references. 1603 std::vector<FlatSymbolRefAttr> nestedRefs; 1604 while (getToken().is(Token::colon)) { 1605 // Check for the '::' prefix. 1606 const char *curPointer = getToken().getLoc().getPointer(); 1607 consumeToken(Token::colon); 1608 if (!consumeIf(Token::colon)) { 1609 state.lex.resetPointer(curPointer); 1610 consumeToken(); 1611 break; 1612 } 1613 // Parse the reference itself. 1614 auto curLoc = getToken().getLoc(); 1615 if (getToken().isNot(Token::at_identifier)) { 1616 emitError(curLoc, "expected nested symbol reference identifier"); 1617 return Attribute(); 1618 } 1619 1620 std::string nameStr = extractSymbolReference(getToken()); 1621 consumeToken(Token::at_identifier); 1622 nestedRefs.push_back(SymbolRefAttr::get(nameStr, getContext())); 1623 } 1624 1625 return builder.getSymbolRefAttr(nameStr, nestedRefs); 1626 } 1627 1628 // Parse a 'unit' attribute. 1629 case Token::kw_unit: 1630 consumeToken(Token::kw_unit); 1631 return builder.getUnitAttr(); 1632 1633 default: 1634 // Parse a type attribute. 1635 if (Type type = parseType()) 1636 return TypeAttr::get(type); 1637 return nullptr; 1638 } 1639 } 1640 1641 /// Attribute dictionary. 1642 /// 1643 /// attribute-dict ::= `{` `}` 1644 /// | `{` attribute-entry (`,` attribute-entry)* `}` 1645 /// attribute-entry ::= bare-id `=` attribute-value 1646 /// 1647 ParseResult 1648 Parser::parseAttributeDict(SmallVectorImpl<NamedAttribute> &attributes) { 1649 if (parseToken(Token::l_brace, "expected '{' in attribute dictionary")) 1650 return failure(); 1651 1652 auto parseElt = [&]() -> ParseResult { 1653 // We allow keywords as attribute names. 1654 if (getToken().isNot(Token::bare_identifier, Token::inttype) && 1655 !getToken().isKeyword()) 1656 return emitError("expected attribute name"); 1657 Identifier nameId = builder.getIdentifier(getTokenSpelling()); 1658 consumeToken(); 1659 1660 // Try to parse the '=' for the attribute value. 1661 if (!consumeIf(Token::equal)) { 1662 // If there is no '=', we treat this as a unit attribute. 1663 attributes.push_back({nameId, builder.getUnitAttr()}); 1664 return success(); 1665 } 1666 1667 auto attr = parseAttribute(); 1668 if (!attr) 1669 return failure(); 1670 1671 attributes.push_back({nameId, attr}); 1672 return success(); 1673 }; 1674 1675 if (parseCommaSeparatedListUntil(Token::r_brace, parseElt)) 1676 return failure(); 1677 1678 return success(); 1679 } 1680 1681 /// Parse an extended attribute. 1682 /// 1683 /// extended-attribute ::= (dialect-attribute | attribute-alias) 1684 /// dialect-attribute ::= `#` dialect-namespace `<` `"` attr-data `"` `>` 1685 /// dialect-attribute ::= `#` alias-name pretty-dialect-sym-body? 1686 /// attribute-alias ::= `#` alias-name 1687 /// 1688 Attribute Parser::parseExtendedAttr(Type type) { 1689 Attribute attr = parseExtendedSymbol<Attribute>( 1690 *this, Token::hash_identifier, state.symbols.attributeAliasDefinitions, 1691 [&](StringRef dialectName, StringRef symbolData, 1692 llvm::SMLoc loc) -> Attribute { 1693 // Parse an optional trailing colon type. 1694 Type attrType = type; 1695 if (consumeIf(Token::colon) && !(attrType = parseType())) 1696 return Attribute(); 1697 1698 // If we found a registered dialect, then ask it to parse the attribute. 1699 if (auto *dialect = state.context->getRegisteredDialect(dialectName)) { 1700 return parseSymbol<Attribute>( 1701 symbolData, state.context, state.symbols, [&](Parser &parser) { 1702 CustomDialectAsmParser customParser(symbolData, parser); 1703 return dialect->parseAttribute(customParser, attrType); 1704 }); 1705 } 1706 1707 // Otherwise, form a new opaque attribute. 1708 return OpaqueAttr::getChecked( 1709 Identifier::get(dialectName, state.context), symbolData, 1710 attrType ? attrType : NoneType::get(state.context), 1711 getEncodedSourceLocation(loc)); 1712 }); 1713 1714 // Ensure that the attribute has the same type as requested. 1715 if (attr && type && attr.getType() != type) { 1716 emitError("attribute type different than expected: expected ") 1717 << type << ", but got " << attr.getType(); 1718 return nullptr; 1719 } 1720 return attr; 1721 } 1722 1723 /// Parse a float attribute. 1724 Attribute Parser::parseFloatAttr(Type type, bool isNegative) { 1725 auto val = getToken().getFloatingPointValue(); 1726 if (!val.hasValue()) 1727 return (emitError("floating point value too large for attribute"), nullptr); 1728 consumeToken(Token::floatliteral); 1729 if (!type) { 1730 // Default to F64 when no type is specified. 1731 if (!consumeIf(Token::colon)) 1732 type = builder.getF64Type(); 1733 else if (!(type = parseType())) 1734 return nullptr; 1735 } 1736 if (!type.isa<FloatType>()) 1737 return (emitError("floating point value not valid for specified type"), 1738 nullptr); 1739 return FloatAttr::get(type, isNegative ? -val.getValue() : val.getValue()); 1740 } 1741 1742 /// Construct a float attribute bitwise equivalent to the integer literal. 1743 static Optional<APFloat> buildHexadecimalFloatLiteral(Parser *p, FloatType type, 1744 uint64_t value) { 1745 // FIXME: bfloat is currently stored as a double internally because it doesn't 1746 // have valid APFloat semantics. 1747 if (type.isF64() || type.isBF16()) 1748 return APFloat(type.getFloatSemantics(), APInt(/*numBits=*/64, value)); 1749 1750 APInt apInt(type.getWidth(), value); 1751 if (apInt != value) { 1752 p->emitError("hexadecimal float constant out of range for type"); 1753 return llvm::None; 1754 } 1755 return APFloat(type.getFloatSemantics(), apInt); 1756 } 1757 1758 /// Parse a decimal or a hexadecimal literal, which can be either an integer 1759 /// or a float attribute. 1760 Attribute Parser::parseDecOrHexAttr(Type type, bool isNegative) { 1761 auto val = getToken().getUInt64IntegerValue(); 1762 if (!val.hasValue()) 1763 return (emitError("integer constant out of range for attribute"), nullptr); 1764 1765 // Remember if the literal is hexadecimal. 1766 StringRef spelling = getToken().getSpelling(); 1767 auto loc = state.curToken.getLoc(); 1768 bool isHex = spelling.size() > 1 && spelling[1] == 'x'; 1769 1770 consumeToken(Token::integer); 1771 if (!type) { 1772 // Default to i64 if not type is specified. 1773 if (!consumeIf(Token::colon)) 1774 type = builder.getIntegerType(64); 1775 else if (!(type = parseType())) 1776 return nullptr; 1777 } 1778 1779 if (auto floatType = type.dyn_cast<FloatType>()) { 1780 if (isNegative) 1781 return emitError( 1782 loc, 1783 "hexadecimal float literal should not have a leading minus"), 1784 nullptr; 1785 if (!isHex) { 1786 emitError(loc, "unexpected decimal integer literal for a float attribute") 1787 .attachNote() 1788 << "add a trailing dot to make the literal a float"; 1789 return nullptr; 1790 } 1791 1792 // Construct a float attribute bitwise equivalent to the integer literal. 1793 Optional<APFloat> apVal = 1794 buildHexadecimalFloatLiteral(this, floatType, *val); 1795 return apVal ? FloatAttr::get(floatType, *apVal) : Attribute(); 1796 } 1797 1798 if (!type.isa<IntegerType>() && !type.isa<IndexType>()) 1799 return emitError(loc, "integer literal not valid for specified type"), 1800 nullptr; 1801 1802 if (isNegative && type.isUnsignedInteger()) { 1803 emitError(loc, 1804 "negative integer literal not valid for unsigned integer type"); 1805 return nullptr; 1806 } 1807 1808 // Parse the integer literal. 1809 int width = type.isIndex() ? 64 : type.getIntOrFloatBitWidth(); 1810 APInt apInt(width, *val, isNegative); 1811 if (apInt != *val) 1812 return emitError(loc, "integer constant out of range for attribute"), 1813 nullptr; 1814 1815 // Otherwise construct an integer attribute. 1816 if (isNegative ? (int64_t)-val.getValue() >= 0 : (int64_t)val.getValue() < 0) 1817 return emitError(loc, "integer constant out of range for attribute"), 1818 nullptr; 1819 1820 return builder.getIntegerAttr(type, isNegative ? -apInt : apInt); 1821 } 1822 1823 /// Parse elements values stored within a hex etring. On success, the values are 1824 /// stored into 'result'. 1825 static ParseResult parseElementAttrHexValues(Parser &parser, Token tok, 1826 std::string &result) { 1827 std::string val = tok.getStringValue(); 1828 if (val.size() < 2 || val[0] != '0' || val[1] != 'x') 1829 return parser.emitError(tok.getLoc(), 1830 "elements hex string should start with '0x'"); 1831 1832 StringRef hexValues = StringRef(val).drop_front(2); 1833 if (!llvm::all_of(hexValues, llvm::isHexDigit)) 1834 return parser.emitError(tok.getLoc(), 1835 "elements hex string only contains hex digits"); 1836 1837 result = llvm::fromHex(hexValues); 1838 return success(); 1839 } 1840 1841 /// Parse an opaque elements attribute. 1842 Attribute Parser::parseOpaqueElementsAttr(Type attrType) { 1843 consumeToken(Token::kw_opaque); 1844 if (parseToken(Token::less, "expected '<' after 'opaque'")) 1845 return nullptr; 1846 1847 if (getToken().isNot(Token::string)) 1848 return (emitError("expected dialect namespace"), nullptr); 1849 1850 auto name = getToken().getStringValue(); 1851 auto *dialect = builder.getContext()->getRegisteredDialect(name); 1852 // TODO(shpeisman): Allow for having an unknown dialect on an opaque 1853 // attribute. Otherwise, it can't be roundtripped without having the dialect 1854 // registered. 1855 if (!dialect) 1856 return (emitError("no registered dialect with namespace '" + name + "'"), 1857 nullptr); 1858 consumeToken(Token::string); 1859 1860 if (parseToken(Token::comma, "expected ','")) 1861 return nullptr; 1862 1863 Token hexTok = getToken(); 1864 if (parseToken(Token::string, "elements hex string should start with '0x'") || 1865 parseToken(Token::greater, "expected '>'")) 1866 return nullptr; 1867 auto type = parseElementsLiteralType(attrType); 1868 if (!type) 1869 return nullptr; 1870 1871 std::string data; 1872 if (parseElementAttrHexValues(*this, hexTok, data)) 1873 return nullptr; 1874 return OpaqueElementsAttr::get(dialect, type, data); 1875 } 1876 1877 namespace { 1878 class TensorLiteralParser { 1879 public: 1880 TensorLiteralParser(Parser &p) : p(p) {} 1881 1882 /// Parse the elements of a tensor literal. If 'allowHex' is true, the parser 1883 /// may also parse a tensor literal that is store as a hex string. 1884 ParseResult parse(bool allowHex); 1885 1886 /// Build a dense attribute instance with the parsed elements and the given 1887 /// shaped type. 1888 DenseElementsAttr getAttr(llvm::SMLoc loc, ShapedType type); 1889 1890 ArrayRef<int64_t> getShape() const { return shape; } 1891 1892 private: 1893 enum class ElementKind { Boolean, Integer, Float }; 1894 1895 /// Return a string to represent the given element kind. 1896 const char *getElementKindStr(ElementKind kind) { 1897 switch (kind) { 1898 case ElementKind::Boolean: 1899 return "'boolean'"; 1900 case ElementKind::Integer: 1901 return "'integer'"; 1902 case ElementKind::Float: 1903 return "'float'"; 1904 } 1905 llvm_unreachable("unknown element kind"); 1906 } 1907 1908 /// Build a Dense Integer attribute for the given type. 1909 DenseElementsAttr getIntAttr(llvm::SMLoc loc, ShapedType type, 1910 IntegerType eltTy); 1911 1912 /// Build a Dense Float attribute for the given type. 1913 DenseElementsAttr getFloatAttr(llvm::SMLoc loc, ShapedType type, 1914 FloatType eltTy); 1915 1916 /// Build a Dense attribute with hex data for the given type. 1917 DenseElementsAttr getHexAttr(llvm::SMLoc loc, ShapedType type); 1918 1919 /// Parse a single element, returning failure if it isn't a valid element 1920 /// literal. For example: 1921 /// parseElement(1) -> Success, 1 1922 /// parseElement([1]) -> Failure 1923 ParseResult parseElement(); 1924 1925 /// Parse a list of either lists or elements, returning the dimensions of the 1926 /// parsed sub-tensors in dims. For example: 1927 /// parseList([1, 2, 3]) -> Success, [3] 1928 /// parseList([[1, 2], [3, 4]]) -> Success, [2, 2] 1929 /// parseList([[1, 2], 3]) -> Failure 1930 /// parseList([[1, [2, 3]], [4, [5]]]) -> Failure 1931 ParseResult parseList(SmallVectorImpl<int64_t> &dims); 1932 1933 /// Parse a literal that was printed as a hex string. 1934 ParseResult parseHexElements(); 1935 1936 Parser &p; 1937 1938 /// The shape inferred from the parsed elements. 1939 SmallVector<int64_t, 4> shape; 1940 1941 /// Storage used when parsing elements, this is a pair of <is_negated, token>. 1942 std::vector<std::pair<bool, Token>> storage; 1943 1944 /// A flag that indicates the type of elements that have been parsed. 1945 Optional<ElementKind> knownEltKind; 1946 1947 /// Storage used when parsing elements that were stored as hex values. 1948 Optional<Token> hexStorage; 1949 }; 1950 } // namespace 1951 1952 /// Parse the elements of a tensor literal. If 'allowHex' is true, the parser 1953 /// may also parse a tensor literal that is store as a hex string. 1954 ParseResult TensorLiteralParser::parse(bool allowHex) { 1955 // If hex is allowed, check for a string literal. 1956 if (allowHex && p.getToken().is(Token::string)) { 1957 hexStorage = p.getToken(); 1958 p.consumeToken(Token::string); 1959 return success(); 1960 } 1961 // Otherwise, parse a list or an individual element. 1962 if (p.getToken().is(Token::l_square)) 1963 return parseList(shape); 1964 return parseElement(); 1965 } 1966 1967 /// Build a dense attribute instance with the parsed elements and the given 1968 /// shaped type. 1969 DenseElementsAttr TensorLiteralParser::getAttr(llvm::SMLoc loc, 1970 ShapedType type) { 1971 // Check to see if we parsed the literal from a hex string. 1972 if (hexStorage.hasValue()) 1973 return getHexAttr(loc, type); 1974 1975 // Check that the parsed storage size has the same number of elements to the 1976 // type, or is a known splat. 1977 if (!shape.empty() && getShape() != type.getShape()) { 1978 p.emitError(loc) << "inferred shape of elements literal ([" << getShape() 1979 << "]) does not match type ([" << type.getShape() << "])"; 1980 return nullptr; 1981 } 1982 1983 // If the type is an integer, build a set of APInt values from the storage 1984 // with the correct bitwidth. 1985 if (auto intTy = type.getElementType().dyn_cast<IntegerType>()) 1986 return getIntAttr(loc, type, intTy); 1987 1988 // Otherwise, this must be a floating point type. 1989 auto floatTy = type.getElementType().dyn_cast<FloatType>(); 1990 if (!floatTy) { 1991 p.emitError(loc) << "expected floating-point or integer element type, got " 1992 << type.getElementType(); 1993 return nullptr; 1994 } 1995 return getFloatAttr(loc, type, floatTy); 1996 } 1997 1998 /// Build a Dense Integer attribute for the given type. 1999 DenseElementsAttr TensorLiteralParser::getIntAttr(llvm::SMLoc loc, 2000 ShapedType type, 2001 IntegerType eltTy) { 2002 std::vector<APInt> intElements; 2003 intElements.reserve(storage.size()); 2004 auto isUintType = type.getElementType().isUnsignedInteger(); 2005 for (const auto &signAndToken : storage) { 2006 bool isNegative = signAndToken.first; 2007 const Token &token = signAndToken.second; 2008 auto tokenLoc = token.getLoc(); 2009 2010 if (isNegative && isUintType) { 2011 p.emitError(tokenLoc) 2012 << "expected unsigned integer elements, but parsed negative value"; 2013 return nullptr; 2014 } 2015 2016 // Check to see if floating point values were parsed. 2017 if (token.is(Token::floatliteral)) { 2018 p.emitError(tokenLoc) 2019 << "expected integer elements, but parsed floating-point"; 2020 return nullptr; 2021 } 2022 2023 assert(token.isAny(Token::integer, Token::kw_true, Token::kw_false) && 2024 "unexpected token type"); 2025 if (token.isAny(Token::kw_true, Token::kw_false)) { 2026 if (!eltTy.isInteger(1)) 2027 p.emitError(tokenLoc) 2028 << "expected i1 type for 'true' or 'false' values"; 2029 APInt apInt(eltTy.getWidth(), token.is(Token::kw_true), 2030 /*isSigned=*/false); 2031 intElements.push_back(apInt); 2032 continue; 2033 } 2034 2035 // Create APInt values for each element with the correct bitwidth. 2036 auto val = token.getUInt64IntegerValue(); 2037 if (!val.hasValue() || (isNegative ? (int64_t)-val.getValue() >= 0 2038 : (int64_t)val.getValue() < 0)) { 2039 p.emitError(tokenLoc, "integer constant out of range for attribute"); 2040 return nullptr; 2041 } 2042 APInt apInt(eltTy.getWidth(), val.getValue(), isNegative); 2043 if (apInt != val.getValue()) 2044 return (p.emitError(tokenLoc, "integer constant out of range for type"), 2045 nullptr); 2046 intElements.push_back(isNegative ? -apInt : apInt); 2047 } 2048 2049 return DenseElementsAttr::get(type, intElements); 2050 } 2051 2052 /// Build a Dense Float attribute for the given type. 2053 DenseElementsAttr TensorLiteralParser::getFloatAttr(llvm::SMLoc loc, 2054 ShapedType type, 2055 FloatType eltTy) { 2056 std::vector<APFloat> floatValues; 2057 floatValues.reserve(storage.size()); 2058 for (const auto &signAndToken : storage) { 2059 bool isNegative = signAndToken.first; 2060 const Token &token = signAndToken.second; 2061 2062 // Handle hexadecimal float literals. 2063 if (token.is(Token::integer) && token.getSpelling().startswith("0x")) { 2064 if (isNegative) { 2065 p.emitError(token.getLoc()) 2066 << "hexadecimal float literal should not have a leading minus"; 2067 return nullptr; 2068 } 2069 auto val = token.getUInt64IntegerValue(); 2070 if (!val.hasValue()) { 2071 p.emitError("hexadecimal float constant out of range for attribute"); 2072 return nullptr; 2073 } 2074 Optional<APFloat> apVal = buildHexadecimalFloatLiteral(&p, eltTy, *val); 2075 if (!apVal) 2076 return nullptr; 2077 floatValues.push_back(*apVal); 2078 continue; 2079 } 2080 2081 // Check to see if any decimal integers or booleans were parsed. 2082 if (!token.is(Token::floatliteral)) { 2083 p.emitError() << "expected floating-point elements, but parsed integer"; 2084 return nullptr; 2085 } 2086 2087 // Build the float values from tokens. 2088 auto val = token.getFloatingPointValue(); 2089 if (!val.hasValue()) { 2090 p.emitError("floating point value too large for attribute"); 2091 return nullptr; 2092 } 2093 // Treat BF16 as double because it is not supported in LLVM's APFloat. 2094 APFloat apVal(isNegative ? -*val : *val); 2095 if (!eltTy.isBF16() && !eltTy.isF64()) { 2096 bool unused; 2097 apVal.convert(eltTy.getFloatSemantics(), APFloat::rmNearestTiesToEven, 2098 &unused); 2099 } 2100 floatValues.push_back(apVal); 2101 } 2102 2103 return DenseElementsAttr::get(type, floatValues); 2104 } 2105 2106 /// Build a Dense attribute with hex data for the given type. 2107 DenseElementsAttr TensorLiteralParser::getHexAttr(llvm::SMLoc loc, 2108 ShapedType type) { 2109 Type elementType = type.getElementType(); 2110 if (!elementType.isa<FloatType>() && !elementType.isa<IntegerType>()) { 2111 p.emitError(loc) << "expected floating-point or integer element type, got " 2112 << elementType; 2113 return nullptr; 2114 } 2115 2116 std::string data; 2117 if (parseElementAttrHexValues(p, hexStorage.getValue(), data)) 2118 return nullptr; 2119 2120 // Check that the size of the hex data correpsonds to the size of the type, or 2121 // a splat of the type. 2122 // TODO: bf16 is currently stored as a double, this should be removed when 2123 // APFloat properly supports it. 2124 int64_t elementWidth = 2125 elementType.isBF16() ? 64 : elementType.getIntOrFloatBitWidth(); 2126 if (static_cast<int64_t>(data.size() * CHAR_BIT) != 2127 (type.getNumElements() * elementWidth)) { 2128 p.emitError(loc) << "elements hex data size is invalid for provided type: " 2129 << type; 2130 return nullptr; 2131 } 2132 2133 return DenseElementsAttr::getFromRawBuffer( 2134 type, ArrayRef<char>(data.data(), data.size()), /*isSplatBuffer=*/false); 2135 } 2136 2137 ParseResult TensorLiteralParser::parseElement() { 2138 switch (p.getToken().getKind()) { 2139 // Parse a boolean element. 2140 case Token::kw_true: 2141 case Token::kw_false: 2142 case Token::floatliteral: 2143 case Token::integer: 2144 storage.emplace_back(/*isNegative=*/false, p.getToken()); 2145 p.consumeToken(); 2146 break; 2147 2148 // Parse a signed integer or a negative floating-point element. 2149 case Token::minus: 2150 p.consumeToken(Token::minus); 2151 if (!p.getToken().isAny(Token::floatliteral, Token::integer)) 2152 return p.emitError("expected integer or floating point literal"); 2153 storage.emplace_back(/*isNegative=*/true, p.getToken()); 2154 p.consumeToken(); 2155 break; 2156 2157 default: 2158 return p.emitError("expected element literal of primitive type"); 2159 } 2160 2161 return success(); 2162 } 2163 2164 /// Parse a list of either lists or elements, returning the dimensions of the 2165 /// parsed sub-tensors in dims. For example: 2166 /// parseList([1, 2, 3]) -> Success, [3] 2167 /// parseList([[1, 2], [3, 4]]) -> Success, [2, 2] 2168 /// parseList([[1, 2], 3]) -> Failure 2169 /// parseList([[1, [2, 3]], [4, [5]]]) -> Failure 2170 ParseResult TensorLiteralParser::parseList(SmallVectorImpl<int64_t> &dims) { 2171 p.consumeToken(Token::l_square); 2172 2173 auto checkDims = [&](const SmallVectorImpl<int64_t> &prevDims, 2174 const SmallVectorImpl<int64_t> &newDims) -> ParseResult { 2175 if (prevDims == newDims) 2176 return success(); 2177 return p.emitError("tensor literal is invalid; ranks are not consistent " 2178 "between elements"); 2179 }; 2180 2181 bool first = true; 2182 SmallVector<int64_t, 4> newDims; 2183 unsigned size = 0; 2184 auto parseCommaSeparatedList = [&]() -> ParseResult { 2185 SmallVector<int64_t, 4> thisDims; 2186 if (p.getToken().getKind() == Token::l_square) { 2187 if (parseList(thisDims)) 2188 return failure(); 2189 } else if (parseElement()) { 2190 return failure(); 2191 } 2192 ++size; 2193 if (!first) 2194 return checkDims(newDims, thisDims); 2195 newDims = thisDims; 2196 first = false; 2197 return success(); 2198 }; 2199 if (p.parseCommaSeparatedListUntil(Token::r_square, parseCommaSeparatedList)) 2200 return failure(); 2201 2202 // Return the sublists' dimensions with 'size' prepended. 2203 dims.clear(); 2204 dims.push_back(size); 2205 dims.append(newDims.begin(), newDims.end()); 2206 return success(); 2207 } 2208 2209 /// Parse a dense elements attribute. 2210 Attribute Parser::parseDenseElementsAttr(Type attrType) { 2211 consumeToken(Token::kw_dense); 2212 if (parseToken(Token::less, "expected '<' after 'dense'")) 2213 return nullptr; 2214 2215 // Parse the literal data. 2216 TensorLiteralParser literalParser(*this); 2217 if (literalParser.parse(/*allowHex=*/true)) 2218 return nullptr; 2219 2220 if (parseToken(Token::greater, "expected '>'")) 2221 return nullptr; 2222 2223 auto typeLoc = getToken().getLoc(); 2224 auto type = parseElementsLiteralType(attrType); 2225 if (!type) 2226 return nullptr; 2227 return literalParser.getAttr(typeLoc, type); 2228 } 2229 2230 /// Shaped type for elements attribute. 2231 /// 2232 /// elements-literal-type ::= vector-type | ranked-tensor-type 2233 /// 2234 /// This method also checks the type has static shape. 2235 ShapedType Parser::parseElementsLiteralType(Type type) { 2236 // If the user didn't provide a type, parse the colon type for the literal. 2237 if (!type) { 2238 if (parseToken(Token::colon, "expected ':'")) 2239 return nullptr; 2240 if (!(type = parseType())) 2241 return nullptr; 2242 } 2243 2244 if (!type.isa<RankedTensorType>() && !type.isa<VectorType>()) { 2245 emitError("elements literal must be a ranked tensor or vector type"); 2246 return nullptr; 2247 } 2248 2249 auto sType = type.cast<ShapedType>(); 2250 if (!sType.hasStaticShape()) 2251 return (emitError("elements literal type must have static shape"), nullptr); 2252 2253 return sType; 2254 } 2255 2256 /// Parse a sparse elements attribute. 2257 Attribute Parser::parseSparseElementsAttr(Type attrType) { 2258 consumeToken(Token::kw_sparse); 2259 if (parseToken(Token::less, "Expected '<' after 'sparse'")) 2260 return nullptr; 2261 2262 /// Parse the indices. We don't allow hex values here as we may need to use 2263 /// the inferred shape. 2264 auto indicesLoc = getToken().getLoc(); 2265 TensorLiteralParser indiceParser(*this); 2266 if (indiceParser.parse(/*allowHex=*/false)) 2267 return nullptr; 2268 2269 if (parseToken(Token::comma, "expected ','")) 2270 return nullptr; 2271 2272 /// Parse the values. 2273 auto valuesLoc = getToken().getLoc(); 2274 TensorLiteralParser valuesParser(*this); 2275 if (valuesParser.parse(/*allowHex=*/true)) 2276 return nullptr; 2277 2278 if (parseToken(Token::greater, "expected '>'")) 2279 return nullptr; 2280 2281 auto type = parseElementsLiteralType(attrType); 2282 if (!type) 2283 return nullptr; 2284 2285 // If the indices are a splat, i.e. the literal parser parsed an element and 2286 // not a list, we set the shape explicitly. The indices are represented by a 2287 // 2-dimensional shape where the second dimension is the rank of the type. 2288 // Given that the parsed indices is a splat, we know that we only have one 2289 // indice and thus one for the first dimension. 2290 auto indiceEltType = builder.getIntegerType(64); 2291 ShapedType indicesType; 2292 if (indiceParser.getShape().empty()) { 2293 indicesType = RankedTensorType::get({1, type.getRank()}, indiceEltType); 2294 } else { 2295 // Otherwise, set the shape to the one parsed by the literal parser. 2296 indicesType = RankedTensorType::get(indiceParser.getShape(), indiceEltType); 2297 } 2298 auto indices = indiceParser.getAttr(indicesLoc, indicesType); 2299 2300 // If the values are a splat, set the shape explicitly based on the number of 2301 // indices. The number of indices is encoded in the first dimension of the 2302 // indice shape type. 2303 auto valuesEltType = type.getElementType(); 2304 ShapedType valuesType = 2305 valuesParser.getShape().empty() 2306 ? RankedTensorType::get({indicesType.getDimSize(0)}, valuesEltType) 2307 : RankedTensorType::get(valuesParser.getShape(), valuesEltType); 2308 auto values = valuesParser.getAttr(valuesLoc, valuesType); 2309 2310 /// Sanity check. 2311 if (valuesType.getRank() != 1) 2312 return (emitError("expected 1-d tensor for values"), nullptr); 2313 2314 auto sameShape = (indicesType.getRank() == 1) || 2315 (type.getRank() == indicesType.getDimSize(1)); 2316 auto sameElementNum = indicesType.getDimSize(0) == valuesType.getDimSize(0); 2317 if (!sameShape || !sameElementNum) { 2318 emitError() << "expected shape ([" << type.getShape() 2319 << "]); inferred shape of indices literal ([" 2320 << indicesType.getShape() 2321 << "]); inferred shape of values literal ([" 2322 << valuesType.getShape() << "])"; 2323 return nullptr; 2324 } 2325 2326 // Build the sparse elements attribute by the indices and values. 2327 return SparseElementsAttr::get(type, indices, values); 2328 } 2329 2330 //===----------------------------------------------------------------------===// 2331 // Location parsing. 2332 //===----------------------------------------------------------------------===// 2333 2334 /// Parse a location. 2335 /// 2336 /// location ::= `loc` inline-location 2337 /// inline-location ::= '(' location-inst ')' 2338 /// 2339 ParseResult Parser::parseLocation(LocationAttr &loc) { 2340 // Check for 'loc' identifier. 2341 if (parseToken(Token::kw_loc, "expected 'loc' keyword")) 2342 return emitError(); 2343 2344 // Parse the inline-location. 2345 if (parseToken(Token::l_paren, "expected '(' in inline location") || 2346 parseLocationInstance(loc) || 2347 parseToken(Token::r_paren, "expected ')' in inline location")) 2348 return failure(); 2349 return success(); 2350 } 2351 2352 /// Specific location instances. 2353 /// 2354 /// location-inst ::= filelinecol-location | 2355 /// name-location | 2356 /// callsite-location | 2357 /// fused-location | 2358 /// unknown-location 2359 /// filelinecol-location ::= string-literal ':' integer-literal 2360 /// ':' integer-literal 2361 /// name-location ::= string-literal 2362 /// callsite-location ::= 'callsite' '(' location-inst 'at' location-inst ')' 2363 /// fused-location ::= fused ('<' attribute-value '>')? 2364 /// '[' location-inst (location-inst ',')* ']' 2365 /// unknown-location ::= 'unknown' 2366 /// 2367 ParseResult Parser::parseCallSiteLocation(LocationAttr &loc) { 2368 consumeToken(Token::bare_identifier); 2369 2370 // Parse the '('. 2371 if (parseToken(Token::l_paren, "expected '(' in callsite location")) 2372 return failure(); 2373 2374 // Parse the callee location. 2375 LocationAttr calleeLoc; 2376 if (parseLocationInstance(calleeLoc)) 2377 return failure(); 2378 2379 // Parse the 'at'. 2380 if (getToken().isNot(Token::bare_identifier) || 2381 getToken().getSpelling() != "at") 2382 return emitError("expected 'at' in callsite location"); 2383 consumeToken(Token::bare_identifier); 2384 2385 // Parse the caller location. 2386 LocationAttr callerLoc; 2387 if (parseLocationInstance(callerLoc)) 2388 return failure(); 2389 2390 // Parse the ')'. 2391 if (parseToken(Token::r_paren, "expected ')' in callsite location")) 2392 return failure(); 2393 2394 // Return the callsite location. 2395 loc = CallSiteLoc::get(calleeLoc, callerLoc); 2396 return success(); 2397 } 2398 2399 ParseResult Parser::parseFusedLocation(LocationAttr &loc) { 2400 consumeToken(Token::bare_identifier); 2401 2402 // Try to parse the optional metadata. 2403 Attribute metadata; 2404 if (consumeIf(Token::less)) { 2405 metadata = parseAttribute(); 2406 if (!metadata) 2407 return emitError("expected valid attribute metadata"); 2408 // Parse the '>' token. 2409 if (parseToken(Token::greater, 2410 "expected '>' after fused location metadata")) 2411 return failure(); 2412 } 2413 2414 SmallVector<Location, 4> locations; 2415 auto parseElt = [&] { 2416 LocationAttr newLoc; 2417 if (parseLocationInstance(newLoc)) 2418 return failure(); 2419 locations.push_back(newLoc); 2420 return success(); 2421 }; 2422 2423 if (parseToken(Token::l_square, "expected '[' in fused location") || 2424 parseCommaSeparatedList(parseElt) || 2425 parseToken(Token::r_square, "expected ']' in fused location")) 2426 return failure(); 2427 2428 // Return the fused location. 2429 loc = FusedLoc::get(locations, metadata, getContext()); 2430 return success(); 2431 } 2432 2433 ParseResult Parser::parseNameOrFileLineColLocation(LocationAttr &loc) { 2434 auto *ctx = getContext(); 2435 auto str = getToken().getStringValue(); 2436 consumeToken(Token::string); 2437 2438 // If the next token is ':' this is a filelinecol location. 2439 if (consumeIf(Token::colon)) { 2440 // Parse the line number. 2441 if (getToken().isNot(Token::integer)) 2442 return emitError("expected integer line number in FileLineColLoc"); 2443 auto line = getToken().getUnsignedIntegerValue(); 2444 if (!line.hasValue()) 2445 return emitError("expected integer line number in FileLineColLoc"); 2446 consumeToken(Token::integer); 2447 2448 // Parse the ':'. 2449 if (parseToken(Token::colon, "expected ':' in FileLineColLoc")) 2450 return failure(); 2451 2452 // Parse the column number. 2453 if (getToken().isNot(Token::integer)) 2454 return emitError("expected integer column number in FileLineColLoc"); 2455 auto column = getToken().getUnsignedIntegerValue(); 2456 if (!column.hasValue()) 2457 return emitError("expected integer column number in FileLineColLoc"); 2458 consumeToken(Token::integer); 2459 2460 loc = FileLineColLoc::get(str, line.getValue(), column.getValue(), ctx); 2461 return success(); 2462 } 2463 2464 // Otherwise, this is a NameLoc. 2465 2466 // Check for a child location. 2467 if (consumeIf(Token::l_paren)) { 2468 auto childSourceLoc = getToken().getLoc(); 2469 2470 // Parse the child location. 2471 LocationAttr childLoc; 2472 if (parseLocationInstance(childLoc)) 2473 return failure(); 2474 2475 // The child must not be another NameLoc. 2476 if (childLoc.isa<NameLoc>()) 2477 return emitError(childSourceLoc, 2478 "child of NameLoc cannot be another NameLoc"); 2479 loc = NameLoc::get(Identifier::get(str, ctx), childLoc); 2480 2481 // Parse the closing ')'. 2482 if (parseToken(Token::r_paren, 2483 "expected ')' after child location of NameLoc")) 2484 return failure(); 2485 } else { 2486 loc = NameLoc::get(Identifier::get(str, ctx), ctx); 2487 } 2488 2489 return success(); 2490 } 2491 2492 ParseResult Parser::parseLocationInstance(LocationAttr &loc) { 2493 // Handle either name or filelinecol locations. 2494 if (getToken().is(Token::string)) 2495 return parseNameOrFileLineColLocation(loc); 2496 2497 // Bare tokens required for other cases. 2498 if (!getToken().is(Token::bare_identifier)) 2499 return emitError("expected location instance"); 2500 2501 // Check for the 'callsite' signifying a callsite location. 2502 if (getToken().getSpelling() == "callsite") 2503 return parseCallSiteLocation(loc); 2504 2505 // If the token is 'fused', then this is a fused location. 2506 if (getToken().getSpelling() == "fused") 2507 return parseFusedLocation(loc); 2508 2509 // Check for a 'unknown' for an unknown location. 2510 if (getToken().getSpelling() == "unknown") { 2511 consumeToken(Token::bare_identifier); 2512 loc = UnknownLoc::get(getContext()); 2513 return success(); 2514 } 2515 2516 return emitError("expected location instance"); 2517 } 2518 2519 //===----------------------------------------------------------------------===// 2520 // Affine parsing. 2521 //===----------------------------------------------------------------------===// 2522 2523 /// Lower precedence ops (all at the same precedence level). LNoOp is false in 2524 /// the boolean sense. 2525 enum AffineLowPrecOp { 2526 /// Null value. 2527 LNoOp, 2528 Add, 2529 Sub 2530 }; 2531 2532 /// Higher precedence ops - all at the same precedence level. HNoOp is false 2533 /// in the boolean sense. 2534 enum AffineHighPrecOp { 2535 /// Null value. 2536 HNoOp, 2537 Mul, 2538 FloorDiv, 2539 CeilDiv, 2540 Mod 2541 }; 2542 2543 namespace { 2544 /// This is a specialized parser for affine structures (affine maps, affine 2545 /// expressions, and integer sets), maintaining the state transient to their 2546 /// bodies. 2547 class AffineParser : public Parser { 2548 public: 2549 AffineParser(ParserState &state, bool allowParsingSSAIds = false, 2550 function_ref<ParseResult(bool)> parseElement = nullptr) 2551 : Parser(state), allowParsingSSAIds(allowParsingSSAIds), 2552 parseElement(parseElement), numDimOperands(0), numSymbolOperands(0) {} 2553 2554 AffineMap parseAffineMapRange(unsigned numDims, unsigned numSymbols); 2555 ParseResult parseAffineMapOrIntegerSetInline(AffineMap &map, IntegerSet &set); 2556 IntegerSet parseIntegerSetConstraints(unsigned numDims, unsigned numSymbols); 2557 ParseResult parseAffineMapOfSSAIds(AffineMap &map, 2558 OpAsmParser::Delimiter delimiter); 2559 void getDimsAndSymbolSSAIds(SmallVectorImpl<StringRef> &dimAndSymbolSSAIds, 2560 unsigned &numDims); 2561 2562 private: 2563 // Binary affine op parsing. 2564 AffineLowPrecOp consumeIfLowPrecOp(); 2565 AffineHighPrecOp consumeIfHighPrecOp(); 2566 2567 // Identifier lists for polyhedral structures. 2568 ParseResult parseDimIdList(unsigned &numDims); 2569 ParseResult parseSymbolIdList(unsigned &numSymbols); 2570 ParseResult parseDimAndOptionalSymbolIdList(unsigned &numDims, 2571 unsigned &numSymbols); 2572 ParseResult parseIdentifierDefinition(AffineExpr idExpr); 2573 2574 AffineExpr parseAffineExpr(); 2575 AffineExpr parseParentheticalExpr(); 2576 AffineExpr parseNegateExpression(AffineExpr lhs); 2577 AffineExpr parseIntegerExpr(); 2578 AffineExpr parseBareIdExpr(); 2579 AffineExpr parseSSAIdExpr(bool isSymbol); 2580 AffineExpr parseSymbolSSAIdExpr(); 2581 2582 AffineExpr getAffineBinaryOpExpr(AffineHighPrecOp op, AffineExpr lhs, 2583 AffineExpr rhs, SMLoc opLoc); 2584 AffineExpr getAffineBinaryOpExpr(AffineLowPrecOp op, AffineExpr lhs, 2585 AffineExpr rhs); 2586 AffineExpr parseAffineOperandExpr(AffineExpr lhs); 2587 AffineExpr parseAffineLowPrecOpExpr(AffineExpr llhs, AffineLowPrecOp llhsOp); 2588 AffineExpr parseAffineHighPrecOpExpr(AffineExpr llhs, AffineHighPrecOp llhsOp, 2589 SMLoc llhsOpLoc); 2590 AffineExpr parseAffineConstraint(bool *isEq); 2591 2592 private: 2593 bool allowParsingSSAIds; 2594 function_ref<ParseResult(bool)> parseElement; 2595 unsigned numDimOperands; 2596 unsigned numSymbolOperands; 2597 SmallVector<std::pair<StringRef, AffineExpr>, 4> dimsAndSymbols; 2598 }; 2599 } // end anonymous namespace 2600 2601 /// Create an affine binary high precedence op expression (mul's, div's, mod). 2602 /// opLoc is the location of the op token to be used to report errors 2603 /// for non-conforming expressions. 2604 AffineExpr AffineParser::getAffineBinaryOpExpr(AffineHighPrecOp op, 2605 AffineExpr lhs, AffineExpr rhs, 2606 SMLoc opLoc) { 2607 // TODO: make the error location info accurate. 2608 switch (op) { 2609 case Mul: 2610 if (!lhs.isSymbolicOrConstant() && !rhs.isSymbolicOrConstant()) { 2611 emitError(opLoc, "non-affine expression: at least one of the multiply " 2612 "operands has to be either a constant or symbolic"); 2613 return nullptr; 2614 } 2615 return lhs * rhs; 2616 case FloorDiv: 2617 if (!rhs.isSymbolicOrConstant()) { 2618 emitError(opLoc, "non-affine expression: right operand of floordiv " 2619 "has to be either a constant or symbolic"); 2620 return nullptr; 2621 } 2622 return lhs.floorDiv(rhs); 2623 case CeilDiv: 2624 if (!rhs.isSymbolicOrConstant()) { 2625 emitError(opLoc, "non-affine expression: right operand of ceildiv " 2626 "has to be either a constant or symbolic"); 2627 return nullptr; 2628 } 2629 return lhs.ceilDiv(rhs); 2630 case Mod: 2631 if (!rhs.isSymbolicOrConstant()) { 2632 emitError(opLoc, "non-affine expression: right operand of mod " 2633 "has to be either a constant or symbolic"); 2634 return nullptr; 2635 } 2636 return lhs % rhs; 2637 case HNoOp: 2638 llvm_unreachable("can't create affine expression for null high prec op"); 2639 return nullptr; 2640 } 2641 llvm_unreachable("Unknown AffineHighPrecOp"); 2642 } 2643 2644 /// Create an affine binary low precedence op expression (add, sub). 2645 AffineExpr AffineParser::getAffineBinaryOpExpr(AffineLowPrecOp op, 2646 AffineExpr lhs, AffineExpr rhs) { 2647 switch (op) { 2648 case AffineLowPrecOp::Add: 2649 return lhs + rhs; 2650 case AffineLowPrecOp::Sub: 2651 return lhs - rhs; 2652 case AffineLowPrecOp::LNoOp: 2653 llvm_unreachable("can't create affine expression for null low prec op"); 2654 return nullptr; 2655 } 2656 llvm_unreachable("Unknown AffineLowPrecOp"); 2657 } 2658 2659 /// Consume this token if it is a lower precedence affine op (there are only 2660 /// two precedence levels). 2661 AffineLowPrecOp AffineParser::consumeIfLowPrecOp() { 2662 switch (getToken().getKind()) { 2663 case Token::plus: 2664 consumeToken(Token::plus); 2665 return AffineLowPrecOp::Add; 2666 case Token::minus: 2667 consumeToken(Token::minus); 2668 return AffineLowPrecOp::Sub; 2669 default: 2670 return AffineLowPrecOp::LNoOp; 2671 } 2672 } 2673 2674 /// Consume this token if it is a higher precedence affine op (there are only 2675 /// two precedence levels) 2676 AffineHighPrecOp AffineParser::consumeIfHighPrecOp() { 2677 switch (getToken().getKind()) { 2678 case Token::star: 2679 consumeToken(Token::star); 2680 return Mul; 2681 case Token::kw_floordiv: 2682 consumeToken(Token::kw_floordiv); 2683 return FloorDiv; 2684 case Token::kw_ceildiv: 2685 consumeToken(Token::kw_ceildiv); 2686 return CeilDiv; 2687 case Token::kw_mod: 2688 consumeToken(Token::kw_mod); 2689 return Mod; 2690 default: 2691 return HNoOp; 2692 } 2693 } 2694 2695 /// Parse a high precedence op expression list: mul, div, and mod are high 2696 /// precedence binary ops, i.e., parse a 2697 /// expr_1 op_1 expr_2 op_2 ... expr_n 2698 /// where op_1, op_2 are all a AffineHighPrecOp (mul, div, mod). 2699 /// All affine binary ops are left associative. 2700 /// Given llhs, returns (llhs llhsOp lhs) op rhs, or (lhs op rhs) if llhs is 2701 /// null. If no rhs can be found, returns (llhs llhsOp lhs) or lhs if llhs is 2702 /// null. llhsOpLoc is the location of the llhsOp token that will be used to 2703 /// report an error for non-conforming expressions. 2704 AffineExpr AffineParser::parseAffineHighPrecOpExpr(AffineExpr llhs, 2705 AffineHighPrecOp llhsOp, 2706 SMLoc llhsOpLoc) { 2707 AffineExpr lhs = parseAffineOperandExpr(llhs); 2708 if (!lhs) 2709 return nullptr; 2710 2711 // Found an LHS. Parse the remaining expression. 2712 auto opLoc = getToken().getLoc(); 2713 if (AffineHighPrecOp op = consumeIfHighPrecOp()) { 2714 if (llhs) { 2715 AffineExpr expr = getAffineBinaryOpExpr(llhsOp, llhs, lhs, opLoc); 2716 if (!expr) 2717 return nullptr; 2718 return parseAffineHighPrecOpExpr(expr, op, opLoc); 2719 } 2720 // No LLHS, get RHS 2721 return parseAffineHighPrecOpExpr(lhs, op, opLoc); 2722 } 2723 2724 // This is the last operand in this expression. 2725 if (llhs) 2726 return getAffineBinaryOpExpr(llhsOp, llhs, lhs, llhsOpLoc); 2727 2728 // No llhs, 'lhs' itself is the expression. 2729 return lhs; 2730 } 2731 2732 /// Parse an affine expression inside parentheses. 2733 /// 2734 /// affine-expr ::= `(` affine-expr `)` 2735 AffineExpr AffineParser::parseParentheticalExpr() { 2736 if (parseToken(Token::l_paren, "expected '('")) 2737 return nullptr; 2738 if (getToken().is(Token::r_paren)) 2739 return (emitError("no expression inside parentheses"), nullptr); 2740 2741 auto expr = parseAffineExpr(); 2742 if (!expr) 2743 return nullptr; 2744 if (parseToken(Token::r_paren, "expected ')'")) 2745 return nullptr; 2746 2747 return expr; 2748 } 2749 2750 /// Parse the negation expression. 2751 /// 2752 /// affine-expr ::= `-` affine-expr 2753 AffineExpr AffineParser::parseNegateExpression(AffineExpr lhs) { 2754 if (parseToken(Token::minus, "expected '-'")) 2755 return nullptr; 2756 2757 AffineExpr operand = parseAffineOperandExpr(lhs); 2758 // Since negation has the highest precedence of all ops (including high 2759 // precedence ops) but lower than parentheses, we are only going to use 2760 // parseAffineOperandExpr instead of parseAffineExpr here. 2761 if (!operand) 2762 // Extra error message although parseAffineOperandExpr would have 2763 // complained. Leads to a better diagnostic. 2764 return (emitError("missing operand of negation"), nullptr); 2765 return (-1) * operand; 2766 } 2767 2768 /// Parse a bare id that may appear in an affine expression. 2769 /// 2770 /// affine-expr ::= bare-id 2771 AffineExpr AffineParser::parseBareIdExpr() { 2772 if (getToken().isNot(Token::bare_identifier)) 2773 return (emitError("expected bare identifier"), nullptr); 2774 2775 StringRef sRef = getTokenSpelling(); 2776 for (auto entry : dimsAndSymbols) { 2777 if (entry.first == sRef) { 2778 consumeToken(Token::bare_identifier); 2779 return entry.second; 2780 } 2781 } 2782 2783 return (emitError("use of undeclared identifier"), nullptr); 2784 } 2785 2786 /// Parse an SSA id which may appear in an affine expression. 2787 AffineExpr AffineParser::parseSSAIdExpr(bool isSymbol) { 2788 if (!allowParsingSSAIds) 2789 return (emitError("unexpected ssa identifier"), nullptr); 2790 if (getToken().isNot(Token::percent_identifier)) 2791 return (emitError("expected ssa identifier"), nullptr); 2792 auto name = getTokenSpelling(); 2793 // Check if we already parsed this SSA id. 2794 for (auto entry : dimsAndSymbols) { 2795 if (entry.first == name) { 2796 consumeToken(Token::percent_identifier); 2797 return entry.second; 2798 } 2799 } 2800 // Parse the SSA id and add an AffineDim/SymbolExpr to represent it. 2801 if (parseElement(isSymbol)) 2802 return (emitError("failed to parse ssa identifier"), nullptr); 2803 auto idExpr = isSymbol 2804 ? getAffineSymbolExpr(numSymbolOperands++, getContext()) 2805 : getAffineDimExpr(numDimOperands++, getContext()); 2806 dimsAndSymbols.push_back({name, idExpr}); 2807 return idExpr; 2808 } 2809 2810 AffineExpr AffineParser::parseSymbolSSAIdExpr() { 2811 if (parseToken(Token::kw_symbol, "expected symbol keyword") || 2812 parseToken(Token::l_paren, "expected '(' at start of SSA symbol")) 2813 return nullptr; 2814 AffineExpr symbolExpr = parseSSAIdExpr(/*isSymbol=*/true); 2815 if (!symbolExpr) 2816 return nullptr; 2817 if (parseToken(Token::r_paren, "expected ')' at end of SSA symbol")) 2818 return nullptr; 2819 return symbolExpr; 2820 } 2821 2822 /// Parse a positive integral constant appearing in an affine expression. 2823 /// 2824 /// affine-expr ::= integer-literal 2825 AffineExpr AffineParser::parseIntegerExpr() { 2826 auto val = getToken().getUInt64IntegerValue(); 2827 if (!val.hasValue() || (int64_t)val.getValue() < 0) 2828 return (emitError("constant too large for index"), nullptr); 2829 2830 consumeToken(Token::integer); 2831 return builder.getAffineConstantExpr((int64_t)val.getValue()); 2832 } 2833 2834 /// Parses an expression that can be a valid operand of an affine expression. 2835 /// lhs: if non-null, lhs is an affine expression that is the lhs of a binary 2836 /// operator, the rhs of which is being parsed. This is used to determine 2837 /// whether an error should be emitted for a missing right operand. 2838 // Eg: for an expression without parentheses (like i + j + k + l), each 2839 // of the four identifiers is an operand. For i + j*k + l, j*k is not an 2840 // operand expression, it's an op expression and will be parsed via 2841 // parseAffineHighPrecOpExpression(). However, for i + (j*k) + -l, (j*k) and 2842 // -l are valid operands that will be parsed by this function. 2843 AffineExpr AffineParser::parseAffineOperandExpr(AffineExpr lhs) { 2844 switch (getToken().getKind()) { 2845 case Token::bare_identifier: 2846 return parseBareIdExpr(); 2847 case Token::kw_symbol: 2848 return parseSymbolSSAIdExpr(); 2849 case Token::percent_identifier: 2850 return parseSSAIdExpr(/*isSymbol=*/false); 2851 case Token::integer: 2852 return parseIntegerExpr(); 2853 case Token::l_paren: 2854 return parseParentheticalExpr(); 2855 case Token::minus: 2856 return parseNegateExpression(lhs); 2857 case Token::kw_ceildiv: 2858 case Token::kw_floordiv: 2859 case Token::kw_mod: 2860 case Token::plus: 2861 case Token::star: 2862 if (lhs) 2863 emitError("missing right operand of binary operator"); 2864 else 2865 emitError("missing left operand of binary operator"); 2866 return nullptr; 2867 default: 2868 if (lhs) 2869 emitError("missing right operand of binary operator"); 2870 else 2871 emitError("expected affine expression"); 2872 return nullptr; 2873 } 2874 } 2875 2876 /// Parse affine expressions that are bare-id's, integer constants, 2877 /// parenthetical affine expressions, and affine op expressions that are a 2878 /// composition of those. 2879 /// 2880 /// All binary op's associate from left to right. 2881 /// 2882 /// {add, sub} have lower precedence than {mul, div, and mod}. 2883 /// 2884 /// Add, sub'are themselves at the same precedence level. Mul, floordiv, 2885 /// ceildiv, and mod are at the same higher precedence level. Negation has 2886 /// higher precedence than any binary op. 2887 /// 2888 /// llhs: the affine expression appearing on the left of the one being parsed. 2889 /// This function will return ((llhs llhsOp lhs) op rhs) if llhs is non null, 2890 /// and lhs op rhs otherwise; if there is no rhs, llhs llhsOp lhs is returned 2891 /// if llhs is non-null; otherwise lhs is returned. This is to deal with left 2892 /// associativity. 2893 /// 2894 /// Eg: when the expression is e1 + e2*e3 + e4, with e1 as llhs, this function 2895 /// will return the affine expr equivalent of (e1 + (e2*e3)) + e4, where 2896 /// (e2*e3) will be parsed using parseAffineHighPrecOpExpr(). 2897 AffineExpr AffineParser::parseAffineLowPrecOpExpr(AffineExpr llhs, 2898 AffineLowPrecOp llhsOp) { 2899 AffineExpr lhs; 2900 if (!(lhs = parseAffineOperandExpr(llhs))) 2901 return nullptr; 2902 2903 // Found an LHS. Deal with the ops. 2904 if (AffineLowPrecOp lOp = consumeIfLowPrecOp()) { 2905 if (llhs) { 2906 AffineExpr sum = getAffineBinaryOpExpr(llhsOp, llhs, lhs); 2907 return parseAffineLowPrecOpExpr(sum, lOp); 2908 } 2909 // No LLHS, get RHS and form the expression. 2910 return parseAffineLowPrecOpExpr(lhs, lOp); 2911 } 2912 auto opLoc = getToken().getLoc(); 2913 if (AffineHighPrecOp hOp = consumeIfHighPrecOp()) { 2914 // We have a higher precedence op here. Get the rhs operand for the llhs 2915 // through parseAffineHighPrecOpExpr. 2916 AffineExpr highRes = parseAffineHighPrecOpExpr(lhs, hOp, opLoc); 2917 if (!highRes) 2918 return nullptr; 2919 2920 // If llhs is null, the product forms the first operand of the yet to be 2921 // found expression. If non-null, the op to associate with llhs is llhsOp. 2922 AffineExpr expr = 2923 llhs ? getAffineBinaryOpExpr(llhsOp, llhs, highRes) : highRes; 2924 2925 // Recurse for subsequent low prec op's after the affine high prec op 2926 // expression. 2927 if (AffineLowPrecOp nextOp = consumeIfLowPrecOp()) 2928 return parseAffineLowPrecOpExpr(expr, nextOp); 2929 return expr; 2930 } 2931 // Last operand in the expression list. 2932 if (llhs) 2933 return getAffineBinaryOpExpr(llhsOp, llhs, lhs); 2934 // No llhs, 'lhs' itself is the expression. 2935 return lhs; 2936 } 2937 2938 /// Parse an affine expression. 2939 /// affine-expr ::= `(` affine-expr `)` 2940 /// | `-` affine-expr 2941 /// | affine-expr `+` affine-expr 2942 /// | affine-expr `-` affine-expr 2943 /// | affine-expr `*` affine-expr 2944 /// | affine-expr `floordiv` affine-expr 2945 /// | affine-expr `ceildiv` affine-expr 2946 /// | affine-expr `mod` affine-expr 2947 /// | bare-id 2948 /// | integer-literal 2949 /// 2950 /// Additional conditions are checked depending on the production. For eg., 2951 /// one of the operands for `*` has to be either constant/symbolic; the second 2952 /// operand for floordiv, ceildiv, and mod has to be a positive integer. 2953 AffineExpr AffineParser::parseAffineExpr() { 2954 return parseAffineLowPrecOpExpr(nullptr, AffineLowPrecOp::LNoOp); 2955 } 2956 2957 /// Parse a dim or symbol from the lists appearing before the actual 2958 /// expressions of the affine map. Update our state to store the 2959 /// dimensional/symbolic identifier. 2960 ParseResult AffineParser::parseIdentifierDefinition(AffineExpr idExpr) { 2961 if (getToken().isNot(Token::bare_identifier)) 2962 return emitError("expected bare identifier"); 2963 2964 auto name = getTokenSpelling(); 2965 for (auto entry : dimsAndSymbols) { 2966 if (entry.first == name) 2967 return emitError("redefinition of identifier '" + name + "'"); 2968 } 2969 consumeToken(Token::bare_identifier); 2970 2971 dimsAndSymbols.push_back({name, idExpr}); 2972 return success(); 2973 } 2974 2975 /// Parse the list of dimensional identifiers to an affine map. 2976 ParseResult AffineParser::parseDimIdList(unsigned &numDims) { 2977 if (parseToken(Token::l_paren, 2978 "expected '(' at start of dimensional identifiers list")) { 2979 return failure(); 2980 } 2981 2982 auto parseElt = [&]() -> ParseResult { 2983 auto dimension = getAffineDimExpr(numDims++, getContext()); 2984 return parseIdentifierDefinition(dimension); 2985 }; 2986 return parseCommaSeparatedListUntil(Token::r_paren, parseElt); 2987 } 2988 2989 /// Parse the list of symbolic identifiers to an affine map. 2990 ParseResult AffineParser::parseSymbolIdList(unsigned &numSymbols) { 2991 consumeToken(Token::l_square); 2992 auto parseElt = [&]() -> ParseResult { 2993 auto symbol = getAffineSymbolExpr(numSymbols++, getContext()); 2994 return parseIdentifierDefinition(symbol); 2995 }; 2996 return parseCommaSeparatedListUntil(Token::r_square, parseElt); 2997 } 2998 2999 /// Parse the list of symbolic identifiers to an affine map. 3000 ParseResult 3001 AffineParser::parseDimAndOptionalSymbolIdList(unsigned &numDims, 3002 unsigned &numSymbols) { 3003 if (parseDimIdList(numDims)) { 3004 return failure(); 3005 } 3006 if (!getToken().is(Token::l_square)) { 3007 numSymbols = 0; 3008 return success(); 3009 } 3010 return parseSymbolIdList(numSymbols); 3011 } 3012 3013 /// Parses an ambiguous affine map or integer set definition inline. 3014 ParseResult AffineParser::parseAffineMapOrIntegerSetInline(AffineMap &map, 3015 IntegerSet &set) { 3016 unsigned numDims = 0, numSymbols = 0; 3017 3018 // List of dimensional and optional symbol identifiers. 3019 if (parseDimAndOptionalSymbolIdList(numDims, numSymbols)) { 3020 return failure(); 3021 } 3022 3023 // This is needed for parsing attributes as we wouldn't know whether we would 3024 // be parsing an integer set attribute or an affine map attribute. 3025 bool isArrow = getToken().is(Token::arrow); 3026 bool isColon = getToken().is(Token::colon); 3027 if (!isArrow && !isColon) { 3028 return emitError("expected '->' or ':'"); 3029 } else if (isArrow) { 3030 parseToken(Token::arrow, "expected '->' or '['"); 3031 map = parseAffineMapRange(numDims, numSymbols); 3032 return map ? success() : failure(); 3033 } else if (parseToken(Token::colon, "expected ':' or '['")) { 3034 return failure(); 3035 } 3036 3037 if ((set = parseIntegerSetConstraints(numDims, numSymbols))) 3038 return success(); 3039 3040 return failure(); 3041 } 3042 3043 /// Parse an AffineMap where the dim and symbol identifiers are SSA ids. 3044 ParseResult 3045 AffineParser::parseAffineMapOfSSAIds(AffineMap &map, 3046 OpAsmParser::Delimiter delimiter) { 3047 Token::Kind rightToken; 3048 switch (delimiter) { 3049 case OpAsmParser::Delimiter::Square: 3050 if (parseToken(Token::l_square, "expected '['")) 3051 return failure(); 3052 rightToken = Token::r_square; 3053 break; 3054 case OpAsmParser::Delimiter::Paren: 3055 if (parseToken(Token::l_paren, "expected '('")) 3056 return failure(); 3057 rightToken = Token::r_paren; 3058 break; 3059 default: 3060 return emitError("unexpected delimiter"); 3061 } 3062 3063 SmallVector<AffineExpr, 4> exprs; 3064 auto parseElt = [&]() -> ParseResult { 3065 auto elt = parseAffineExpr(); 3066 exprs.push_back(elt); 3067 return elt ? success() : failure(); 3068 }; 3069 3070 // Parse a multi-dimensional affine expression (a comma-separated list of 3071 // 1-d affine expressions); the list cannot be empty. Grammar: 3072 // multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `) 3073 if (parseCommaSeparatedListUntil(rightToken, parseElt, 3074 /*allowEmptyList=*/true)) 3075 return failure(); 3076 // Parsed a valid affine map. 3077 if (exprs.empty()) 3078 map = AffineMap::get(getContext()); 3079 else 3080 map = AffineMap::get(numDimOperands, dimsAndSymbols.size() - numDimOperands, 3081 exprs); 3082 return success(); 3083 } 3084 3085 /// Parse the range and sizes affine map definition inline. 3086 /// 3087 /// affine-map ::= dim-and-symbol-id-lists `->` multi-dim-affine-expr 3088 /// 3089 /// multi-dim-affine-expr ::= `(` `)` 3090 /// multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `)` 3091 AffineMap AffineParser::parseAffineMapRange(unsigned numDims, 3092 unsigned numSymbols) { 3093 parseToken(Token::l_paren, "expected '(' at start of affine map range"); 3094 3095 SmallVector<AffineExpr, 4> exprs; 3096 auto parseElt = [&]() -> ParseResult { 3097 auto elt = parseAffineExpr(); 3098 ParseResult res = elt ? success() : failure(); 3099 exprs.push_back(elt); 3100 return res; 3101 }; 3102 3103 // Parse a multi-dimensional affine expression (a comma-separated list of 3104 // 1-d affine expressions); the list cannot be empty. Grammar: 3105 // multi-dim-affine-expr ::= `(` affine-expr (`,` affine-expr)* `) 3106 if (parseCommaSeparatedListUntil(Token::r_paren, parseElt, true)) 3107 return AffineMap(); 3108 3109 if (exprs.empty()) 3110 return AffineMap::get(getContext()); 3111 3112 // Parsed a valid affine map. 3113 return AffineMap::get(numDims, numSymbols, exprs); 3114 } 3115 3116 /// Parse an affine constraint. 3117 /// affine-constraint ::= affine-expr `>=` `0` 3118 /// | affine-expr `==` `0` 3119 /// 3120 /// isEq is set to true if the parsed constraint is an equality, false if it 3121 /// is an inequality (greater than or equal). 3122 /// 3123 AffineExpr AffineParser::parseAffineConstraint(bool *isEq) { 3124 AffineExpr expr = parseAffineExpr(); 3125 if (!expr) 3126 return nullptr; 3127 3128 if (consumeIf(Token::greater) && consumeIf(Token::equal) && 3129 getToken().is(Token::integer)) { 3130 auto dim = getToken().getUnsignedIntegerValue(); 3131 if (dim.hasValue() && dim.getValue() == 0) { 3132 consumeToken(Token::integer); 3133 *isEq = false; 3134 return expr; 3135 } 3136 return (emitError("expected '0' after '>='"), nullptr); 3137 } 3138 3139 if (consumeIf(Token::equal) && consumeIf(Token::equal) && 3140 getToken().is(Token::integer)) { 3141 auto dim = getToken().getUnsignedIntegerValue(); 3142 if (dim.hasValue() && dim.getValue() == 0) { 3143 consumeToken(Token::integer); 3144 *isEq = true; 3145 return expr; 3146 } 3147 return (emitError("expected '0' after '=='"), nullptr); 3148 } 3149 3150 return (emitError("expected '== 0' or '>= 0' at end of affine constraint"), 3151 nullptr); 3152 } 3153 3154 /// Parse the constraints that are part of an integer set definition. 3155 /// integer-set-inline 3156 /// ::= dim-and-symbol-id-lists `:` 3157 /// '(' affine-constraint-conjunction? ')' 3158 /// affine-constraint-conjunction ::= affine-constraint (`,` 3159 /// affine-constraint)* 3160 /// 3161 IntegerSet AffineParser::parseIntegerSetConstraints(unsigned numDims, 3162 unsigned numSymbols) { 3163 if (parseToken(Token::l_paren, 3164 "expected '(' at start of integer set constraint list")) 3165 return IntegerSet(); 3166 3167 SmallVector<AffineExpr, 4> constraints; 3168 SmallVector<bool, 4> isEqs; 3169 auto parseElt = [&]() -> ParseResult { 3170 bool isEq; 3171 auto elt = parseAffineConstraint(&isEq); 3172 ParseResult res = elt ? success() : failure(); 3173 if (elt) { 3174 constraints.push_back(elt); 3175 isEqs.push_back(isEq); 3176 } 3177 return res; 3178 }; 3179 3180 // Parse a list of affine constraints (comma-separated). 3181 if (parseCommaSeparatedListUntil(Token::r_paren, parseElt, true)) 3182 return IntegerSet(); 3183 3184 // If no constraints were parsed, then treat this as a degenerate 'true' case. 3185 if (constraints.empty()) { 3186 /* 0 == 0 */ 3187 auto zero = getAffineConstantExpr(0, getContext()); 3188 return IntegerSet::get(numDims, numSymbols, zero, true); 3189 } 3190 3191 // Parsed a valid integer set. 3192 return IntegerSet::get(numDims, numSymbols, constraints, isEqs); 3193 } 3194 3195 /// Parse an ambiguous reference to either and affine map or an integer set. 3196 ParseResult Parser::parseAffineMapOrIntegerSetReference(AffineMap &map, 3197 IntegerSet &set) { 3198 return AffineParser(state).parseAffineMapOrIntegerSetInline(map, set); 3199 } 3200 ParseResult Parser::parseAffineMapReference(AffineMap &map) { 3201 llvm::SMLoc curLoc = getToken().getLoc(); 3202 IntegerSet set; 3203 if (parseAffineMapOrIntegerSetReference(map, set)) 3204 return failure(); 3205 if (set) 3206 return emitError(curLoc, "expected AffineMap, but got IntegerSet"); 3207 return success(); 3208 } 3209 ParseResult Parser::parseIntegerSetReference(IntegerSet &set) { 3210 llvm::SMLoc curLoc = getToken().getLoc(); 3211 AffineMap map; 3212 if (parseAffineMapOrIntegerSetReference(map, set)) 3213 return failure(); 3214 if (map) 3215 return emitError(curLoc, "expected IntegerSet, but got AffineMap"); 3216 return success(); 3217 } 3218 3219 /// Parse an AffineMap of SSA ids. The callback 'parseElement' is used to 3220 /// parse SSA value uses encountered while parsing affine expressions. 3221 ParseResult 3222 Parser::parseAffineMapOfSSAIds(AffineMap &map, 3223 function_ref<ParseResult(bool)> parseElement, 3224 OpAsmParser::Delimiter delimiter) { 3225 return AffineParser(state, /*allowParsingSSAIds=*/true, parseElement) 3226 .parseAffineMapOfSSAIds(map, delimiter); 3227 } 3228 3229 //===----------------------------------------------------------------------===// 3230 // OperationParser 3231 //===----------------------------------------------------------------------===// 3232 3233 namespace { 3234 /// This class provides support for parsing operations and regions of 3235 /// operations. 3236 class OperationParser : public Parser { 3237 public: 3238 OperationParser(ParserState &state, ModuleOp moduleOp) 3239 : Parser(state), opBuilder(moduleOp.getBodyRegion()), moduleOp(moduleOp) { 3240 } 3241 3242 ~OperationParser(); 3243 3244 /// After parsing is finished, this function must be called to see if there 3245 /// are any remaining issues. 3246 ParseResult finalize(); 3247 3248 //===--------------------------------------------------------------------===// 3249 // SSA Value Handling 3250 //===--------------------------------------------------------------------===// 3251 3252 /// This represents a use of an SSA value in the program. The first two 3253 /// entries in the tuple are the name and result number of a reference. The 3254 /// third is the location of the reference, which is used in case this ends 3255 /// up being a use of an undefined value. 3256 struct SSAUseInfo { 3257 StringRef name; // Value name, e.g. %42 or %abc 3258 unsigned number; // Number, specified with #12 3259 SMLoc loc; // Location of first definition or use. 3260 }; 3261 3262 /// Push a new SSA name scope to the parser. 3263 void pushSSANameScope(bool isIsolated); 3264 3265 /// Pop the last SSA name scope from the parser. 3266 ParseResult popSSANameScope(); 3267 3268 /// Register a definition of a value with the symbol table. 3269 ParseResult addDefinition(SSAUseInfo useInfo, Value value); 3270 3271 /// Parse an optional list of SSA uses into 'results'. 3272 ParseResult parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results); 3273 3274 /// Parse a single SSA use into 'result'. 3275 ParseResult parseSSAUse(SSAUseInfo &result); 3276 3277 /// Given a reference to an SSA value and its type, return a reference. This 3278 /// returns null on failure. 3279 Value resolveSSAUse(SSAUseInfo useInfo, Type type); 3280 3281 ParseResult parseSSADefOrUseAndType( 3282 const std::function<ParseResult(SSAUseInfo, Type)> &action); 3283 3284 ParseResult parseOptionalSSAUseAndTypeList(SmallVectorImpl<Value> &results); 3285 3286 /// Return the location of the value identified by its name and number if it 3287 /// has been already reference. 3288 Optional<SMLoc> getReferenceLoc(StringRef name, unsigned number) { 3289 auto &values = isolatedNameScopes.back().values; 3290 if (!values.count(name) || number >= values[name].size()) 3291 return {}; 3292 if (values[name][number].first) 3293 return values[name][number].second; 3294 return {}; 3295 } 3296 3297 //===--------------------------------------------------------------------===// 3298 // Operation Parsing 3299 //===--------------------------------------------------------------------===// 3300 3301 /// Parse an operation instance. 3302 ParseResult parseOperation(); 3303 3304 /// Parse a single operation successor. 3305 ParseResult parseSuccessor(Block *&dest); 3306 3307 /// Parse a comma-separated list of operation successors in brackets. 3308 ParseResult parseSuccessors(SmallVectorImpl<Block *> &destinations); 3309 3310 /// Parse an operation instance that is in the generic form. 3311 Operation *parseGenericOperation(); 3312 3313 /// Parse an operation instance that is in the generic form and insert it at 3314 /// the provided insertion point. 3315 Operation *parseGenericOperation(Block *insertBlock, 3316 Block::iterator insertPt); 3317 3318 /// Parse an operation instance that is in the op-defined custom form. 3319 Operation *parseCustomOperation(); 3320 3321 //===--------------------------------------------------------------------===// 3322 // Region Parsing 3323 //===--------------------------------------------------------------------===// 3324 3325 /// Parse a region into 'region' with the provided entry block arguments. 3326 /// 'isIsolatedNameScope' indicates if the naming scope of this region is 3327 /// isolated from those above. 3328 ParseResult parseRegion(Region ®ion, 3329 ArrayRef<std::pair<SSAUseInfo, Type>> entryArguments, 3330 bool isIsolatedNameScope = false); 3331 3332 /// Parse a region body into 'region'. 3333 ParseResult parseRegionBody(Region ®ion); 3334 3335 //===--------------------------------------------------------------------===// 3336 // Block Parsing 3337 //===--------------------------------------------------------------------===// 3338 3339 /// Parse a new block into 'block'. 3340 ParseResult parseBlock(Block *&block); 3341 3342 /// Parse a list of operations into 'block'. 3343 ParseResult parseBlockBody(Block *block); 3344 3345 /// Parse a (possibly empty) list of block arguments. 3346 ParseResult parseOptionalBlockArgList(SmallVectorImpl<BlockArgument> &results, 3347 Block *owner); 3348 3349 /// Get the block with the specified name, creating it if it doesn't 3350 /// already exist. The location specified is the point of use, which allows 3351 /// us to diagnose references to blocks that are not defined precisely. 3352 Block *getBlockNamed(StringRef name, SMLoc loc); 3353 3354 /// Define the block with the specified name. Returns the Block* or nullptr in 3355 /// the case of redefinition. 3356 Block *defineBlockNamed(StringRef name, SMLoc loc, Block *existing); 3357 3358 private: 3359 /// Returns the info for a block at the current scope for the given name. 3360 std::pair<Block *, SMLoc> &getBlockInfoByName(StringRef name) { 3361 return blocksByName.back()[name]; 3362 } 3363 3364 /// Insert a new forward reference to the given block. 3365 void insertForwardRef(Block *block, SMLoc loc) { 3366 forwardRef.back().try_emplace(block, loc); 3367 } 3368 3369 /// Erase any forward reference to the given block. 3370 bool eraseForwardRef(Block *block) { return forwardRef.back().erase(block); } 3371 3372 /// Record that a definition was added at the current scope. 3373 void recordDefinition(StringRef def); 3374 3375 /// Get the value entry for the given SSA name. 3376 SmallVectorImpl<std::pair<Value, SMLoc>> &getSSAValueEntry(StringRef name); 3377 3378 /// Create a forward reference placeholder value with the given location and 3379 /// result type. 3380 Value createForwardRefPlaceholder(SMLoc loc, Type type); 3381 3382 /// Return true if this is a forward reference. 3383 bool isForwardRefPlaceholder(Value value) { 3384 return forwardRefPlaceholders.count(value); 3385 } 3386 3387 /// This struct represents an isolated SSA name scope. This scope may contain 3388 /// other nested non-isolated scopes. These scopes are used for operations 3389 /// that are known to be isolated to allow for reusing names within their 3390 /// regions, even if those names are used above. 3391 struct IsolatedSSANameScope { 3392 /// Record that a definition was added at the current scope. 3393 void recordDefinition(StringRef def) { 3394 definitionsPerScope.back().insert(def); 3395 } 3396 3397 /// Push a nested name scope. 3398 void pushSSANameScope() { definitionsPerScope.push_back({}); } 3399 3400 /// Pop a nested name scope. 3401 void popSSANameScope() { 3402 for (auto &def : definitionsPerScope.pop_back_val()) 3403 values.erase(def.getKey()); 3404 } 3405 3406 /// This keeps track of all of the SSA values we are tracking for each name 3407 /// scope, indexed by their name. This has one entry per result number. 3408 llvm::StringMap<SmallVector<std::pair<Value, SMLoc>, 1>> values; 3409 3410 /// This keeps track of all of the values defined by a specific name scope. 3411 SmallVector<llvm::StringSet<>, 2> definitionsPerScope; 3412 }; 3413 3414 /// A list of isolated name scopes. 3415 SmallVector<IsolatedSSANameScope, 2> isolatedNameScopes; 3416 3417 /// This keeps track of the block names as well as the location of the first 3418 /// reference for each nested name scope. This is used to diagnose invalid 3419 /// block references and memorize them. 3420 SmallVector<DenseMap<StringRef, std::pair<Block *, SMLoc>>, 2> blocksByName; 3421 SmallVector<DenseMap<Block *, SMLoc>, 2> forwardRef; 3422 3423 /// These are all of the placeholders we've made along with the location of 3424 /// their first reference, to allow checking for use of undefined values. 3425 DenseMap<Value, SMLoc> forwardRefPlaceholders; 3426 3427 /// The builder used when creating parsed operation instances. 3428 OpBuilder opBuilder; 3429 3430 /// The top level module operation. 3431 ModuleOp moduleOp; 3432 }; 3433 } // end anonymous namespace 3434 3435 OperationParser::~OperationParser() { 3436 for (auto &fwd : forwardRefPlaceholders) { 3437 // Drop all uses of undefined forward declared reference and destroy 3438 // defining operation. 3439 fwd.first.dropAllUses(); 3440 fwd.first.getDefiningOp()->destroy(); 3441 } 3442 } 3443 3444 /// After parsing is finished, this function must be called to see if there are 3445 /// any remaining issues. 3446 ParseResult OperationParser::finalize() { 3447 // Check for any forward references that are left. If we find any, error 3448 // out. 3449 if (!forwardRefPlaceholders.empty()) { 3450 SmallVector<std::pair<const char *, Value>, 4> errors; 3451 // Iteration over the map isn't deterministic, so sort by source location. 3452 for (auto entry : forwardRefPlaceholders) 3453 errors.push_back({entry.second.getPointer(), entry.first}); 3454 llvm::array_pod_sort(errors.begin(), errors.end()); 3455 3456 for (auto entry : errors) { 3457 auto loc = SMLoc::getFromPointer(entry.first); 3458 emitError(loc, "use of undeclared SSA value name"); 3459 } 3460 return failure(); 3461 } 3462 3463 return success(); 3464 } 3465 3466 //===----------------------------------------------------------------------===// 3467 // SSA Value Handling 3468 //===----------------------------------------------------------------------===// 3469 3470 void OperationParser::pushSSANameScope(bool isIsolated) { 3471 blocksByName.push_back(DenseMap<StringRef, std::pair<Block *, SMLoc>>()); 3472 forwardRef.push_back(DenseMap<Block *, SMLoc>()); 3473 3474 // Push back a new name definition scope. 3475 if (isIsolated) 3476 isolatedNameScopes.push_back({}); 3477 isolatedNameScopes.back().pushSSANameScope(); 3478 } 3479 3480 ParseResult OperationParser::popSSANameScope() { 3481 auto forwardRefInCurrentScope = forwardRef.pop_back_val(); 3482 3483 // Verify that all referenced blocks were defined. 3484 if (!forwardRefInCurrentScope.empty()) { 3485 SmallVector<std::pair<const char *, Block *>, 4> errors; 3486 // Iteration over the map isn't deterministic, so sort by source location. 3487 for (auto entry : forwardRefInCurrentScope) { 3488 errors.push_back({entry.second.getPointer(), entry.first}); 3489 // Add this block to the top-level region to allow for automatic cleanup. 3490 moduleOp.getOperation()->getRegion(0).push_back(entry.first); 3491 } 3492 llvm::array_pod_sort(errors.begin(), errors.end()); 3493 3494 for (auto entry : errors) { 3495 auto loc = SMLoc::getFromPointer(entry.first); 3496 emitError(loc, "reference to an undefined block"); 3497 } 3498 return failure(); 3499 } 3500 3501 // Pop the next nested namescope. If there is only one internal namescope, 3502 // just pop the isolated scope. 3503 auto ¤tNameScope = isolatedNameScopes.back(); 3504 if (currentNameScope.definitionsPerScope.size() == 1) 3505 isolatedNameScopes.pop_back(); 3506 else 3507 currentNameScope.popSSANameScope(); 3508 3509 blocksByName.pop_back(); 3510 return success(); 3511 } 3512 3513 /// Register a definition of a value with the symbol table. 3514 ParseResult OperationParser::addDefinition(SSAUseInfo useInfo, Value value) { 3515 auto &entries = getSSAValueEntry(useInfo.name); 3516 3517 // Make sure there is a slot for this value. 3518 if (entries.size() <= useInfo.number) 3519 entries.resize(useInfo.number + 1); 3520 3521 // If we already have an entry for this, check to see if it was a definition 3522 // or a forward reference. 3523 if (auto existing = entries[useInfo.number].first) { 3524 if (!isForwardRefPlaceholder(existing)) { 3525 return emitError(useInfo.loc) 3526 .append("redefinition of SSA value '", useInfo.name, "'") 3527 .attachNote(getEncodedSourceLocation(entries[useInfo.number].second)) 3528 .append("previously defined here"); 3529 } 3530 3531 // If it was a forward reference, update everything that used it to use 3532 // the actual definition instead, delete the forward ref, and remove it 3533 // from our set of forward references we track. 3534 existing.replaceAllUsesWith(value); 3535 existing.getDefiningOp()->destroy(); 3536 forwardRefPlaceholders.erase(existing); 3537 } 3538 3539 /// Record this definition for the current scope. 3540 entries[useInfo.number] = {value, useInfo.loc}; 3541 recordDefinition(useInfo.name); 3542 return success(); 3543 } 3544 3545 /// Parse a (possibly empty) list of SSA operands. 3546 /// 3547 /// ssa-use-list ::= ssa-use (`,` ssa-use)* 3548 /// ssa-use-list-opt ::= ssa-use-list? 3549 /// 3550 ParseResult 3551 OperationParser::parseOptionalSSAUseList(SmallVectorImpl<SSAUseInfo> &results) { 3552 if (getToken().isNot(Token::percent_identifier)) 3553 return success(); 3554 return parseCommaSeparatedList([&]() -> ParseResult { 3555 SSAUseInfo result; 3556 if (parseSSAUse(result)) 3557 return failure(); 3558 results.push_back(result); 3559 return success(); 3560 }); 3561 } 3562 3563 /// Parse a SSA operand for an operation. 3564 /// 3565 /// ssa-use ::= ssa-id 3566 /// 3567 ParseResult OperationParser::parseSSAUse(SSAUseInfo &result) { 3568 result.name = getTokenSpelling(); 3569 result.number = 0; 3570 result.loc = getToken().getLoc(); 3571 if (parseToken(Token::percent_identifier, "expected SSA operand")) 3572 return failure(); 3573 3574 // If we have an attribute ID, it is a result number. 3575 if (getToken().is(Token::hash_identifier)) { 3576 if (auto value = getToken().getHashIdentifierNumber()) 3577 result.number = value.getValue(); 3578 else 3579 return emitError("invalid SSA value result number"); 3580 consumeToken(Token::hash_identifier); 3581 } 3582 3583 return success(); 3584 } 3585 3586 /// Given an unbound reference to an SSA value and its type, return the value 3587 /// it specifies. This returns null on failure. 3588 Value OperationParser::resolveSSAUse(SSAUseInfo useInfo, Type type) { 3589 auto &entries = getSSAValueEntry(useInfo.name); 3590 3591 // If we have already seen a value of this name, return it. 3592 if (useInfo.number < entries.size() && entries[useInfo.number].first) { 3593 auto result = entries[useInfo.number].first; 3594 // Check that the type matches the other uses. 3595 if (result.getType() == type) 3596 return result; 3597 3598 emitError(useInfo.loc, "use of value '") 3599 .append(useInfo.name, 3600 "' expects different type than prior uses: ", type, " vs ", 3601 result.getType()) 3602 .attachNote(getEncodedSourceLocation(entries[useInfo.number].second)) 3603 .append("prior use here"); 3604 return nullptr; 3605 } 3606 3607 // Make sure we have enough slots for this. 3608 if (entries.size() <= useInfo.number) 3609 entries.resize(useInfo.number + 1); 3610 3611 // If the value has already been defined and this is an overly large result 3612 // number, diagnose that. 3613 if (entries[0].first && !isForwardRefPlaceholder(entries[0].first)) 3614 return (emitError(useInfo.loc, "reference to invalid result number"), 3615 nullptr); 3616 3617 // Otherwise, this is a forward reference. Create a placeholder and remember 3618 // that we did so. 3619 auto result = createForwardRefPlaceholder(useInfo.loc, type); 3620 entries[useInfo.number].first = result; 3621 entries[useInfo.number].second = useInfo.loc; 3622 return result; 3623 } 3624 3625 /// Parse an SSA use with an associated type. 3626 /// 3627 /// ssa-use-and-type ::= ssa-use `:` type 3628 ParseResult OperationParser::parseSSADefOrUseAndType( 3629 const std::function<ParseResult(SSAUseInfo, Type)> &action) { 3630 SSAUseInfo useInfo; 3631 if (parseSSAUse(useInfo) || 3632 parseToken(Token::colon, "expected ':' and type for SSA operand")) 3633 return failure(); 3634 3635 auto type = parseType(); 3636 if (!type) 3637 return failure(); 3638 3639 return action(useInfo, type); 3640 } 3641 3642 /// Parse a (possibly empty) list of SSA operands, followed by a colon, then 3643 /// followed by a type list. 3644 /// 3645 /// ssa-use-and-type-list 3646 /// ::= ssa-use-list ':' type-list-no-parens 3647 /// 3648 ParseResult OperationParser::parseOptionalSSAUseAndTypeList( 3649 SmallVectorImpl<Value> &results) { 3650 SmallVector<SSAUseInfo, 4> valueIDs; 3651 if (parseOptionalSSAUseList(valueIDs)) 3652 return failure(); 3653 3654 // If there were no operands, then there is no colon or type lists. 3655 if (valueIDs.empty()) 3656 return success(); 3657 3658 SmallVector<Type, 4> types; 3659 if (parseToken(Token::colon, "expected ':' in operand list") || 3660 parseTypeListNoParens(types)) 3661 return failure(); 3662 3663 if (valueIDs.size() != types.size()) 3664 return emitError("expected ") 3665 << valueIDs.size() << " types to match operand list"; 3666 3667 results.reserve(valueIDs.size()); 3668 for (unsigned i = 0, e = valueIDs.size(); i != e; ++i) { 3669 if (auto value = resolveSSAUse(valueIDs[i], types[i])) 3670 results.push_back(value); 3671 else 3672 return failure(); 3673 } 3674 3675 return success(); 3676 } 3677 3678 /// Record that a definition was added at the current scope. 3679 void OperationParser::recordDefinition(StringRef def) { 3680 isolatedNameScopes.back().recordDefinition(def); 3681 } 3682 3683 /// Get the value entry for the given SSA name. 3684 SmallVectorImpl<std::pair<Value, SMLoc>> & 3685 OperationParser::getSSAValueEntry(StringRef name) { 3686 return isolatedNameScopes.back().values[name]; 3687 } 3688 3689 /// Create and remember a new placeholder for a forward reference. 3690 Value OperationParser::createForwardRefPlaceholder(SMLoc loc, Type type) { 3691 // Forward references are always created as operations, because we just need 3692 // something with a def/use chain. 3693 // 3694 // We create these placeholders as having an empty name, which we know 3695 // cannot be created through normal user input, allowing us to distinguish 3696 // them. 3697 auto name = OperationName("placeholder", getContext()); 3698 auto *op = Operation::create( 3699 getEncodedSourceLocation(loc), name, type, /*operands=*/{}, 3700 /*attributes=*/llvm::None, /*successors=*/{}, /*numRegions=*/0, 3701 /*resizableOperandList=*/false); 3702 forwardRefPlaceholders[op->getResult(0)] = loc; 3703 return op->getResult(0); 3704 } 3705 3706 //===----------------------------------------------------------------------===// 3707 // Operation Parsing 3708 //===----------------------------------------------------------------------===// 3709 3710 /// Parse an operation. 3711 /// 3712 /// operation ::= op-result-list? 3713 /// (generic-operation | custom-operation) 3714 /// trailing-location? 3715 /// generic-operation ::= string-literal `(` ssa-use-list? `)` 3716 /// successor-list? (`(` region-list `)`)? 3717 /// attribute-dict? `:` function-type 3718 /// custom-operation ::= bare-id custom-operation-format 3719 /// op-result-list ::= op-result (`,` op-result)* `=` 3720 /// op-result ::= ssa-id (`:` integer-literal) 3721 /// 3722 ParseResult OperationParser::parseOperation() { 3723 auto loc = getToken().getLoc(); 3724 SmallVector<std::tuple<StringRef, unsigned, SMLoc>, 1> resultIDs; 3725 size_t numExpectedResults = 0; 3726 if (getToken().is(Token::percent_identifier)) { 3727 // Parse the group of result ids. 3728 auto parseNextResult = [&]() -> ParseResult { 3729 // Parse the next result id. 3730 if (!getToken().is(Token::percent_identifier)) 3731 return emitError("expected valid ssa identifier"); 3732 3733 Token nameTok = getToken(); 3734 consumeToken(Token::percent_identifier); 3735 3736 // If the next token is a ':', we parse the expected result count. 3737 size_t expectedSubResults = 1; 3738 if (consumeIf(Token::colon)) { 3739 // Check that the next token is an integer. 3740 if (!getToken().is(Token::integer)) 3741 return emitError("expected integer number of results"); 3742 3743 // Check that number of results is > 0. 3744 auto val = getToken().getUInt64IntegerValue(); 3745 if (!val.hasValue() || val.getValue() < 1) 3746 return emitError("expected named operation to have atleast 1 result"); 3747 consumeToken(Token::integer); 3748 expectedSubResults = *val; 3749 } 3750 3751 resultIDs.emplace_back(nameTok.getSpelling(), expectedSubResults, 3752 nameTok.getLoc()); 3753 numExpectedResults += expectedSubResults; 3754 return success(); 3755 }; 3756 if (parseCommaSeparatedList(parseNextResult)) 3757 return failure(); 3758 3759 if (parseToken(Token::equal, "expected '=' after SSA name")) 3760 return failure(); 3761 } 3762 3763 Operation *op; 3764 if (getToken().is(Token::bare_identifier) || getToken().isKeyword()) 3765 op = parseCustomOperation(); 3766 else if (getToken().is(Token::string)) 3767 op = parseGenericOperation(); 3768 else 3769 return emitError("expected operation name in quotes"); 3770 3771 // If parsing of the basic operation failed, then this whole thing fails. 3772 if (!op) 3773 return failure(); 3774 3775 // If the operation had a name, register it. 3776 if (!resultIDs.empty()) { 3777 if (op->getNumResults() == 0) 3778 return emitError(loc, "cannot name an operation with no results"); 3779 if (numExpectedResults != op->getNumResults()) 3780 return emitError(loc, "operation defines ") 3781 << op->getNumResults() << " results but was provided " 3782 << numExpectedResults << " to bind"; 3783 3784 // Add definitions for each of the result groups. 3785 unsigned opResI = 0; 3786 for (std::tuple<StringRef, unsigned, SMLoc> &resIt : resultIDs) { 3787 for (unsigned subRes : llvm::seq<unsigned>(0, std::get<1>(resIt))) { 3788 if (addDefinition({std::get<0>(resIt), subRes, std::get<2>(resIt)}, 3789 op->getResult(opResI++))) 3790 return failure(); 3791 } 3792 } 3793 } 3794 3795 return success(); 3796 } 3797 3798 /// Parse a single operation successor. 3799 /// 3800 /// successor ::= block-id 3801 /// 3802 ParseResult OperationParser::parseSuccessor(Block *&dest) { 3803 // Verify branch is identifier and get the matching block. 3804 if (!getToken().is(Token::caret_identifier)) 3805 return emitError("expected block name"); 3806 dest = getBlockNamed(getTokenSpelling(), getToken().getLoc()); 3807 consumeToken(); 3808 return success(); 3809 } 3810 3811 /// Parse a comma-separated list of operation successors in brackets. 3812 /// 3813 /// successor-list ::= `[` successor (`,` successor )* `]` 3814 /// 3815 ParseResult 3816 OperationParser::parseSuccessors(SmallVectorImpl<Block *> &destinations) { 3817 if (parseToken(Token::l_square, "expected '['")) 3818 return failure(); 3819 3820 auto parseElt = [this, &destinations] { 3821 Block *dest; 3822 ParseResult res = parseSuccessor(dest); 3823 destinations.push_back(dest); 3824 return res; 3825 }; 3826 return parseCommaSeparatedListUntil(Token::r_square, parseElt, 3827 /*allowEmptyList=*/false); 3828 } 3829 3830 namespace { 3831 // RAII-style guard for cleaning up the regions in the operation state before 3832 // deleting them. Within the parser, regions may get deleted if parsing failed, 3833 // and other errors may be present, in particular undominated uses. This makes 3834 // sure such uses are deleted. 3835 struct CleanupOpStateRegions { 3836 ~CleanupOpStateRegions() { 3837 SmallVector<Region *, 4> regionsToClean; 3838 regionsToClean.reserve(state.regions.size()); 3839 for (auto ®ion : state.regions) 3840 if (region) 3841 for (auto &block : *region) 3842 block.dropAllDefinedValueUses(); 3843 } 3844 OperationState &state; 3845 }; 3846 } // namespace 3847 3848 Operation *OperationParser::parseGenericOperation() { 3849 // Get location information for the operation. 3850 auto srcLocation = getEncodedSourceLocation(getToken().getLoc()); 3851 3852 auto name = getToken().getStringValue(); 3853 if (name.empty()) 3854 return (emitError("empty operation name is invalid"), nullptr); 3855 if (name.find('\0') != StringRef::npos) 3856 return (emitError("null character not allowed in operation name"), nullptr); 3857 3858 consumeToken(Token::string); 3859 3860 OperationState result(srcLocation, name); 3861 3862 // Generic operations have a resizable operation list. 3863 result.setOperandListToResizable(); 3864 3865 // Parse the operand list. 3866 SmallVector<SSAUseInfo, 8> operandInfos; 3867 if (parseToken(Token::l_paren, "expected '(' to start operand list") || 3868 parseOptionalSSAUseList(operandInfos) || 3869 parseToken(Token::r_paren, "expected ')' to end operand list")) { 3870 return nullptr; 3871 } 3872 3873 // Parse the successor list. 3874 if (getToken().is(Token::l_square)) { 3875 // Check if the operation is a known terminator. 3876 const AbstractOperation *abstractOp = result.name.getAbstractOperation(); 3877 if (abstractOp && !abstractOp->hasProperty(OperationProperty::Terminator)) 3878 return emitError("successors in non-terminator"), nullptr; 3879 3880 SmallVector<Block *, 2> successors; 3881 if (parseSuccessors(successors)) 3882 return nullptr; 3883 result.addSuccessors(successors); 3884 } 3885 3886 // Parse the region list. 3887 CleanupOpStateRegions guard{result}; 3888 if (consumeIf(Token::l_paren)) { 3889 do { 3890 // Create temporary regions with the top level region as parent. 3891 result.regions.emplace_back(new Region(moduleOp)); 3892 if (parseRegion(*result.regions.back(), /*entryArguments=*/{})) 3893 return nullptr; 3894 } while (consumeIf(Token::comma)); 3895 if (parseToken(Token::r_paren, "expected ')' to end region list")) 3896 return nullptr; 3897 } 3898 3899 if (getToken().is(Token::l_brace)) { 3900 if (parseAttributeDict(result.attributes)) 3901 return nullptr; 3902 } 3903 3904 if (parseToken(Token::colon, "expected ':' followed by operation type")) 3905 return nullptr; 3906 3907 auto typeLoc = getToken().getLoc(); 3908 auto type = parseType(); 3909 if (!type) 3910 return nullptr; 3911 auto fnType = type.dyn_cast<FunctionType>(); 3912 if (!fnType) 3913 return (emitError(typeLoc, "expected function type"), nullptr); 3914 3915 result.addTypes(fnType.getResults()); 3916 3917 // Check that we have the right number of types for the operands. 3918 auto operandTypes = fnType.getInputs(); 3919 if (operandTypes.size() != operandInfos.size()) { 3920 auto plural = "s"[operandInfos.size() == 1]; 3921 return (emitError(typeLoc, "expected ") 3922 << operandInfos.size() << " operand type" << plural 3923 << " but had " << operandTypes.size(), 3924 nullptr); 3925 } 3926 3927 // Resolve all of the operands. 3928 for (unsigned i = 0, e = operandInfos.size(); i != e; ++i) { 3929 result.operands.push_back(resolveSSAUse(operandInfos[i], operandTypes[i])); 3930 if (!result.operands.back()) 3931 return nullptr; 3932 } 3933 3934 // Parse a location if one is present. 3935 if (parseOptionalTrailingLocation(result.location)) 3936 return nullptr; 3937 3938 return opBuilder.createOperation(result); 3939 } 3940 3941 Operation *OperationParser::parseGenericOperation(Block *insertBlock, 3942 Block::iterator insertPt) { 3943 OpBuilder::InsertionGuard restoreInsertionPoint(opBuilder); 3944 opBuilder.setInsertionPoint(insertBlock, insertPt); 3945 return parseGenericOperation(); 3946 } 3947 3948 namespace { 3949 class CustomOpAsmParser : public OpAsmParser { 3950 public: 3951 CustomOpAsmParser(SMLoc nameLoc, const AbstractOperation *opDefinition, 3952 OperationParser &parser) 3953 : nameLoc(nameLoc), opDefinition(opDefinition), parser(parser) {} 3954 3955 /// Parse an instance of the operation described by 'opDefinition' into the 3956 /// provided operation state. 3957 ParseResult parseOperation(OperationState &opState) { 3958 if (opDefinition->parseAssembly(*this, opState)) 3959 return failure(); 3960 return success(); 3961 } 3962 3963 Operation *parseGenericOperation(Block *insertBlock, 3964 Block::iterator insertPt) final { 3965 return parser.parseGenericOperation(insertBlock, insertPt); 3966 } 3967 3968 //===--------------------------------------------------------------------===// 3969 // Utilities 3970 //===--------------------------------------------------------------------===// 3971 3972 /// Return if any errors were emitted during parsing. 3973 bool didEmitError() const { return emittedError; } 3974 3975 /// Emit a diagnostic at the specified location and return failure. 3976 InFlightDiagnostic emitError(llvm::SMLoc loc, const Twine &message) override { 3977 emittedError = true; 3978 return parser.emitError(loc, "custom op '" + opDefinition->name + "' " + 3979 message); 3980 } 3981 3982 llvm::SMLoc getCurrentLocation() override { 3983 return parser.getToken().getLoc(); 3984 } 3985 3986 Builder &getBuilder() const override { return parser.builder; } 3987 3988 llvm::SMLoc getNameLoc() const override { return nameLoc; } 3989 3990 //===--------------------------------------------------------------------===// 3991 // Token Parsing 3992 //===--------------------------------------------------------------------===// 3993 3994 /// Parse a `->` token. 3995 ParseResult parseArrow() override { 3996 return parser.parseToken(Token::arrow, "expected '->'"); 3997 } 3998 3999 /// Parses a `->` if present. 4000 ParseResult parseOptionalArrow() override { 4001 return success(parser.consumeIf(Token::arrow)); 4002 } 4003 4004 /// Parse a `:` token. 4005 ParseResult parseColon() override { 4006 return parser.parseToken(Token::colon, "expected ':'"); 4007 } 4008 4009 /// Parse a `:` token if present. 4010 ParseResult parseOptionalColon() override { 4011 return success(parser.consumeIf(Token::colon)); 4012 } 4013 4014 /// Parse a `,` token. 4015 ParseResult parseComma() override { 4016 return parser.parseToken(Token::comma, "expected ','"); 4017 } 4018 4019 /// Parse a `,` token if present. 4020 ParseResult parseOptionalComma() override { 4021 return success(parser.consumeIf(Token::comma)); 4022 } 4023 4024 /// Parses a `...` if present. 4025 ParseResult parseOptionalEllipsis() override { 4026 return success(parser.consumeIf(Token::ellipsis)); 4027 } 4028 4029 /// Parse a `=` token. 4030 ParseResult parseEqual() override { 4031 return parser.parseToken(Token::equal, "expected '='"); 4032 } 4033 4034 /// Parse a '<' token. 4035 ParseResult parseLess() override { 4036 return parser.parseToken(Token::less, "expected '<'"); 4037 } 4038 4039 /// Parse a '>' token. 4040 ParseResult parseGreater() override { 4041 return parser.parseToken(Token::greater, "expected '>'"); 4042 } 4043 4044 /// Parse a `(` token. 4045 ParseResult parseLParen() override { 4046 return parser.parseToken(Token::l_paren, "expected '('"); 4047 } 4048 4049 /// Parses a '(' if present. 4050 ParseResult parseOptionalLParen() override { 4051 return success(parser.consumeIf(Token::l_paren)); 4052 } 4053 4054 /// Parse a `)` token. 4055 ParseResult parseRParen() override { 4056 return parser.parseToken(Token::r_paren, "expected ')'"); 4057 } 4058 4059 /// Parses a ')' if present. 4060 ParseResult parseOptionalRParen() override { 4061 return success(parser.consumeIf(Token::r_paren)); 4062 } 4063 4064 /// Parse a `[` token. 4065 ParseResult parseLSquare() override { 4066 return parser.parseToken(Token::l_square, "expected '['"); 4067 } 4068 4069 /// Parses a '[' if present. 4070 ParseResult parseOptionalLSquare() override { 4071 return success(parser.consumeIf(Token::l_square)); 4072 } 4073 4074 /// Parse a `]` token. 4075 ParseResult parseRSquare() override { 4076 return parser.parseToken(Token::r_square, "expected ']'"); 4077 } 4078 4079 /// Parses a ']' if present. 4080 ParseResult parseOptionalRSquare() override { 4081 return success(parser.consumeIf(Token::r_square)); 4082 } 4083 4084 //===--------------------------------------------------------------------===// 4085 // Attribute Parsing 4086 //===--------------------------------------------------------------------===// 4087 4088 /// Parse an arbitrary attribute of a given type and return it in result. This 4089 /// also adds the attribute to the specified attribute list with the specified 4090 /// name. 4091 ParseResult parseAttribute(Attribute &result, Type type, StringRef attrName, 4092 SmallVectorImpl<NamedAttribute> &attrs) override { 4093 result = parser.parseAttribute(type); 4094 if (!result) 4095 return failure(); 4096 4097 attrs.push_back(parser.builder.getNamedAttr(attrName, result)); 4098 return success(); 4099 } 4100 4101 /// Parse a named dictionary into 'result' if it is present. 4102 ParseResult 4103 parseOptionalAttrDict(SmallVectorImpl<NamedAttribute> &result) override { 4104 if (parser.getToken().isNot(Token::l_brace)) 4105 return success(); 4106 return parser.parseAttributeDict(result); 4107 } 4108 4109 /// Parse a named dictionary into 'result' if the `attributes` keyword is 4110 /// present. 4111 ParseResult parseOptionalAttrDictWithKeyword( 4112 SmallVectorImpl<NamedAttribute> &result) override { 4113 if (failed(parseOptionalKeyword("attributes"))) 4114 return success(); 4115 return parser.parseAttributeDict(result); 4116 } 4117 4118 /// Parse an affine map instance into 'map'. 4119 ParseResult parseAffineMap(AffineMap &map) override { 4120 return parser.parseAffineMapReference(map); 4121 } 4122 4123 /// Parse an integer set instance into 'set'. 4124 ParseResult printIntegerSet(IntegerSet &set) override { 4125 return parser.parseIntegerSetReference(set); 4126 } 4127 4128 //===--------------------------------------------------------------------===// 4129 // Identifier Parsing 4130 //===--------------------------------------------------------------------===// 4131 4132 /// Returns if the current token corresponds to a keyword. 4133 bool isCurrentTokenAKeyword() const { 4134 return parser.getToken().is(Token::bare_identifier) || 4135 parser.getToken().isKeyword(); 4136 } 4137 4138 /// Parse the given keyword if present. 4139 ParseResult parseOptionalKeyword(StringRef keyword) override { 4140 // Check that the current token has the same spelling. 4141 if (!isCurrentTokenAKeyword() || parser.getTokenSpelling() != keyword) 4142 return failure(); 4143 parser.consumeToken(); 4144 return success(); 4145 } 4146 4147 /// Parse a keyword, if present, into 'keyword'. 4148 ParseResult parseOptionalKeyword(StringRef *keyword) override { 4149 // Check that the current token is a keyword. 4150 if (!isCurrentTokenAKeyword()) 4151 return failure(); 4152 4153 *keyword = parser.getTokenSpelling(); 4154 parser.consumeToken(); 4155 return success(); 4156 } 4157 4158 /// Parse an optional @-identifier and store it (without the '@' symbol) in a 4159 /// string attribute named 'attrName'. 4160 ParseResult 4161 parseOptionalSymbolName(StringAttr &result, StringRef attrName, 4162 SmallVectorImpl<NamedAttribute> &attrs) override { 4163 Token atToken = parser.getToken(); 4164 if (atToken.isNot(Token::at_identifier)) 4165 return failure(); 4166 4167 result = getBuilder().getStringAttr(extractSymbolReference(atToken)); 4168 attrs.push_back(getBuilder().getNamedAttr(attrName, result)); 4169 parser.consumeToken(); 4170 return success(); 4171 } 4172 4173 //===--------------------------------------------------------------------===// 4174 // Operand Parsing 4175 //===--------------------------------------------------------------------===// 4176 4177 /// Parse a single operand. 4178 ParseResult parseOperand(OperandType &result) override { 4179 OperationParser::SSAUseInfo useInfo; 4180 if (parser.parseSSAUse(useInfo)) 4181 return failure(); 4182 4183 result = {useInfo.loc, useInfo.name, useInfo.number}; 4184 return success(); 4185 } 4186 4187 /// Parse zero or more SSA comma-separated operand references with a specified 4188 /// surrounding delimiter, and an optional required operand count. 4189 ParseResult parseOperandList(SmallVectorImpl<OperandType> &result, 4190 int requiredOperandCount = -1, 4191 Delimiter delimiter = Delimiter::None) override { 4192 return parseOperandOrRegionArgList(result, /*isOperandList=*/true, 4193 requiredOperandCount, delimiter); 4194 } 4195 4196 /// Parse zero or more SSA comma-separated operand or region arguments with 4197 /// optional surrounding delimiter and required operand count. 4198 ParseResult 4199 parseOperandOrRegionArgList(SmallVectorImpl<OperandType> &result, 4200 bool isOperandList, int requiredOperandCount = -1, 4201 Delimiter delimiter = Delimiter::None) { 4202 auto startLoc = parser.getToken().getLoc(); 4203 4204 // Handle delimiters. 4205 switch (delimiter) { 4206 case Delimiter::None: 4207 // Don't check for the absence of a delimiter if the number of operands 4208 // is unknown (and hence the operand list could be empty). 4209 if (requiredOperandCount == -1) 4210 break; 4211 // Token already matches an identifier and so can't be a delimiter. 4212 if (parser.getToken().is(Token::percent_identifier)) 4213 break; 4214 // Test against known delimiters. 4215 if (parser.getToken().is(Token::l_paren) || 4216 parser.getToken().is(Token::l_square)) 4217 return emitError(startLoc, "unexpected delimiter"); 4218 return emitError(startLoc, "invalid operand"); 4219 case Delimiter::OptionalParen: 4220 if (parser.getToken().isNot(Token::l_paren)) 4221 return success(); 4222 LLVM_FALLTHROUGH; 4223 case Delimiter::Paren: 4224 if (parser.parseToken(Token::l_paren, "expected '(' in operand list")) 4225 return failure(); 4226 break; 4227 case Delimiter::OptionalSquare: 4228 if (parser.getToken().isNot(Token::l_square)) 4229 return success(); 4230 LLVM_FALLTHROUGH; 4231 case Delimiter::Square: 4232 if (parser.parseToken(Token::l_square, "expected '[' in operand list")) 4233 return failure(); 4234 break; 4235 } 4236 4237 // Check for zero operands. 4238 if (parser.getToken().is(Token::percent_identifier)) { 4239 do { 4240 OperandType operandOrArg; 4241 if (isOperandList ? parseOperand(operandOrArg) 4242 : parseRegionArgument(operandOrArg)) 4243 return failure(); 4244 result.push_back(operandOrArg); 4245 } while (parser.consumeIf(Token::comma)); 4246 } 4247 4248 // Handle delimiters. If we reach here, the optional delimiters were 4249 // present, so we need to parse their closing one. 4250 switch (delimiter) { 4251 case Delimiter::None: 4252 break; 4253 case Delimiter::OptionalParen: 4254 case Delimiter::Paren: 4255 if (parser.parseToken(Token::r_paren, "expected ')' in operand list")) 4256 return failure(); 4257 break; 4258 case Delimiter::OptionalSquare: 4259 case Delimiter::Square: 4260 if (parser.parseToken(Token::r_square, "expected ']' in operand list")) 4261 return failure(); 4262 break; 4263 } 4264 4265 if (requiredOperandCount != -1 && 4266 result.size() != static_cast<size_t>(requiredOperandCount)) 4267 return emitError(startLoc, "expected ") 4268 << requiredOperandCount << " operands"; 4269 return success(); 4270 } 4271 4272 /// Parse zero or more trailing SSA comma-separated trailing operand 4273 /// references with a specified surrounding delimiter, and an optional 4274 /// required operand count. A leading comma is expected before the operands. 4275 ParseResult parseTrailingOperandList(SmallVectorImpl<OperandType> &result, 4276 int requiredOperandCount, 4277 Delimiter delimiter) override { 4278 if (parser.getToken().is(Token::comma)) { 4279 parseComma(); 4280 return parseOperandList(result, requiredOperandCount, delimiter); 4281 } 4282 if (requiredOperandCount != -1) 4283 return emitError(parser.getToken().getLoc(), "expected ") 4284 << requiredOperandCount << " operands"; 4285 return success(); 4286 } 4287 4288 /// Resolve an operand to an SSA value, emitting an error on failure. 4289 ParseResult resolveOperand(const OperandType &operand, Type type, 4290 SmallVectorImpl<Value> &result) override { 4291 OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number, 4292 operand.location}; 4293 if (auto value = parser.resolveSSAUse(operandInfo, type)) { 4294 result.push_back(value); 4295 return success(); 4296 } 4297 return failure(); 4298 } 4299 4300 /// Parse an AffineMap of SSA ids. 4301 ParseResult parseAffineMapOfSSAIds(SmallVectorImpl<OperandType> &operands, 4302 Attribute &mapAttr, StringRef attrName, 4303 SmallVectorImpl<NamedAttribute> &attrs, 4304 Delimiter delimiter) override { 4305 SmallVector<OperandType, 2> dimOperands; 4306 SmallVector<OperandType, 1> symOperands; 4307 4308 auto parseElement = [&](bool isSymbol) -> ParseResult { 4309 OperandType operand; 4310 if (parseOperand(operand)) 4311 return failure(); 4312 if (isSymbol) 4313 symOperands.push_back(operand); 4314 else 4315 dimOperands.push_back(operand); 4316 return success(); 4317 }; 4318 4319 AffineMap map; 4320 if (parser.parseAffineMapOfSSAIds(map, parseElement, delimiter)) 4321 return failure(); 4322 // Add AffineMap attribute. 4323 if (map) { 4324 mapAttr = AffineMapAttr::get(map); 4325 attrs.push_back(parser.builder.getNamedAttr(attrName, mapAttr)); 4326 } 4327 4328 // Add dim operands before symbol operands in 'operands'. 4329 operands.assign(dimOperands.begin(), dimOperands.end()); 4330 operands.append(symOperands.begin(), symOperands.end()); 4331 return success(); 4332 } 4333 4334 //===--------------------------------------------------------------------===// 4335 // Region Parsing 4336 //===--------------------------------------------------------------------===// 4337 4338 /// Parse a region that takes `arguments` of `argTypes` types. This 4339 /// effectively defines the SSA values of `arguments` and assigns their type. 4340 ParseResult parseRegion(Region ®ion, ArrayRef<OperandType> arguments, 4341 ArrayRef<Type> argTypes, 4342 bool enableNameShadowing) override { 4343 assert(arguments.size() == argTypes.size() && 4344 "mismatching number of arguments and types"); 4345 4346 SmallVector<std::pair<OperationParser::SSAUseInfo, Type>, 2> 4347 regionArguments; 4348 for (auto pair : llvm::zip(arguments, argTypes)) { 4349 const OperandType &operand = std::get<0>(pair); 4350 Type type = std::get<1>(pair); 4351 OperationParser::SSAUseInfo operandInfo = {operand.name, operand.number, 4352 operand.location}; 4353 regionArguments.emplace_back(operandInfo, type); 4354 } 4355 4356 // Try to parse the region. 4357 assert((!enableNameShadowing || 4358 opDefinition->hasProperty(OperationProperty::IsolatedFromAbove)) && 4359 "name shadowing is only allowed on isolated regions"); 4360 if (parser.parseRegion(region, regionArguments, enableNameShadowing)) 4361 return failure(); 4362 return success(); 4363 } 4364 4365 /// Parses a region if present. 4366 ParseResult parseOptionalRegion(Region ®ion, 4367 ArrayRef<OperandType> arguments, 4368 ArrayRef<Type> argTypes, 4369 bool enableNameShadowing) override { 4370 if (parser.getToken().isNot(Token::l_brace)) 4371 return success(); 4372 return parseRegion(region, arguments, argTypes, enableNameShadowing); 4373 } 4374 4375 /// Parse a region argument. The type of the argument will be resolved later 4376 /// by a call to `parseRegion`. 4377 ParseResult parseRegionArgument(OperandType &argument) override { 4378 return parseOperand(argument); 4379 } 4380 4381 /// Parse a region argument if present. 4382 ParseResult parseOptionalRegionArgument(OperandType &argument) override { 4383 if (parser.getToken().isNot(Token::percent_identifier)) 4384 return success(); 4385 return parseRegionArgument(argument); 4386 } 4387 4388 ParseResult 4389 parseRegionArgumentList(SmallVectorImpl<OperandType> &result, 4390 int requiredOperandCount = -1, 4391 Delimiter delimiter = Delimiter::None) override { 4392 return parseOperandOrRegionArgList(result, /*isOperandList=*/false, 4393 requiredOperandCount, delimiter); 4394 } 4395 4396 //===--------------------------------------------------------------------===// 4397 // Successor Parsing 4398 //===--------------------------------------------------------------------===// 4399 4400 /// Parse a single operation successor. 4401 ParseResult parseSuccessor(Block *&dest) override { 4402 return parser.parseSuccessor(dest); 4403 } 4404 4405 /// Parse an optional operation successor and its operand list. 4406 OptionalParseResult parseOptionalSuccessor(Block *&dest) override { 4407 if (parser.getToken().isNot(Token::caret_identifier)) 4408 return llvm::None; 4409 return parseSuccessor(dest); 4410 } 4411 4412 /// Parse a single operation successor and its operand list. 4413 ParseResult 4414 parseSuccessorAndUseList(Block *&dest, 4415 SmallVectorImpl<Value> &operands) override { 4416 if (parseSuccessor(dest)) 4417 return failure(); 4418 4419 // Handle optional arguments. 4420 if (succeeded(parseOptionalLParen()) && 4421 (parser.parseOptionalSSAUseAndTypeList(operands) || parseRParen())) { 4422 return failure(); 4423 } 4424 return success(); 4425 } 4426 4427 //===--------------------------------------------------------------------===// 4428 // Type Parsing 4429 //===--------------------------------------------------------------------===// 4430 4431 /// Parse a type. 4432 ParseResult parseType(Type &result) override { 4433 return failure(!(result = parser.parseType())); 4434 } 4435 4436 /// Parse an arrow followed by a type list. 4437 ParseResult parseArrowTypeList(SmallVectorImpl<Type> &result) override { 4438 if (parseArrow() || parser.parseFunctionResultTypes(result)) 4439 return failure(); 4440 return success(); 4441 } 4442 4443 /// Parse an optional arrow followed by a type list. 4444 ParseResult 4445 parseOptionalArrowTypeList(SmallVectorImpl<Type> &result) override { 4446 if (!parser.consumeIf(Token::arrow)) 4447 return success(); 4448 return parser.parseFunctionResultTypes(result); 4449 } 4450 4451 /// Parse a colon followed by a type. 4452 ParseResult parseColonType(Type &result) override { 4453 return failure(parser.parseToken(Token::colon, "expected ':'") || 4454 !(result = parser.parseType())); 4455 } 4456 4457 /// Parse a colon followed by a type list, which must have at least one type. 4458 ParseResult parseColonTypeList(SmallVectorImpl<Type> &result) override { 4459 if (parser.parseToken(Token::colon, "expected ':'")) 4460 return failure(); 4461 return parser.parseTypeListNoParens(result); 4462 } 4463 4464 /// Parse an optional colon followed by a type list, which if present must 4465 /// have at least one type. 4466 ParseResult 4467 parseOptionalColonTypeList(SmallVectorImpl<Type> &result) override { 4468 if (!parser.consumeIf(Token::colon)) 4469 return success(); 4470 return parser.parseTypeListNoParens(result); 4471 } 4472 4473 /// Parse a list of assignments of the form 4474 /// (%x1 = %y1 : type1, %x2 = %y2 : type2, ...). 4475 /// The list must contain at least one entry 4476 ParseResult parseAssignmentList(SmallVectorImpl<OperandType> &lhs, 4477 SmallVectorImpl<OperandType> &rhs) override { 4478 auto parseElt = [&]() -> ParseResult { 4479 OperandType regionArg, operand; 4480 if (parseRegionArgument(regionArg) || parseEqual() || 4481 parseOperand(operand)) 4482 return failure(); 4483 lhs.push_back(regionArg); 4484 rhs.push_back(operand); 4485 return success(); 4486 }; 4487 if (parseLParen()) 4488 return failure(); 4489 return parser.parseCommaSeparatedListUntil(Token::r_paren, parseElt); 4490 } 4491 4492 private: 4493 /// The source location of the operation name. 4494 SMLoc nameLoc; 4495 4496 /// The abstract information of the operation. 4497 const AbstractOperation *opDefinition; 4498 4499 /// The main operation parser. 4500 OperationParser &parser; 4501 4502 /// A flag that indicates if any errors were emitted during parsing. 4503 bool emittedError = false; 4504 }; 4505 } // end anonymous namespace. 4506 4507 Operation *OperationParser::parseCustomOperation() { 4508 auto opLoc = getToken().getLoc(); 4509 auto opName = getTokenSpelling(); 4510 4511 auto *opDefinition = AbstractOperation::lookup(opName, getContext()); 4512 if (!opDefinition && !opName.contains('.')) { 4513 // If the operation name has no namespace prefix we treat it as a standard 4514 // operation and prefix it with "std". 4515 // TODO: Would it be better to just build a mapping of the registered 4516 // operations in the standard dialect? 4517 opDefinition = 4518 AbstractOperation::lookup(Twine("std." + opName).str(), getContext()); 4519 } 4520 4521 if (!opDefinition) { 4522 emitError(opLoc) << "custom op '" << opName << "' is unknown"; 4523 return nullptr; 4524 } 4525 4526 consumeToken(); 4527 4528 // If the custom op parser crashes, produce some indication to help 4529 // debugging. 4530 std::string opNameStr = opName.str(); 4531 llvm::PrettyStackTraceFormat fmt("MLIR Parser: custom op parser '%s'", 4532 opNameStr.c_str()); 4533 4534 // Get location information for the operation. 4535 auto srcLocation = getEncodedSourceLocation(opLoc); 4536 4537 // Have the op implementation take a crack and parsing this. 4538 OperationState opState(srcLocation, opDefinition->name); 4539 CleanupOpStateRegions guard{opState}; 4540 CustomOpAsmParser opAsmParser(opLoc, opDefinition, *this); 4541 if (opAsmParser.parseOperation(opState)) 4542 return nullptr; 4543 4544 // If it emitted an error, we failed. 4545 if (opAsmParser.didEmitError()) 4546 return nullptr; 4547 4548 // Parse a location if one is present. 4549 if (parseOptionalTrailingLocation(opState.location)) 4550 return nullptr; 4551 4552 // Otherwise, we succeeded. Use the state it parsed as our op information. 4553 return opBuilder.createOperation(opState); 4554 } 4555 4556 //===----------------------------------------------------------------------===// 4557 // Region Parsing 4558 //===----------------------------------------------------------------------===// 4559 4560 /// Region. 4561 /// 4562 /// region ::= '{' region-body 4563 /// 4564 ParseResult OperationParser::parseRegion( 4565 Region ®ion, 4566 ArrayRef<std::pair<OperationParser::SSAUseInfo, Type>> entryArguments, 4567 bool isIsolatedNameScope) { 4568 // Parse the '{'. 4569 if (parseToken(Token::l_brace, "expected '{' to begin a region")) 4570 return failure(); 4571 4572 // Check for an empty region. 4573 if (entryArguments.empty() && consumeIf(Token::r_brace)) 4574 return success(); 4575 auto currentPt = opBuilder.saveInsertionPoint(); 4576 4577 // Push a new named value scope. 4578 pushSSANameScope(isIsolatedNameScope); 4579 4580 // Parse the first block directly to allow for it to be unnamed. 4581 Block *block = new Block(); 4582 4583 // Add arguments to the entry block. 4584 if (!entryArguments.empty()) { 4585 for (auto &placeholderArgPair : entryArguments) { 4586 auto &argInfo = placeholderArgPair.first; 4587 // Ensure that the argument was not already defined. 4588 if (auto defLoc = getReferenceLoc(argInfo.name, argInfo.number)) { 4589 return emitError(argInfo.loc, "region entry argument '" + argInfo.name + 4590 "' is already in use") 4591 .attachNote(getEncodedSourceLocation(*defLoc)) 4592 << "previously referenced here"; 4593 } 4594 if (addDefinition(placeholderArgPair.first, 4595 block->addArgument(placeholderArgPair.second))) { 4596 delete block; 4597 return failure(); 4598 } 4599 } 4600 4601 // If we had named arguments, then don't allow a block name. 4602 if (getToken().is(Token::caret_identifier)) 4603 return emitError("invalid block name in region with named arguments"); 4604 } 4605 4606 if (parseBlock(block)) { 4607 delete block; 4608 return failure(); 4609 } 4610 4611 // Verify that no other arguments were parsed. 4612 if (!entryArguments.empty() && 4613 block->getNumArguments() > entryArguments.size()) { 4614 delete block; 4615 return emitError("entry block arguments were already defined"); 4616 } 4617 4618 // Parse the rest of the region. 4619 region.push_back(block); 4620 if (parseRegionBody(region)) 4621 return failure(); 4622 4623 // Pop the SSA value scope for this region. 4624 if (popSSANameScope()) 4625 return failure(); 4626 4627 // Reset the original insertion point. 4628 opBuilder.restoreInsertionPoint(currentPt); 4629 return success(); 4630 } 4631 4632 /// Region. 4633 /// 4634 /// region-body ::= block* '}' 4635 /// 4636 ParseResult OperationParser::parseRegionBody(Region ®ion) { 4637 // Parse the list of blocks. 4638 while (!consumeIf(Token::r_brace)) { 4639 Block *newBlock = nullptr; 4640 if (parseBlock(newBlock)) 4641 return failure(); 4642 region.push_back(newBlock); 4643 } 4644 return success(); 4645 } 4646 4647 //===----------------------------------------------------------------------===// 4648 // Block Parsing 4649 //===----------------------------------------------------------------------===// 4650 4651 /// Block declaration. 4652 /// 4653 /// block ::= block-label? operation* 4654 /// block-label ::= block-id block-arg-list? `:` 4655 /// block-id ::= caret-id 4656 /// block-arg-list ::= `(` ssa-id-and-type-list? `)` 4657 /// 4658 ParseResult OperationParser::parseBlock(Block *&block) { 4659 // The first block of a region may already exist, if it does the caret 4660 // identifier is optional. 4661 if (block && getToken().isNot(Token::caret_identifier)) 4662 return parseBlockBody(block); 4663 4664 SMLoc nameLoc = getToken().getLoc(); 4665 auto name = getTokenSpelling(); 4666 if (parseToken(Token::caret_identifier, "expected block name")) 4667 return failure(); 4668 4669 block = defineBlockNamed(name, nameLoc, block); 4670 4671 // Fail if the block was already defined. 4672 if (!block) 4673 return emitError(nameLoc, "redefinition of block '") << name << "'"; 4674 4675 // If an argument list is present, parse it. 4676 if (consumeIf(Token::l_paren)) { 4677 SmallVector<BlockArgument, 8> bbArgs; 4678 if (parseOptionalBlockArgList(bbArgs, block) || 4679 parseToken(Token::r_paren, "expected ')' to end argument list")) 4680 return failure(); 4681 } 4682 4683 if (parseToken(Token::colon, "expected ':' after block name")) 4684 return failure(); 4685 4686 return parseBlockBody(block); 4687 } 4688 4689 ParseResult OperationParser::parseBlockBody(Block *block) { 4690 // Set the insertion point to the end of the block to parse. 4691 opBuilder.setInsertionPointToEnd(block); 4692 4693 // Parse the list of operations that make up the body of the block. 4694 while (getToken().isNot(Token::caret_identifier, Token::r_brace)) 4695 if (parseOperation()) 4696 return failure(); 4697 4698 return success(); 4699 } 4700 4701 /// Get the block with the specified name, creating it if it doesn't already 4702 /// exist. The location specified is the point of use, which allows 4703 /// us to diagnose references to blocks that are not defined precisely. 4704 Block *OperationParser::getBlockNamed(StringRef name, SMLoc loc) { 4705 auto &blockAndLoc = getBlockInfoByName(name); 4706 if (!blockAndLoc.first) { 4707 blockAndLoc = {new Block(), loc}; 4708 insertForwardRef(blockAndLoc.first, loc); 4709 } 4710 4711 return blockAndLoc.first; 4712 } 4713 4714 /// Define the block with the specified name. Returns the Block* or nullptr in 4715 /// the case of redefinition. 4716 Block *OperationParser::defineBlockNamed(StringRef name, SMLoc loc, 4717 Block *existing) { 4718 auto &blockAndLoc = getBlockInfoByName(name); 4719 if (!blockAndLoc.first) { 4720 // If the caller provided a block, use it. Otherwise create a new one. 4721 if (!existing) 4722 existing = new Block(); 4723 blockAndLoc.first = existing; 4724 blockAndLoc.second = loc; 4725 return blockAndLoc.first; 4726 } 4727 4728 // Forward declarations are removed once defined, so if we are defining a 4729 // existing block and it is not a forward declaration, then it is a 4730 // redeclaration. 4731 if (!eraseForwardRef(blockAndLoc.first)) 4732 return nullptr; 4733 return blockAndLoc.first; 4734 } 4735 4736 /// Parse a (possibly empty) list of SSA operands with types as block arguments. 4737 /// 4738 /// ssa-id-and-type-list ::= ssa-id-and-type (`,` ssa-id-and-type)* 4739 /// 4740 ParseResult OperationParser::parseOptionalBlockArgList( 4741 SmallVectorImpl<BlockArgument> &results, Block *owner) { 4742 if (getToken().is(Token::r_brace)) 4743 return success(); 4744 4745 // If the block already has arguments, then we're handling the entry block. 4746 // Parse and register the names for the arguments, but do not add them. 4747 bool definingExistingArgs = owner->getNumArguments() != 0; 4748 unsigned nextArgument = 0; 4749 4750 return parseCommaSeparatedList([&]() -> ParseResult { 4751 return parseSSADefOrUseAndType( 4752 [&](SSAUseInfo useInfo, Type type) -> ParseResult { 4753 // If this block did not have existing arguments, define a new one. 4754 if (!definingExistingArgs) 4755 return addDefinition(useInfo, owner->addArgument(type)); 4756 4757 // Otherwise, ensure that this argument has already been created. 4758 if (nextArgument >= owner->getNumArguments()) 4759 return emitError("too many arguments specified in argument list"); 4760 4761 // Finally, make sure the existing argument has the correct type. 4762 auto arg = owner->getArgument(nextArgument++); 4763 if (arg.getType() != type) 4764 return emitError("argument and block argument type mismatch"); 4765 return addDefinition(useInfo, arg); 4766 }); 4767 }); 4768 } 4769 4770 //===----------------------------------------------------------------------===// 4771 // Top-level entity parsing. 4772 //===----------------------------------------------------------------------===// 4773 4774 namespace { 4775 /// This parser handles entities that are only valid at the top level of the 4776 /// file. 4777 class ModuleParser : public Parser { 4778 public: 4779 explicit ModuleParser(ParserState &state) : Parser(state) {} 4780 4781 ParseResult parseModule(ModuleOp module); 4782 4783 private: 4784 /// Parse an attribute alias declaration. 4785 ParseResult parseAttributeAliasDef(); 4786 4787 /// Parse an attribute alias declaration. 4788 ParseResult parseTypeAliasDef(); 4789 }; 4790 } // end anonymous namespace 4791 4792 /// Parses an attribute alias declaration. 4793 /// 4794 /// attribute-alias-def ::= '#' alias-name `=` attribute-value 4795 /// 4796 ParseResult ModuleParser::parseAttributeAliasDef() { 4797 assert(getToken().is(Token::hash_identifier)); 4798 StringRef aliasName = getTokenSpelling().drop_front(); 4799 4800 // Check for redefinitions. 4801 if (getState().symbols.attributeAliasDefinitions.count(aliasName) > 0) 4802 return emitError("redefinition of attribute alias id '" + aliasName + "'"); 4803 4804 // Make sure this isn't invading the dialect attribute namespace. 4805 if (aliasName.contains('.')) 4806 return emitError("attribute names with a '.' are reserved for " 4807 "dialect-defined names"); 4808 4809 consumeToken(Token::hash_identifier); 4810 4811 // Parse the '='. 4812 if (parseToken(Token::equal, "expected '=' in attribute alias definition")) 4813 return failure(); 4814 4815 // Parse the attribute value. 4816 Attribute attr = parseAttribute(); 4817 if (!attr) 4818 return failure(); 4819 4820 getState().symbols.attributeAliasDefinitions[aliasName] = attr; 4821 return success(); 4822 } 4823 4824 /// Parse a type alias declaration. 4825 /// 4826 /// type-alias-def ::= '!' alias-name `=` 'type' type 4827 /// 4828 ParseResult ModuleParser::parseTypeAliasDef() { 4829 assert(getToken().is(Token::exclamation_identifier)); 4830 StringRef aliasName = getTokenSpelling().drop_front(); 4831 4832 // Check for redefinitions. 4833 if (getState().symbols.typeAliasDefinitions.count(aliasName) > 0) 4834 return emitError("redefinition of type alias id '" + aliasName + "'"); 4835 4836 // Make sure this isn't invading the dialect type namespace. 4837 if (aliasName.contains('.')) 4838 return emitError("type names with a '.' are reserved for " 4839 "dialect-defined names"); 4840 4841 consumeToken(Token::exclamation_identifier); 4842 4843 // Parse the '=' and 'type'. 4844 if (parseToken(Token::equal, "expected '=' in type alias definition") || 4845 parseToken(Token::kw_type, "expected 'type' in type alias definition")) 4846 return failure(); 4847 4848 // Parse the type. 4849 Type aliasedType = parseType(); 4850 if (!aliasedType) 4851 return failure(); 4852 4853 // Register this alias with the parser state. 4854 getState().symbols.typeAliasDefinitions.try_emplace(aliasName, aliasedType); 4855 return success(); 4856 } 4857 4858 /// This is the top-level module parser. 4859 ParseResult ModuleParser::parseModule(ModuleOp module) { 4860 OperationParser opParser(getState(), module); 4861 4862 // Module itself is a name scope. 4863 opParser.pushSSANameScope(/*isIsolated=*/true); 4864 4865 while (true) { 4866 switch (getToken().getKind()) { 4867 default: 4868 // Parse a top-level operation. 4869 if (opParser.parseOperation()) 4870 return failure(); 4871 break; 4872 4873 // If we got to the end of the file, then we're done. 4874 case Token::eof: { 4875 if (opParser.finalize()) 4876 return failure(); 4877 4878 // Handle the case where the top level module was explicitly defined. 4879 auto &bodyBlocks = module.getBodyRegion().getBlocks(); 4880 auto &operations = bodyBlocks.front().getOperations(); 4881 assert(!operations.empty() && "expected a valid module terminator"); 4882 4883 // Check that the first operation is a module, and it is the only 4884 // non-terminator operation. 4885 ModuleOp nested = dyn_cast<ModuleOp>(operations.front()); 4886 if (nested && std::next(operations.begin(), 2) == operations.end()) { 4887 // Merge the data of the nested module operation into 'module'. 4888 module.setLoc(nested.getLoc()); 4889 module.setAttrs(nested.getOperation()->getAttrList()); 4890 bodyBlocks.splice(bodyBlocks.end(), nested.getBodyRegion().getBlocks()); 4891 4892 // Erase the original module body. 4893 bodyBlocks.pop_front(); 4894 } 4895 4896 return opParser.popSSANameScope(); 4897 } 4898 4899 // If we got an error token, then the lexer already emitted an error, just 4900 // stop. Someday we could introduce error recovery if there was demand 4901 // for it. 4902 case Token::error: 4903 return failure(); 4904 4905 // Parse an attribute alias. 4906 case Token::hash_identifier: 4907 if (parseAttributeAliasDef()) 4908 return failure(); 4909 break; 4910 4911 // Parse a type alias. 4912 case Token::exclamation_identifier: 4913 if (parseTypeAliasDef()) 4914 return failure(); 4915 break; 4916 } 4917 } 4918 } 4919 4920 //===----------------------------------------------------------------------===// 4921 4922 /// This parses the file specified by the indicated SourceMgr and returns an 4923 /// MLIR module if it was valid. If not, it emits diagnostics and returns 4924 /// null. 4925 OwningModuleRef mlir::parseSourceFile(const llvm::SourceMgr &sourceMgr, 4926 MLIRContext *context) { 4927 auto sourceBuf = sourceMgr.getMemoryBuffer(sourceMgr.getMainFileID()); 4928 4929 // This is the result module we are parsing into. 4930 OwningModuleRef module(ModuleOp::create(FileLineColLoc::get( 4931 sourceBuf->getBufferIdentifier(), /*line=*/0, /*column=*/0, context))); 4932 4933 SymbolState aliasState; 4934 ParserState state(sourceMgr, context, aliasState); 4935 if (ModuleParser(state).parseModule(*module)) 4936 return nullptr; 4937 4938 // Make sure the parse module has no other structural problems detected by 4939 // the verifier. 4940 if (failed(verify(*module))) 4941 return nullptr; 4942 4943 return module; 4944 } 4945 4946 /// This parses the file specified by the indicated filename and returns an 4947 /// MLIR module if it was valid. If not, the error message is emitted through 4948 /// the error handler registered in the context, and a null pointer is returned. 4949 OwningModuleRef mlir::parseSourceFile(StringRef filename, 4950 MLIRContext *context) { 4951 llvm::SourceMgr sourceMgr; 4952 return parseSourceFile(filename, sourceMgr, context); 4953 } 4954 4955 /// This parses the file specified by the indicated filename using the provided 4956 /// SourceMgr and returns an MLIR module if it was valid. If not, the error 4957 /// message is emitted through the error handler registered in the context, and 4958 /// a null pointer is returned. 4959 OwningModuleRef mlir::parseSourceFile(StringRef filename, 4960 llvm::SourceMgr &sourceMgr, 4961 MLIRContext *context) { 4962 if (sourceMgr.getNumBuffers() != 0) { 4963 // TODO(b/136086478): Extend to support multiple buffers. 4964 emitError(mlir::UnknownLoc::get(context), 4965 "only main buffer parsed at the moment"); 4966 return nullptr; 4967 } 4968 auto file_or_err = llvm::MemoryBuffer::getFileOrSTDIN(filename); 4969 if (std::error_code error = file_or_err.getError()) { 4970 emitError(mlir::UnknownLoc::get(context), 4971 "could not open input file " + filename); 4972 return nullptr; 4973 } 4974 4975 // Load the MLIR module. 4976 sourceMgr.AddNewSourceBuffer(std::move(*file_or_err), llvm::SMLoc()); 4977 return parseSourceFile(sourceMgr, context); 4978 } 4979 4980 /// This parses the program string to a MLIR module if it was valid. If not, 4981 /// it emits diagnostics and returns null. 4982 OwningModuleRef mlir::parseSourceString(StringRef moduleStr, 4983 MLIRContext *context) { 4984 auto memBuffer = MemoryBuffer::getMemBuffer(moduleStr); 4985 if (!memBuffer) 4986 return nullptr; 4987 4988 SourceMgr sourceMgr; 4989 sourceMgr.AddNewSourceBuffer(std::move(memBuffer), SMLoc()); 4990 return parseSourceFile(sourceMgr, context); 4991 } 4992 4993 /// Parses a symbol, of type 'T', and returns it if parsing was successful. If 4994 /// parsing failed, nullptr is returned. The number of bytes read from the input 4995 /// string is returned in 'numRead'. 4996 template <typename T, typename ParserFn> 4997 static T parseSymbol(StringRef inputStr, MLIRContext *context, size_t &numRead, 4998 ParserFn &&parserFn) { 4999 SymbolState aliasState; 5000 return parseSymbol<T>( 5001 inputStr, context, aliasState, 5002 [&](Parser &parser) { 5003 SourceMgrDiagnosticHandler handler( 5004 const_cast<llvm::SourceMgr &>(parser.getSourceMgr()), 5005 parser.getContext()); 5006 return parserFn(parser); 5007 }, 5008 &numRead); 5009 } 5010 5011 Attribute mlir::parseAttribute(StringRef attrStr, MLIRContext *context) { 5012 size_t numRead = 0; 5013 return parseAttribute(attrStr, context, numRead); 5014 } 5015 Attribute mlir::parseAttribute(StringRef attrStr, Type type) { 5016 size_t numRead = 0; 5017 return parseAttribute(attrStr, type, numRead); 5018 } 5019 5020 Attribute mlir::parseAttribute(StringRef attrStr, MLIRContext *context, 5021 size_t &numRead) { 5022 return parseSymbol<Attribute>(attrStr, context, numRead, [](Parser &parser) { 5023 return parser.parseAttribute(); 5024 }); 5025 } 5026 Attribute mlir::parseAttribute(StringRef attrStr, Type type, size_t &numRead) { 5027 return parseSymbol<Attribute>( 5028 attrStr, type.getContext(), numRead, 5029 [type](Parser &parser) { return parser.parseAttribute(type); }); 5030 } 5031 5032 Type mlir::parseType(StringRef typeStr, MLIRContext *context) { 5033 size_t numRead = 0; 5034 return parseType(typeStr, context, numRead); 5035 } 5036 5037 Type mlir::parseType(StringRef typeStr, MLIRContext *context, size_t &numRead) { 5038 return parseSymbol<Type>(typeStr, context, numRead, 5039 [](Parser &parser) { return parser.parseType(); }); 5040 } 5041