MLIR 24.0.0git
AttributeParser.cpp
Go to the documentation of this file.
1//===- AttributeParser.cpp - MLIR Attribute 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 Types.
10//
11//===----------------------------------------------------------------------===//
12
13#include "Parser.h"
14
16#include "mlir/IR/AffineMap.h"
22#include "mlir/IR/IntegerSet.h"
23#include <optional>
24
25using namespace mlir;
26using namespace mlir::detail;
27
28/// Parse an arbitrary attribute.
29///
30/// attribute-value ::= `unit`
31/// | bool-literal
32/// | integer-literal (`:` (index-type | integer-type))?
33/// | float-literal (`:` float-type)?
34/// | string-literal (`:` type)?
35/// | type
36/// | `[` `:` (integer-type | float-type) tensor-literal `]`
37/// | `[` (attribute-value (`,` attribute-value)*)? `]`
38/// | `{` (attribute-entry (`,` attribute-entry)*)? `}`
39/// | symbol-ref-id (`::` symbol-ref-id)*
40/// | `dense` `<` tensor-literal `>` `:`
41/// (tensor-type | vector-type)
42/// | `sparse` `<` attribute-value `,` attribute-value `>`
43/// `:` (tensor-type | vector-type)
44/// | `strided` `<` `[` comma-separated-int-or-question `]`
45/// (`,` `offset` `:` integer-literal)? `>`
46/// | distinct-attribute
47/// | extended-attribute
48///
50 switch (getToken().getKind()) {
51 // Parse an AffineMap or IntegerSet attribute.
52 case Token::kw_affine_map: {
53 consumeToken(Token::kw_affine_map);
54
55 AffineMap map;
56 if (parseToken(Token::less, "expected '<' in affine map") ||
58 parseToken(Token::greater, "expected '>' in affine map"))
59 return Attribute();
60 return AffineMapAttr::get(map);
61 }
62 case Token::kw_affine_set: {
63 consumeToken(Token::kw_affine_set);
64
65 IntegerSet set;
66 if (parseToken(Token::less, "expected '<' in integer set") ||
68 parseToken(Token::greater, "expected '>' in integer set"))
69 return Attribute();
70 return IntegerSetAttr::get(set);
71 }
72
73 // Parse an array attribute.
74 case Token::l_square: {
75 consumeToken(Token::l_square);
77 auto parseElt = [&]() -> ParseResult {
78 elements.push_back(parseAttribute());
79 return elements.back() ? success() : failure();
80 };
81
82 if (parseCommaSeparatedListUntil(Token::r_square, parseElt))
83 return nullptr;
84 return builder.getArrayAttr(elements);
85 }
86
87 // Parse a boolean attribute.
88 case Token::kw_false:
89 consumeToken(Token::kw_false);
90 return builder.getBoolAttr(false);
91 case Token::kw_true:
92 consumeToken(Token::kw_true);
93 return builder.getBoolAttr(true);
94
95 // Parse a dense elements attribute.
96 case Token::kw_dense:
97 return parseDenseElementsAttr(type);
98
99 // Parse a dense resource elements attribute.
100 case Token::kw_dense_resource:
102
103 // Parse a dense array attribute.
104 case Token::kw_array:
105 return parseDenseArrayAttr(type);
106
107 // Parse a dictionary attribute.
108 case Token::l_brace: {
109 NamedAttrList elements;
110 if (parseAttributeDict(elements))
111 return nullptr;
112 return elements.getDictionary(getContext());
113 }
114
115 // Parse an extended attribute, i.e. alias or dialect attribute.
116 case Token::hash_identifier:
117 return parseExtendedAttr(type);
118
119 // Parse floating point and integer attributes.
120 case Token::floatliteral:
121 return parseFloatAttr(type, /*isNegative=*/false);
122 case Token::integer:
123 return parseDecOrHexAttr(type, /*isNegative=*/false);
124 case Token::minus: {
125 consumeToken(Token::minus);
126 if (getToken().is(Token::integer))
127 return parseDecOrHexAttr(type, /*isNegative=*/true);
128 if (getToken().is(Token::floatliteral))
129 return parseFloatAttr(type, /*isNegative=*/true);
130
131 return (emitWrongTokenError(
132 "expected constant integer or floating point value"),
133 nullptr);
134 }
135
136 // Parse a location attribute.
137 case Token::kw_loc: {
138 consumeToken(Token::kw_loc);
139
140 LocationAttr locAttr;
141 if (parseToken(Token::l_paren, "expected '(' in inline location") ||
142 parseLocationInstance(locAttr) ||
143 parseToken(Token::r_paren, "expected ')' in inline location"))
144 return Attribute();
145 return locAttr;
146 }
147
148 // Parse a sparse elements attribute.
149 case Token::kw_sparse:
150 return parseSparseElementsAttr(type);
151
152 // Parse a strided layout attribute.
153 case Token::kw_strided:
154 return parseStridedLayoutAttr();
155
156 // Parse a distinct attribute.
157 case Token::kw_distinct:
158 return parseDistinctAttr(type);
159
160 // Parse a string attribute.
161 case Token::string: {
162 auto val = getToken().getStringValue();
163 consumeToken(Token::string);
164 // Parse the optional trailing colon type if one wasn't explicitly provided.
165 if (!type && consumeIf(Token::colon) && !(type = parseType()))
166 return Attribute();
167
168 return type ? StringAttr::get(val, type)
169 : StringAttr::get(getContext(), val);
170 }
171
172 // Parse a symbol reference attribute.
173 case Token::at_identifier: {
174 // When populating the parser state, this is a list of locations for all of
175 // the nested references.
176 SmallVector<SMRange> referenceLocations;
177 if (state.asmState)
178 referenceLocations.push_back(getToken().getLocRange());
179
180 // Parse the top-level reference.
181 std::string nameStr = getToken().getSymbolReference();
182 consumeToken(Token::at_identifier);
183
184 // Parse any nested references.
185 std::vector<FlatSymbolRefAttr> nestedRefs;
186 while (getToken().is(Token::colon)) {
187 // Check for the '::' prefix.
188 const char *curPointer = getToken().getLoc().getPointer();
189 consumeToken(Token::colon);
190 if (!consumeIf(Token::colon)) {
191 if (getToken().isNot(Token::eof, Token::error)) {
192 state.lex.resetPointer(curPointer);
193 consumeToken();
194 }
195 break;
196 }
197 // Parse the reference itself.
198 auto curLoc = getToken().getLoc();
199 if (getToken().isNot(Token::at_identifier)) {
200 emitError(curLoc, "expected nested symbol reference identifier");
201 return Attribute();
202 }
203
204 // If we are populating the assembly state, add the location for this
205 // reference.
206 if (state.asmState)
207 referenceLocations.push_back(getToken().getLocRange());
208
209 std::string nameStr = getToken().getSymbolReference();
210 consumeToken(Token::at_identifier);
211 nestedRefs.push_back(SymbolRefAttr::get(getContext(), nameStr));
212 }
213 SymbolRefAttr symbolRefAttr =
214 SymbolRefAttr::get(getContext(), nameStr, nestedRefs);
215
216 // If we are populating the assembly state, record this symbol reference.
217 if (state.asmState)
218 state.asmState->addUses(symbolRefAttr, referenceLocations);
219 return symbolRefAttr;
220 }
221
222 // Parse a 'unit' attribute.
223 case Token::kw_unit:
224 consumeToken(Token::kw_unit);
225 return builder.getUnitAttr();
226
227 // Handle completion of an attribute.
228 case Token::code_complete:
229 if (getToken().isCodeCompletionFor(Token::hash_identifier))
230 return parseExtendedAttr(type);
231 return codeCompleteAttribute();
232
233 default:
234 // Parse a type attribute. We parse `Optional` here to allow for providing a
235 // better error message.
236 Type type;
238 if (!result.has_value())
239 return emitWrongTokenError("expected attribute value"), Attribute();
240 return failed(*result) ? Attribute() : TypeAttr::get(type);
241 }
242}
243
244/// Parse an optional attribute with the provided type.
246 Type type) {
247 switch (getToken().getKind()) {
248 case Token::at_identifier:
249 case Token::floatliteral:
250 case Token::integer:
251 case Token::hash_identifier:
252 case Token::kw_affine_map:
253 case Token::kw_affine_set:
254 case Token::kw_dense:
255 case Token::kw_dense_resource:
256 case Token::kw_false:
257 case Token::kw_loc:
258 case Token::kw_sparse:
259 case Token::kw_true:
260 case Token::kw_unit:
261 case Token::l_brace:
262 case Token::l_square:
263 case Token::minus:
264 case Token::string:
265 attribute = parseAttribute(type);
266 return success(attribute != nullptr);
267
268 default:
269 // Parse an optional type attribute.
270 Type type;
272 if (result.has_value() && succeeded(*result))
273 attribute = TypeAttr::get(type);
274 return result;
275 }
276}
278 Type type) {
279 return parseOptionalAttributeWithToken(Token::l_square, attribute, type);
280}
282 Type type) {
283 return parseOptionalAttributeWithToken(Token::string, attribute, type);
284}
286 Type type) {
287 return parseOptionalAttributeWithToken(Token::at_identifier, result, type);
288}
289
290/// Attribute dictionary.
291///
292/// attribute-dict ::= `{` `}`
293/// | `{` attribute-entry (`,` attribute-entry)* `}`
294/// attribute-entry ::= (bare-id | string-literal) `=` attribute-value
295///
297 llvm::SmallDenseSet<StringAttr> seenKeys;
298 auto parseElt = [&]() -> ParseResult {
299 // The name of an attribute can either be a bare identifier, or a string.
300 std::optional<StringAttr> nameId;
301 if (getToken().is(Token::string))
302 nameId = builder.getStringAttr(getToken().getStringValue());
303 else if (getToken().isAny(Token::bare_identifier, Token::inttype) ||
304 getToken().isKeyword())
305 nameId = builder.getStringAttr(getTokenSpelling());
306 else
307 return emitWrongTokenError("expected attribute name");
308
309 if (nameId->empty())
310 return emitError("expected valid attribute name");
311
312 if (!seenKeys.insert(*nameId).second)
313 return emitError("duplicate key '")
314 << nameId->getValue() << "' in dictionary attribute";
315 consumeToken();
316
317 // Lazy load a dialect in the context if there is a possible namespace.
318 auto splitName = nameId->strref().split('.');
319 if (!splitName.second.empty())
320 getContext()->getOrLoadDialect(splitName.first);
321
322 // Try to parse the '=' for the attribute value.
323 if (!consumeIf(Token::equal)) {
324 // If there is no '=', we treat this as a unit attribute.
325 attributes.push_back({*nameId, builder.getUnitAttr()});
326 return success();
327 }
328
329 auto attr = parseAttribute();
330 if (!attr)
331 return failure();
332 attributes.push_back({*nameId, attr});
333 return success();
334 };
335
336 return parseCommaSeparatedList(Delimiter::Braces, parseElt,
337 " in attribute dictionary");
338}
339
340/// Parse a float attribute.
341Attribute Parser::parseFloatAttr(Type type, bool isNegative) {
342 SMLoc loc = getToken().getLoc();
343 auto val = getToken().getFloatingPointValue();
344 if (!val)
345 return (emitError("floating point value too large for attribute"), nullptr);
346 consumeToken(Token::floatliteral);
347 if (!type) {
348 // Default to F64 when no type is specified.
349 if (!consumeIf(Token::colon))
350 type = builder.getF64Type();
351 else if (!(type = parseType()))
352 return nullptr;
353 }
354 if (!isa<FloatType>(type))
355 return (emitError("floating point value not valid for specified type"),
356 nullptr);
357 // A type with no signed representation, such as f8E8M0FNU, has no encoding
358 // for a negative value. The conversion inside FloatAttr::get keeps the sign
359 // bit, and printing the attribute that comes out of it asserts.
360 if (isNegative && !APFloat::semanticsHasSignedRepr(
361 cast<FloatType>(type).getFloatSemantics()))
362 return (emitError(loc, "negative floating point literal for a type with no "
363 "signed representation"),
364 nullptr);
365 return FloatAttr::get(type, isNegative ? -*val : *val);
366}
367
368/// Construct an APint from a parsed value, a known attribute type and
369/// sign.
370static std::optional<APInt> buildAttributeAPInt(Type type, bool isNegative,
371 StringRef spelling) {
372 // Parse the integer value into an APInt that is big enough to hold the value.
373 APInt result;
374 bool isHex = spelling.size() > 1 && spelling[1] == 'x';
375 if (spelling.getAsInteger(isHex ? 0 : 10, result))
376 return std::nullopt;
377
378 // Extend or truncate the bitwidth to the right size.
379 unsigned width = type.isIndex() ? IndexType::kInternalStorageBitWidth
380 : type.getIntOrFloatBitWidth();
381
382 if (width > result.getBitWidth()) {
383 result = result.zext(width);
384 } else if (width < result.getBitWidth()) {
385 // The parser can return an unnecessarily wide result with leading zeros.
386 // This isn't a problem, but truncating off bits is bad.
387 if (result.countl_zero() < result.getBitWidth() - width)
388 return std::nullopt;
389
390 result = result.trunc(width);
391 }
392
393 if (width == 0) {
394 // 0 bit integers cannot be negative and manipulation of their sign bit will
395 // assert, so short-cut validation here.
396 if (isNegative)
397 return std::nullopt;
398 } else if (isNegative) {
399 // The value is negative, we have an overflow if the sign bit is not set
400 // in the negated apInt.
401 result.negate();
402 if (!result.isSignBitSet())
403 return std::nullopt;
404 } else if ((type.isSignedInteger() || type.isIndex()) &&
405 result.isSignBitSet()) {
406 // The value is a positive signed integer or index,
407 // we have an overflow if the sign bit is set.
408 return std::nullopt;
409 }
410
411 return result;
412}
413
414/// Parse a decimal or a hexadecimal literal, which can be either an integer
415/// or a float attribute.
417 Token tok = getToken();
418 StringRef spelling = tok.getSpelling();
419 SMLoc loc = tok.getLoc();
420
421 consumeToken(Token::integer);
422 if (!type) {
423 // Default to i64 if not type is specified.
424 if (!consumeIf(Token::colon))
425 type = builder.getIntegerType(64);
426 else if (!(type = parseType()))
427 return nullptr;
428 }
429
430 if (auto floatType = dyn_cast<FloatType>(type)) {
431 std::optional<APFloat> result;
432 if (failed(parseFloatFromIntegerLiteral(result, tok, isNegative,
433 floatType.getFloatSemantics())))
434 return Attribute();
435 return FloatAttr::get(floatType, *result);
436 }
437
438 if (!isa<IntegerType, IndexType>(type))
439 return emitError(loc, "integer literal not valid for specified type"),
440 nullptr;
441
442 if (isNegative && type.isUnsignedInteger()) {
443 emitError(loc,
444 "negative integer literal not valid for unsigned integer type");
445 return nullptr;
446 }
447
448 std::optional<APInt> apInt = buildAttributeAPInt(type, isNegative, spelling);
449 if (!apInt)
450 return emitError(loc, "integer constant out of range for attribute"),
451 nullptr;
452 return builder.getIntegerAttr(type, *apInt);
453}
454
455//===----------------------------------------------------------------------===//
456// TensorLiteralParser
457//===----------------------------------------------------------------------===//
458
459/// Parse elements values stored within a hex string. On success, the values are
460/// stored into 'result'.
461static ParseResult parseElementAttrHexValues(Parser &parser, Token tok,
462 std::string &result) {
463 if (std::optional<std::string> value = tok.getHexStringValue()) {
464 result = std::move(*value);
465 return success();
466 }
467 return parser.emitError(
468 tok.getLoc(), "expected string containing hex digits starting with `0x`");
469}
470
471namespace {
472/// This class implements a parser for TensorLiterals. A tensor literal is
473/// either a single element (e.g, 5) or a multi-dimensional list of elements
474/// (e.g., [[5, 5]]).
475class TensorLiteralParser {
476public:
477 TensorLiteralParser(Parser &p) : p(p) {}
478
479 /// Parse the elements of a tensor literal. If 'allowHex' is true, the parser
480 /// may also parse a tensor literal that is store as a hex string.
481 ParseResult parse(bool allowHex);
482
483 /// Build a dense attribute instance with the parsed elements and the given
484 /// shaped type.
485 DenseElementsAttr getAttr(SMLoc loc, ShapedType type);
486
487 ArrayRef<int64_t> getShape() const { return shape; }
488
489private:
490 /// Get the parsed elements for an integer attribute.
491 ParseResult getIntAttrElements(SMLoc loc, Type eltTy,
492 std::vector<APInt> &intValues);
493
494 /// Get the parsed elements for a float attribute.
495 ParseResult getFloatAttrElements(SMLoc loc, FloatType eltTy,
496 std::vector<APFloat> &floatValues);
497
498 /// Build a Dense String attribute for the given type.
499 DenseElementsAttr getStringAttr(SMLoc loc, ShapedType type, Type eltTy);
500
501 /// Build a Dense attribute with hex data for the given type.
502 DenseElementsAttr getHexAttr(SMLoc loc, ShapedType type);
503
504 /// Parse a single element, returning failure if it isn't a valid element
505 /// literal. For example:
506 /// parseElement(1) -> Success, 1
507 /// parseElement([1]) -> Failure
508 ParseResult parseElement();
509
510 /// Parse a list of either lists or elements, returning the dimensions of the
511 /// parsed sub-tensors in dims. For example:
512 /// parseList([1, 2, 3]) -> Success, [3]
513 /// parseList([[1, 2], [3, 4]]) -> Success, [2, 2]
514 /// parseList([[1, 2], 3]) -> Failure
515 /// parseList([[1, [2, 3]], [4, [5]]]) -> Failure
516 ParseResult parseList(SmallVectorImpl<int64_t> &dims);
517
518 /// Parse a literal that was printed as a hex string.
519 ParseResult parseHexElements();
520
521 Parser &p;
522
523 /// The shape inferred from the parsed elements.
524 SmallVector<int64_t, 4> shape;
525
526 /// Storage used when parsing elements, this is a pair of <is_negated, token>.
527 std::vector<std::pair<bool, Token>> storage;
528
529 /// Storage used when parsing elements that were stored as hex values.
530 std::optional<Token> hexStorage;
531};
532} // namespace
533
534/// Parse the elements of a tensor literal. If 'allowHex' is true, the parser
535/// may also parse a tensor literal that is store as a hex string.
536ParseResult TensorLiteralParser::parse(bool allowHex) {
537 // If hex is allowed, check for a string literal.
538 if (allowHex && p.getToken().is(Token::string)) {
539 hexStorage = p.getToken();
540 p.consumeToken(Token::string);
541 return success();
542 }
543 // Otherwise, parse a list or an individual element.
544 if (p.getToken().is(Token::l_square))
545 return parseList(shape);
546 return parseElement();
547}
548
549/// Build a dense attribute instance with the parsed elements and the given
550/// shaped type.
551DenseElementsAttr TensorLiteralParser::getAttr(SMLoc loc, ShapedType type) {
552 Type eltType = type.getElementType();
553
554 // Check to see if we parse the literal from a hex string.
555 if (hexStorage &&
556 (eltType.isIntOrIndexOrFloat() || isa<ComplexType>(eltType)))
557 return getHexAttr(loc, type);
558
559 // Check that the parsed storage size has the same number of elements to the
560 // type, or is a known splat.
561 if (!shape.empty() && getShape() != type.getShape()) {
562 p.emitError(loc) << "inferred shape of elements literal ([" << getShape()
563 << "]) does not match type ([" << type.getShape() << "])";
564 return nullptr;
565 }
566
567 // Handle the case where no elements were parsed.
568 if (!hexStorage && storage.empty() && type.getNumElements()) {
569 p.emitError(loc) << "parsed zero elements, but type (" << type
570 << ") expected at least 1";
571 return nullptr;
572 }
573
574 // Handle complex types in the specific element type cases below.
575 bool isComplex = false;
576 if (ComplexType complexTy = dyn_cast<ComplexType>(eltType)) {
577 eltType = complexTy.getElementType();
578 isComplex = true;
579 // Complex types have N*2 elements or complex splat.
580 // Empty shape may mean a splat or empty literal, only validate splats.
581 bool isSplat = shape.empty() && type.getNumElements() != 0;
582 if (isSplat && storage.size() != 2) {
583 p.emitError(loc) << "parsed " << storage.size() << " elements, but type ("
584 << complexTy << ") expected 2 elements";
585 return nullptr;
586 }
587 if (!shape.empty() &&
588 storage.size() != static_cast<size_t>(type.getNumElements()) * 2) {
589 p.emitError(loc) << "parsed " << storage.size() << " elements, but type ("
590 << type << ") expected " << type.getNumElements() * 2
591 << " elements";
592 return nullptr;
593 }
594 }
595
596 // Handle integer and index types.
597 if (eltType.isIntOrIndex()) {
598 std::vector<APInt> intValues;
599 if (failed(getIntAttrElements(loc, eltType, intValues)))
600 return nullptr;
601 if (isComplex) {
602 // If this is a complex, treat the parsed values as complex values.
603 auto complexData = llvm::ArrayRef(
604 reinterpret_cast<mlir::Complex<APInt> *>(intValues.data()),
605 intValues.size() / 2);
606 return DenseElementsAttr::get(type, complexData);
607 }
608 return DenseElementsAttr::get(type, intValues);
609 }
610 // Handle floating point types.
611 if (FloatType floatTy = dyn_cast<FloatType>(eltType)) {
612 std::vector<APFloat> floatValues;
613 if (failed(getFloatAttrElements(loc, floatTy, floatValues)))
614 return nullptr;
615 if (isComplex) {
616 // If this is a complex, treat the parsed values as complex values.
617 auto complexData = llvm::ArrayRef(
618 reinterpret_cast<mlir::Complex<APFloat> *>(floatValues.data()),
619 floatValues.size() / 2);
620 return DenseElementsAttr::get(type, complexData);
621 }
622 return DenseElementsAttr::get(type, floatValues);
623 }
624
625 // Other types are assumed to be string representations.
626 return getStringAttr(loc, type, type.getElementType());
627}
628
629/// Build a Dense Integer attribute for the given type.
630ParseResult
631TensorLiteralParser::getIntAttrElements(SMLoc loc, Type eltTy,
632 std::vector<APInt> &intValues) {
633 intValues.reserve(storage.size());
634 bool isUintType = eltTy.isUnsignedInteger();
635 for (const auto &signAndToken : storage) {
636 bool isNegative = signAndToken.first;
637 const Token &token = signAndToken.second;
638 auto tokenLoc = token.getLoc();
639
640 if (isNegative && isUintType) {
641 return p.emitError(tokenLoc)
642 << "expected unsigned integer elements, but parsed negative value";
643 }
644
645 // Check to see if floating point values were parsed.
646 if (token.is(Token::floatliteral)) {
647 return p.emitError(tokenLoc)
648 << "expected integer elements, but parsed floating-point";
649 }
650
651 assert(token.isAny(Token::integer, Token::kw_true, Token::kw_false) &&
652 "unexpected token type");
653 if (token.isAny(Token::kw_true, Token::kw_false)) {
654 if (!eltTy.isInteger(1)) {
655 return p.emitError(tokenLoc)
656 << "expected i1 type for 'true' or 'false' values";
657 }
658 APInt apInt(1, token.is(Token::kw_true), /*isSigned=*/false);
659 intValues.push_back(apInt);
660 continue;
661 }
662
663 // Create APInt values for each element with the correct bitwidth.
664 std::optional<APInt> apInt =
665 buildAttributeAPInt(eltTy, isNegative, token.getSpelling());
666 if (!apInt)
667 return p.emitError(tokenLoc, "integer constant out of range for type");
668 intValues.push_back(*apInt);
669 }
670 return success();
671}
672
673/// Build a Dense Float attribute for the given type.
674ParseResult
675TensorLiteralParser::getFloatAttrElements(SMLoc loc, FloatType eltTy,
676 std::vector<APFloat> &floatValues) {
677 floatValues.reserve(storage.size());
678 for (const auto &signAndToken : storage) {
679 bool isNegative = signAndToken.first;
680 const Token &token = signAndToken.second;
681 std::optional<APFloat> result;
682 if (failed(p.parseFloatFromLiteral(result, token, isNegative,
683 eltTy.getFloatSemantics())))
684 return failure();
685 floatValues.push_back(*result);
686 }
687 return success();
688}
689
690/// Build a Dense String attribute for the given type.
691DenseElementsAttr TensorLiteralParser::getStringAttr(SMLoc loc, ShapedType type,
692 Type eltTy) {
693 if (hexStorage.has_value()) {
694 auto stringValue = hexStorage->getStringValue();
695 return DenseStringElementsAttr::get(type, {stringValue});
696 }
697
698 std::vector<std::string> stringValues;
699 std::vector<StringRef> stringRefValues;
700 stringValues.reserve(storage.size());
701 stringRefValues.reserve(storage.size());
702
703 for (auto val : storage) {
704 if (!val.second.is(Token::string)) {
705 p.emitError(loc) << "expected string token, got "
706 << val.second.getSpelling();
707 return nullptr;
708 }
709 stringValues.push_back(val.second.getStringValue());
710 stringRefValues.emplace_back(stringValues.back());
711 }
712
713 return DenseStringElementsAttr::get(type, stringRefValues);
714}
715
716/// Build a Dense attribute with hex data for the given type.
717DenseElementsAttr TensorLiteralParser::getHexAttr(SMLoc loc, ShapedType type) {
718 Type elementType = type.getElementType();
719 if (!elementType.isIntOrIndexOrFloat() && !isa<ComplexType>(elementType)) {
720 p.emitError(loc)
721 << "expected floating-point, integer, or complex element type, got "
722 << elementType;
723 return nullptr;
724 }
725
726 std::string data;
727 if (parseElementAttrHexValues(p, *hexStorage, data))
728 return nullptr;
729
730 ArrayRef<char> rawData(data);
731 if (!DenseElementsAttr::isValidRawBuffer(type, rawData)) {
732 p.emitError(loc) << "elements hex data size is invalid for provided type: "
733 << type;
734 return nullptr;
735 }
736
737 if (llvm::endianness::native == llvm::endianness::big) {
738 // Convert endianess in big-endian(BE) machines. `rawData` is
739 // little-endian(LE) because HEX in raw data of dense element attribute
740 // is always LE format. It is converted into BE here to be used in BE
741 // machines.
742 SmallVector<char, 64> outDataVec(rawData.size());
743 MutableArrayRef<char> convRawData(outDataVec);
744 DenseTypedElementsAttr::convertEndianOfArrayRefForBEmachine(
745 rawData, convRawData, type);
746 return DenseElementsAttr::getFromRawBuffer(type, convRawData);
747 }
748
749 return DenseElementsAttr::getFromRawBuffer(type, rawData);
750}
751
752ParseResult TensorLiteralParser::parseElement() {
753 switch (p.getToken().getKind()) {
754 // Parse a boolean element.
755 case Token::kw_true:
756 case Token::kw_false:
757 case Token::floatliteral:
758 case Token::integer:
759 storage.emplace_back(/*isNegative=*/false, p.getToken());
760 p.consumeToken();
761 break;
762
763 // Parse a signed integer or a negative floating-point element.
764 case Token::minus:
765 p.consumeToken(Token::minus);
766 if (!p.getToken().isAny(Token::floatliteral, Token::integer))
767 return p.emitError("expected integer or floating point literal");
768 storage.emplace_back(/*isNegative=*/true, p.getToken());
769 p.consumeToken();
770 break;
771
772 case Token::string:
773 storage.emplace_back(/*isNegative=*/false, p.getToken());
774 p.consumeToken();
775 break;
776
777 // Parse a complex element of the form '(' element ',' element ')'.
778 case Token::l_paren:
779 p.consumeToken(Token::l_paren);
780 if (parseElement() ||
781 p.parseToken(Token::comma, "expected ',' between complex elements") ||
782 parseElement() ||
783 p.parseToken(Token::r_paren, "expected ')' after complex elements"))
784 return failure();
785 break;
786
787 default:
788 return p.emitError("expected element literal of primitive type");
789 }
790
791 return success();
792}
793
794/// Parse a list of either lists or elements, returning the dimensions of the
795/// parsed sub-tensors in dims. For example:
796/// parseList([1, 2, 3]) -> Success, [3]
797/// parseList([[1, 2], [3, 4]]) -> Success, [2, 2]
798/// parseList([[1, 2], 3]) -> Failure
799/// parseList([[1, [2, 3]], [4, [5]]]) -> Failure
800ParseResult TensorLiteralParser::parseList(SmallVectorImpl<int64_t> &dims) {
801 auto checkDims = [&](const SmallVectorImpl<int64_t> &prevDims,
802 const SmallVectorImpl<int64_t> &newDims) -> ParseResult {
803 if (prevDims == newDims)
804 return success();
805 return p.emitError("tensor literal is invalid; ranks are not consistent "
806 "between elements");
807 };
808
809 bool first = true;
810 SmallVector<int64_t, 4> newDims;
811 unsigned size = 0;
812 auto parseOneElement = [&]() -> ParseResult {
813 SmallVector<int64_t, 4> thisDims;
814 if (p.getToken().getKind() == Token::l_square) {
815 if (parseList(thisDims))
816 return failure();
817 } else if (parseElement()) {
818 return failure();
819 }
820 ++size;
821 if (!first)
822 return checkDims(newDims, thisDims);
823 newDims = thisDims;
824 first = false;
825 return success();
826 };
827 if (p.parseCommaSeparatedList(Parser::Delimiter::Square, parseOneElement))
828 return failure();
829
830 // Return the sublists' dimensions with 'size' prepended.
831 dims.clear();
832 dims.push_back(size);
833 dims.append(newDims.begin(), newDims.end());
834 return success();
835}
836
837//===----------------------------------------------------------------------===//
838// DenseArrayAttr Parser
839//===----------------------------------------------------------------------===//
840
841namespace {
842/// A generic dense array element parser. It parsers integer and floating point
843/// elements.
844class DenseArrayElementParser {
845public:
846 explicit DenseArrayElementParser(Type type) : type(type) {}
847
848 /// Parse an integer element.
849 ParseResult parseIntegerElement(Parser &p);
850
851 /// Parse a floating point element.
852 ParseResult parseFloatElement(Parser &p);
853
854 /// Convert the current contents to a dense array.
855 DenseArrayAttr getAttr() { return DenseArrayAttr::get(type, size, rawData); }
856
857private:
858 /// Append the raw data of an APInt to the result.
859 void append(const APInt &data);
860
861 /// The array element type.
862 Type type;
863 /// The resultant byte array representing the contents of the array.
864 std::vector<char> rawData;
865 /// The number of elements in the array.
866 int64_t size = 0;
867};
868} // namespace
869
870void DenseArrayElementParser::append(const APInt &data) {
871 if (data.getBitWidth()) {
872 assert(data.getBitWidth() % 8 == 0);
873 unsigned byteSize = data.getBitWidth() / 8;
874 size_t offset = rawData.size();
875 rawData.insert(rawData.end(), byteSize, 0);
876 llvm::StoreIntToMemory(
877 data, reinterpret_cast<uint8_t *>(rawData.data() + offset), byteSize);
878 }
879 ++size;
880}
881
882ParseResult DenseArrayElementParser::parseIntegerElement(Parser &p) {
883 bool isNegative = p.consumeIf(Token::minus);
884
885 // Parse an integer literal as an APInt.
886 std::optional<APInt> value;
887 StringRef spelling = p.getToken().getSpelling();
888 if (p.getToken().isAny(Token::kw_true, Token::kw_false)) {
889 if (!type.isInteger(1))
890 return p.emitError("expected i1 type for 'true' or 'false' values");
891 value = APInt(/*numBits=*/8, p.getToken().is(Token::kw_true),
892 !type.isUnsignedInteger());
893 p.consumeToken();
894 } else if (p.consumeIf(Token::integer)) {
895 if (type.isInteger(1))
896 return p.emitError("expected 'true' or 'false' values for i1 type");
897 value = buildAttributeAPInt(type, isNegative, spelling);
898 if (!value)
899 return p.emitError("integer constant out of range");
900 } else {
901 return p.emitError("expected integer literal");
902 }
903 append(*value);
904 return success();
905}
906
907ParseResult DenseArrayElementParser::parseFloatElement(Parser &p) {
908 bool isNegative = p.consumeIf(Token::minus);
909 Token token = p.getToken();
910 std::optional<APFloat> fromIntLit;
911 if (failed(
912 p.parseFloatFromLiteral(fromIntLit, token, isNegative,
913 cast<FloatType>(type).getFloatSemantics())))
914 return failure();
915 p.consumeToken();
916 append(fromIntLit->bitcastToAPInt());
917 return success();
918}
919
920/// Parse a dense array attribute.
922 consumeToken(Token::kw_array);
923 if (parseToken(Token::less, "expected '<' after 'array'"))
924 return {};
925
926 SMLoc typeLoc = getToken().getLoc();
927 Type eltType = parseType();
928 if (!eltType) {
929 emitError(typeLoc, "expected an integer or floating point type");
930 return {};
931 }
932
933 // Only bool or integer and floating point elements divisible by bytes are
934 // supported.
935 if (!eltType.isIntOrFloat()) {
936 emitError(typeLoc, "expected integer or float type, got: ") << eltType;
937 return {};
938 }
939 if (!eltType.isInteger(1) && eltType.getIntOrFloatBitWidth() % 8 != 0) {
940 emitError(typeLoc, "element type bitwidth must be a multiple of 8");
941 return {};
942 }
943
944 // Check for empty list.
945 if (consumeIf(Token::greater))
946 return DenseArrayAttr::get(eltType, 0, {});
947
948 if (parseToken(Token::colon, "expected ':' after dense array type"))
949 return {};
950
951 DenseArrayElementParser eltParser(eltType);
952 if (isa<IntegerType>(eltType)) {
954 [&] { return eltParser.parseIntegerElement(*this); }))
955 return {};
956 } else {
958 [&] { return eltParser.parseFloatElement(*this); }))
959 return {};
960 }
961 if (parseToken(Token::greater, "expected '>' to close an array attribute"))
962 return {};
963 return eltParser.getAttr();
964}
965
966/// Try to parse a dense elements attribute with the type-first syntax.
967/// Syntax: dense<TYPE : [ATTR, ATTR, ...]>
968/// This syntax is used for types other than int, float, index and complex.
969///
970/// Returns:
971/// - "null" attribute if this is not the type-first syntax.
972/// - "failure" in case of a parse error.
973/// - A valid Attribute otherwise.
974static FailureOr<Attribute> parseDenseElementsAttrTyped(Parser &p, SMLoc loc) {
975 // Skip l_paren because "parseType" would try to parse it as a tuple/function
976 // type, but '(' starts a complex literal like in the literal-first syntax.
977 if (p.getToken().is(Token::l_paren))
978 return Attribute();
979
980 // Parse type and valdiate that it's a shaped type.
981 auto typeLoc = p.getToken().getLoc();
982 Type type;
983 OptionalParseResult typeResult = p.parseOptionalType(type);
984 if (!typeResult.has_value())
985 return Attribute(); // Not type-first syntax.
986 if (failed(*typeResult))
987 return failure(); // Type parse error.
988
989 auto shapedType = dyn_cast<ShapedType>(type);
990 if (!shapedType) {
991 p.emitError(typeLoc, "expected a shaped type for dense elements");
992 return failure();
993 }
994 if (!shapedType.hasStaticShape()) {
995 p.emitError(typeLoc, "dense elements type must have static shape");
996 return failure();
997 }
998
999 // Check that the element type implements DenseElementTypeInterface.
1000 auto denseEltType = dyn_cast<DenseElementType>(shapedType.getElementType());
1001 if (!denseEltType) {
1002 p.emitError(typeLoc,
1003 "element type must implement DenseElementTypeInterface "
1004 "for type-first dense syntax");
1005 return failure();
1006 }
1007
1008 // Parse colon.
1009 if (p.parseToken(Token::colon, "expected ':' after type in dense attribute"))
1010 return failure();
1011
1012 // Parse the element attributes and convert to raw bytes.
1013 SmallVector<char> rawData;
1014
1015 // Helper to parse a single element.
1016 auto parseSingleElement = [&]() -> ParseResult {
1017 Attribute elemAttr = p.parseAttribute();
1018 if (!elemAttr)
1019 return failure();
1020 if (failed(denseEltType.convertFromAttribute(elemAttr, rawData))) {
1021 p.emitError("incompatible attribute for element type");
1022 return failure();
1023 }
1024 return success();
1025 };
1026
1027 // Recursively parse elements matching the expected shape.
1028 std::function<ParseResult(ArrayRef<int64_t>)> parseElements;
1029 parseElements = [&](ArrayRef<int64_t> remainingShape) -> ParseResult {
1030 // Leaf: parse a single element.
1031 if (remainingShape.empty())
1032 return parseSingleElement();
1033
1034 // Non-leaf: expect a list with the correct number of elements.
1035 int64_t expectedCount = remainingShape.front();
1036 ArrayRef<int64_t> innerShape = remainingShape.drop_front();
1037 int64_t actualCount = 0;
1038
1039 auto parseOne = [&]() -> ParseResult {
1040 if (parseElements(innerShape))
1041 return failure();
1042 ++actualCount;
1043 return success();
1044 };
1045
1046 if (p.parseCommaSeparatedList(Parser::Delimiter::Square, parseOne))
1047 return failure();
1048
1049 if (actualCount != expectedCount) {
1050 p.emitError() << "expected " << expectedCount
1051 << " elements in dimension, got " << actualCount;
1052 return failure();
1053 }
1054 return success();
1055 };
1056
1057 // Parse elements.
1058 if (!p.getToken().is(Token::l_square)) {
1059 // Single element - parse as splat.
1060 if (parseSingleElement())
1061 return failure();
1062 } else if (shapedType.getShape().empty()) {
1063 // Scalar type shouldn't have a list.
1064 p.emitError(loc, "expected single element for scalar type, got list");
1065 return failure();
1066 } else {
1067 // Parse structured literal matching the shape.
1068 if (parseElements(shapedType.getShape()))
1069 return failure();
1070 }
1071
1072 if (p.parseToken(Token::greater, "expected '>' to close dense attribute"))
1073 return failure();
1074
1075 // Create the attribute from raw buffer.
1076 return DenseElementsAttr::getFromRawBuffer(shapedType, rawData);
1077}
1078
1079/// Parse a dense elements attribute.
1081 auto attribLoc = getToken().getLoc();
1082 consumeToken(Token::kw_dense);
1083 if (parseToken(Token::less, "expected '<' after 'dense'"))
1084 return nullptr;
1085
1086 // Try to parse the type-first syntax: dense<TYPE : [ATTR, ...]>
1087 FailureOr<Attribute> typedResult =
1088 parseDenseElementsAttrTyped(*this, attribLoc);
1089 if (failed(typedResult))
1090 return nullptr;
1091 if (*typedResult)
1092 return *typedResult;
1093
1094 // Try to parse the literal-first syntax, which is the default format for
1095 // int, float, index and complex element types.
1096 TensorLiteralParser literalParser(*this);
1097 if (!consumeIf(Token::greater)) {
1098 if (literalParser.parse(/*allowHex=*/true) ||
1099 parseToken(Token::greater, "expected '>'"))
1100 return nullptr;
1101 }
1102
1103 auto type = parseElementsLiteralType(attribLoc, attrType);
1104 if (!type)
1105 return nullptr;
1106 return literalParser.getAttr(attribLoc, type);
1107}
1108
1110 auto loc = getToken().getLoc();
1111 consumeToken(Token::kw_dense_resource);
1112 if (parseToken(Token::less, "expected '<' after 'dense_resource'"))
1113 return nullptr;
1114
1115 // Parse the resource handle.
1116 FailureOr<AsmDialectResourceHandle> rawHandle =
1117 parseResourceHandle(getContext()->getLoadedDialect<BuiltinDialect>());
1118 if (failed(rawHandle) || parseToken(Token::greater, "expected '>'"))
1119 return nullptr;
1120
1121 auto *handle = dyn_cast<DenseResourceElementsHandle>(&*rawHandle);
1122 if (!handle)
1123 return emitError(loc, "invalid `dense_resource` handle type"), nullptr;
1124
1125 // Parse the type of the attribute if the user didn't provide one.
1126 SMLoc typeLoc = loc;
1127 if (!attrType) {
1128 typeLoc = getToken().getLoc();
1129 if (parseToken(Token::colon, "expected ':'") || !(attrType = parseType()))
1130 return nullptr;
1131 }
1132
1133 ShapedType shapedType = dyn_cast<ShapedType>(attrType);
1134 if (!shapedType) {
1135 emitError(typeLoc, "`dense_resource` expected a shaped type");
1136 return nullptr;
1137 }
1138
1139 return DenseResourceElementsAttr::get(shapedType, *handle);
1140}
1141
1142/// Shaped type for elements attribute.
1143///
1144/// elements-literal-type ::= vector-type | ranked-tensor-type
1145///
1146/// This method also checks the type has static shape.
1147ShapedType Parser::parseElementsLiteralType(SMLoc loc, Type type) {
1148 // If the user didn't provide a type, parse the colon type for the literal.
1149 if (!type) {
1150 if (parseToken(Token::colon, "expected ':'"))
1151 return nullptr;
1152 if (!(type = parseType()))
1153 return nullptr;
1154 }
1155
1156 auto sType = dyn_cast<ShapedType>(type);
1157 if (!sType) {
1158 emitError(loc, "elements literal must be a shaped type");
1159 return nullptr;
1160 }
1161
1162 if (!sType.hasStaticShape()) {
1163 emitError(loc, "elements literal type must have static shape");
1164 return nullptr;
1165 }
1166
1167 return sType;
1168}
1169
1170/// Parse a sparse elements attribute.
1172 SMLoc loc = getToken().getLoc();
1173 consumeToken(Token::kw_sparse);
1174 if (parseToken(Token::less, "Expected '<' after 'sparse'"))
1175 return nullptr;
1176
1177 // Check for the case where all elements are sparse. The indices are
1178 // represented by a 2-dimensional shape where the second dimension is the rank
1179 // of the type.
1180 Type indiceEltType = builder.getIntegerType(64);
1181 if (consumeIf(Token::greater)) {
1182 ShapedType type = parseElementsLiteralType(loc, attrType);
1183 if (!type)
1184 return nullptr;
1185
1186 // Construct the sparse elements attr using zero element indice/value
1187 // attributes.
1188 ShapedType indicesType =
1189 RankedTensorType::get({0, type.getRank()}, indiceEltType);
1190 ShapedType valuesType = RankedTensorType::get({0}, type.getElementType());
1192 loc, type, DenseElementsAttr::get(indicesType, ArrayRef<Attribute>()),
1194 }
1195
1196 /// Parse the indices. We don't allow hex values here as we may need to use
1197 /// the inferred shape.
1198 auto indicesLoc = getToken().getLoc();
1199 TensorLiteralParser indiceParser(*this);
1200 if (indiceParser.parse(/*allowHex=*/false))
1201 return nullptr;
1202
1203 if (parseToken(Token::comma, "expected ','"))
1204 return nullptr;
1205
1206 /// Parse the values.
1207 auto valuesLoc = getToken().getLoc();
1208 TensorLiteralParser valuesParser(*this);
1209 if (valuesParser.parse(/*allowHex=*/true))
1210 return nullptr;
1211
1212 if (parseToken(Token::greater, "expected '>'"))
1213 return nullptr;
1214
1215 auto type = parseElementsLiteralType(loc, attrType);
1216 if (!type)
1217 return nullptr;
1218
1219 // If the indices are a splat, i.e. the literal parser parsed an element and
1220 // not a list, we set the shape explicitly. The indices are represented by a
1221 // 2-dimensional shape where the second dimension is the rank of the type.
1222 // Given that the parsed indices is a splat, we know that we only have one
1223 // indice and thus one for the first dimension.
1224 ShapedType indicesType;
1225 if (indiceParser.getShape().empty()) {
1226 indicesType = RankedTensorType::get({1, type.getRank()}, indiceEltType);
1227 } else {
1228 // Otherwise, set the shape to the one parsed by the literal parser.
1229 indicesType = RankedTensorType::get(indiceParser.getShape(), indiceEltType);
1230 }
1231 auto indices = indiceParser.getAttr(indicesLoc, indicesType);
1232 if (!indices)
1233 return nullptr;
1234
1235 // If the values are a splat, set the shape explicitly based on the number of
1236 // indices. The number of indices is encoded in the first dimension of the
1237 // indice shape type.
1238 auto valuesEltType = type.getElementType();
1239 ShapedType valuesType =
1240 valuesParser.getShape().empty()
1241 ? RankedTensorType::get({indicesType.getDimSize(0)}, valuesEltType)
1242 : RankedTensorType::get(valuesParser.getShape(), valuesEltType);
1243 auto values = valuesParser.getAttr(valuesLoc, valuesType);
1244 if (!values)
1245 return nullptr;
1246
1247 // Build the sparse elements attribute by the indices and values.
1248 return getChecked<SparseElementsAttr>(loc, type, indices, values);
1249}
1250
1252 // Callback for error emissing at the keyword token location.
1253 llvm::SMLoc loc = getToken().getLoc();
1254 auto errorEmitter = [&] { return emitError(loc); };
1255
1256 consumeToken(Token::kw_strided);
1257 if (failed(parseToken(Token::less, "expected '<' after 'strided'")) ||
1258 failed(parseToken(Token::l_square, "expected '['")))
1259 return nullptr;
1260
1261 // Parses either an integer token or a question mark token. Reports an error
1262 // and returns std::nullopt if the current token is neither. The integer token
1263 // must fit into int64_t limits.
1264 auto parseStrideOrOffset = [&]() -> std::optional<int64_t> {
1265 if (consumeIf(Token::question))
1266 return ShapedType::kDynamic;
1267
1268 SMLoc loc = getToken().getLoc();
1269 auto emitWrongTokenError = [&] {
1270 emitError(loc, "expected a 64-bit signed integer or '?'");
1271 return std::nullopt;
1272 };
1273
1274 bool negative = consumeIf(Token::minus);
1275
1276 if (getToken().is(Token::integer)) {
1277 std::optional<uint64_t> value = getToken().getUInt64IntegerValue();
1278 if (!value ||
1279 *value > static_cast<uint64_t>(std::numeric_limits<int64_t>::max()))
1280 return emitWrongTokenError();
1281 consumeToken();
1282 auto result = static_cast<int64_t>(*value);
1283 if (negative)
1284 result = -result;
1285
1286 return result;
1287 }
1288
1289 return emitWrongTokenError();
1290 };
1291
1292 // Parse strides.
1293 SmallVector<int64_t> strides;
1294 if (!getToken().is(Token::r_square)) {
1295 do {
1296 std::optional<int64_t> stride = parseStrideOrOffset();
1297 if (!stride)
1298 return nullptr;
1299 strides.push_back(*stride);
1300 } while (consumeIf(Token::comma));
1301 }
1302
1303 if (failed(parseToken(Token::r_square, "expected ']'")))
1304 return nullptr;
1305
1306 // Fast path in absence of offset.
1307 if (consumeIf(Token::greater)) {
1308 if (failed(StridedLayoutAttr::verify(errorEmitter,
1309 /*offset=*/0, strides)))
1310 return nullptr;
1311 return StridedLayoutAttr::get(getContext(), /*offset=*/0, strides);
1312 }
1313
1314 if (failed(parseToken(Token::comma, "expected ','")) ||
1315 failed(parseToken(Token::kw_offset, "expected 'offset' after comma")) ||
1316 failed(parseToken(Token::colon, "expected ':' after 'offset'")))
1317 return nullptr;
1318
1319 std::optional<int64_t> offset = parseStrideOrOffset();
1320 if (!offset || failed(parseToken(Token::greater, "expected '>'")))
1321 return nullptr;
1322
1323 if (failed(StridedLayoutAttr::verify(errorEmitter, *offset, strides)))
1324 return nullptr;
1325 return StridedLayoutAttr::get(getContext(), *offset, strides);
1326 // return getChecked<StridedLayoutAttr>(loc,getContext(), *offset, strides);
1327}
1328
1329/// Parse a distinct attribute.
1330///
1331/// distinct-attribute ::= `distinct`
1332/// `[` integer-literal `]<` attribute-value `>`
1333///
1335 SMLoc loc = getToken().getLoc();
1336 consumeToken(Token::kw_distinct);
1337 if (parseToken(Token::l_square, "expected '[' after 'distinct'"))
1338 return {};
1339
1340 // Parse the distinct integer identifier.
1341 Token token = getToken();
1342 if (parseToken(Token::integer, "expected distinct ID"))
1343 return {};
1344 std::optional<uint64_t> value = token.getUInt64IntegerValue();
1345 if (!value) {
1346 emitError("expected an unsigned 64-bit integer");
1347 return {};
1348 }
1349
1350 // Parse the referenced attribute.
1351 if (parseToken(Token::r_square, "expected ']' to close distinct ID") ||
1352 parseToken(Token::less, "expected '<' after distinct ID"))
1353 return {};
1354
1355 Attribute referencedAttr;
1356 if (getToken().is(Token::greater)) {
1357 consumeToken();
1358 referencedAttr = builder.getUnitAttr();
1359 } else {
1360 referencedAttr = parseAttribute(type);
1361 if (!referencedAttr) {
1362 emitError("expected attribute");
1363 return {};
1364 }
1365
1366 if (parseToken(Token::greater, "expected '>' to close distinct attribute"))
1367 return {};
1368 }
1369
1370 // Add the distinct attribute to the parser state, if it has not been parsed
1371 // before. Otherwise, check if the parsed reference attribute matches the one
1372 // found in the parser state.
1373 DenseMap<uint64_t, DistinctAttr> &distinctAttrs =
1374 state.symbols.distinctAttributes;
1375 auto it = distinctAttrs.find(*value);
1376 if (it == distinctAttrs.end()) {
1377 DistinctAttr distinctAttr = DistinctAttr::create(referencedAttr);
1378 it = distinctAttrs.try_emplace(*value, distinctAttr).first;
1379 } else if (it->getSecond().getReferencedAttr() != referencedAttr) {
1380 emitError(loc, "referenced attribute does not match previous definition: ")
1381 << it->getSecond().getReferencedAttr();
1382 return {};
1383 }
1384
1385 return it->getSecond();
1386}
return success()
static FailureOr< Attribute > parseDenseElementsAttrTyped(Parser &p, SMLoc loc)
Try to parse a dense elements attribute with the type-first syntax.
static std::optional< APInt > buildAttributeAPInt(Type type, bool isNegative, StringRef spelling)
Construct an APint from a parsed value, a known attribute type and sign.
static ParseResult parseElementAttrHexValues(Parser &parser, Token tok, std::string &result)
Parse elements values stored within a hex string.
static ArrayRef< int64_t > getShape(Type type)
Returns the shape of the given type.
Definition Traits.cpp:117
A multi-dimensional affine map Affine map's are immutable like Type's, and they are uniqued.
Definition AffineMap.h:46
Attributes are known-constant values of operations.
Definition Attributes.h:25
static DenseElementsAttr getFromRawBuffer(ShapedType type, ArrayRef< char > rawBuffer)
Construct a dense elements attribute from a raw buffer representing the data for this attribute.
static bool isValidRawBuffer(ShapedType type, ArrayRef< char > rawBuffer)
Returns true if the given buffer is a valid raw buffer for the given type.
static DenseElementsAttr get(ShapedType type, ArrayRef< Attribute > values)
Constructs a dense elements attribute from an array of element values.
An attribute that associates a referenced attribute with a unique identifier.
static DistinctAttr create(Attribute referencedAttr)
Creates a distinct attribute that associates a referenced attribute with a unique identifier.
An integer set representing a conjunction of one or more affine equalities and inequalities.
Definition IntegerSet.h:44
Location objects represent source locations information in MLIR.
Definition Location.h:32
T * getOrLoadDialect()
Get (or create) a dialect for the given derived dialect type.
NamedAttrList is array of NamedAttributes that tracks whether it is sorted and does some basic work t...
DictionaryAttr getDictionary(MLIRContext *context) const
Return a dictionary attribute for the underlying dictionary.
void push_back(NamedAttribute newAttribute)
Add an attribute with the specified name.
This class implements Optional functionality for ParseResult.
bool has_value() const
Returns true if we contain a valid ParseResult value.
This represents a token in the MLIR syntax.
Definition Token.h:20
SMLoc getLoc() const
Definition Token.cpp:24
bool is(Kind k) const
Definition Token.h:38
std::string getStringValue() const
Given a token containing a string literal, return its value, including removing the quote characters ...
Definition Token.cpp:86
std::string getSymbolReference() const
Given a token containing a symbol reference, return the unescaped string value.
Definition Token.cpp:153
static std::optional< uint64_t > getUInt64IntegerValue(StringRef spelling)
For an integer token, return its value as an uint64_t.
Definition Token.cpp:45
std::optional< double > getFloatingPointValue() const
For a floatliteral token, return its value as a double.
Definition Token.cpp:56
bool isAny(Kind k1, Kind k2) const
Definition Token.h:40
StringRef getSpelling() const
Definition Token.h:34
std::optional< std::string > getHexStringValue() const
Given a token containing a hex string literal, return its value or std::nullopt if the token does not...
Definition Token.cpp:135
Instances of the Type class are uniqued, have an immutable identifier and an optional mutable compone...
Definition Types.h:74
bool isSignedInteger() const
Return true if this is a signed integer type (with the specified width).
Definition Types.cpp:78
bool isIndex() const
Definition Types.cpp:56
bool isIntOrIndexOrFloat() const
Return true if this is an integer (of any signedness), index, or float type.
Definition Types.cpp:122
bool isUnsignedInteger() const
Return true if this is an unsigned integer type (with the specified width).
Definition Types.cpp:90
bool isIntOrIndex() const
Return true if this is an integer (of any signedness) or an index type.
Definition Types.cpp:114
bool isInteger() const
Return true if this is an integer type (with the specified width).
Definition Types.cpp:58
bool isIntOrFloat() const
Return true if this is an integer (of any signedness) or a float type.
Definition Types.cpp:118
unsigned getIntOrFloatBitWidth() const
Return the bit width of an integer or a float type, assert failure on other types.
Definition Types.cpp:124
This class implement support for parsing global entities like attributes and types.
Definition Parser.h:27
ParseResult parseFloatFromLiteral(std::optional< APFloat > &result, const Token &tok, bool isNegative, const llvm::fltSemantics &semantics)
Parse a floating point value from a literal.
Definition Parser.cpp:399
Attribute parseDenseArrayAttr(Type type)
Parse a DenseArrayAttr.
Attribute parseStridedLayoutAttr()
Parse a strided layout attribute.
Attribute parseDecOrHexAttr(Type type, bool isNegative)
Parse a decimal or a hexadecimal literal, which can be either an integer or a float attribute.
T getChecked(SMLoc loc, ParamsT &&...params)
Invoke the getChecked method of the given Attribute or Type class, using the provided location to emi...
Definition Parser.h:198
OptionalParseResult parseOptionalType(Type &type)
Optionally parse a type.
ParseResult parseToken(Token::Kind expectedToken, const Twine &message)
Consume the specified token if present and return success.
Definition Parser.cpp:305
ParseResult parseCommaSeparatedListUntil(Token::Kind rightToken, function_ref< ParseResult()> parseElement, bool allowEmptyList=true)
Parse a comma-separated list of elements up until the specified end token.
Definition Parser.cpp:173
Type parseType()
Parse an arbitrary type.
Attribute parseDenseElementsAttr(Type attrType)
Parse a dense elements attribute.
Attribute parseDenseResourceElementsAttr(Type attrType)
Parse a dense resource elements attribute.
ParseResult parseAffineMapReference(AffineMap &map)
InFlightDiagnostic emitError(const Twine &message={})
Emit an error and return failure.
Definition Parser.cpp:192
ParserState & state
The Parser is subclassed and reinstantiated.
Definition Parser.h:372
Attribute parseAttribute(Type type={})
Parse an arbitrary attribute with an optional type.
StringRef getTokenSpelling() const
Definition Parser.h:104
FailureOr< AsmDialectResourceHandle > parseResourceHandle(const OpAsmDialectInterface *dialect, std::string &name)
Parse a handle to a dialect resource within the assembly format.
Definition Parser.cpp:487
ParseResult parseLocationInstance(LocationAttr &loc)
Parse a raw location instance.
void consumeToken()
Advance the current lexer onto the next token.
Definition Parser.h:119
Attribute codeCompleteAttribute()
Definition Parser.cpp:590
ParseResult parseAttributeDict(NamedAttrList &attributes)
Parse an attribute dictionary.
Attribute parseDistinctAttr(Type type)
Parse a distinct attribute.
InFlightDiagnostic emitWrongTokenError(const Twine &message={})
Emit an error about a "wrong token".
Definition Parser.cpp:254
ParseResult parseCommaSeparatedList(Delimiter delimiter, function_ref< ParseResult()> parseElementFn, StringRef contextMessage=StringRef())
Parse a list of comma-separated items with an optional delimiter.
Definition Parser.cpp:84
Attribute parseSparseElementsAttr(Type attrType)
Parse a sparse elements attribute.
OptionalParseResult parseOptionalAttribute(Attribute &attribute, Type type={})
Parse an optional attribute with the provided type.
Attribute parseFloatAttr(Type type, bool isNegative)
Parse a float attribute.
ParseResult parseFloatFromIntegerLiteral(std::optional< APFloat > &result, const Token &tok, bool isNegative, const llvm::fltSemantics &semantics)
Parse a floating point value from an integer literal token.
Definition Parser.cpp:431
ParseResult parseIntegerSetReference(IntegerSet &set)
const Token & getToken() const
Return the current token the parser is inspecting.
Definition Parser.h:103
Attribute parseExtendedAttr(Type type)
Parse an extended attribute.
MLIRContext * getContext() const
Definition Parser.h:38
ShapedType parseElementsLiteralType(SMLoc loc, Type type)
Shaped type for elements attribute.
bool consumeIf(Token::Kind kind)
If the current token has the specified kind, consume it and return true.
Definition Parser.h:111
OptionalParseResult parseOptionalAttributeWithToken(Token::Kind kind, AttributeT &attr, Type type={})
Parse an optional attribute that is demarcated by a specific token.
Definition Parser.h:260
AttrTypeReplacer.
QueryRef parse(llvm::StringRef line, const QuerySession &qs)
Definition Query.cpp:21
detail::InFlightRemark failed(Location loc, RemarkOpts opts)
Report an optimization remark that failed.
Definition Remarks.h:717
Include the generated interface declarations.
std::conditional_t< std::is_floating_point_v< T >, std::complex< T >, NonFloatComplex< T > > Complex
Definition Complex.h:265
llvm::DenseMap< KeyT, ValueT, KeyInfoT, BucketT > DenseMap
Definition LLVM.h:120