CIRCT 24.0.0git
Loading...
Searching...
No Matches
FIRParser.cpp
Go to the documentation of this file.
1//===- FIRParser.cpp - .fir to FIRRTL dialect parser ----------------------===//
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 implements a .fir file parser.
10//
11//===----------------------------------------------------------------------===//
12
14#include "FIRLexer.h"
24#include "circt/Support/LLVM.h"
25#include "mlir/IR/BuiltinOps.h"
26#include "mlir/IR/BuiltinTypes.h"
27#include "mlir/IR/Diagnostics.h"
28#include "mlir/IR/ImplicitLocOpBuilder.h"
29#include "mlir/IR/PatternMatch.h"
30#include "mlir/IR/Threading.h"
31#include "mlir/IR/Verifier.h"
32#include "mlir/Support/Timing.h"
33#include "mlir/Tools/mlir-translate/Translation.h"
34#include "llvm/ADT/PointerEmbeddedInt.h"
35#include "llvm/ADT/STLExtras.h"
36#include "llvm/ADT/SmallPtrSet.h"
37#include "llvm/ADT/StringExtras.h"
38#include "llvm/ADT/StringSet.h"
39#include "llvm/ADT/StringSwitch.h"
40#include "llvm/ADT/TypeSwitch.h"
41#include "llvm/Support/JSON.h"
42#include "llvm/Support/LogicalResult.h"
43#include "llvm/Support/SourceMgr.h"
44#include "llvm/Support/raw_ostream.h"
45#include <memory>
46#include <utility>
47
48using namespace circt;
49using namespace firrtl;
50using namespace chirrtl;
51
52using llvm::SMLoc;
53using llvm::SourceMgr;
54using mlir::LocationAttr;
55
56namespace json = llvm::json;
57
58//===----------------------------------------------------------------------===//
59// SharedParserConstants
60//===----------------------------------------------------------------------===//
61
62namespace {
63
64/// This class refers to immutable values and annotations maintained globally by
65/// the parser which can be referred to by any active parser, even those running
66/// in parallel. This is shared by all active parsers.
67struct SharedParserConstants {
68 SharedParserConstants(MLIRContext *context, FIRParserOptions options)
69 : context(context), options(options),
70 emptyArrayAttr(ArrayAttr::get(context, {})),
71 loIdentifier(StringAttr::get(context, "lo")),
72 hiIdentifier(StringAttr::get(context, "hi")),
73 amountIdentifier(StringAttr::get(context, "amount")),
74 placeholderInnerRef(
75 hw::InnerRefAttr::get(StringAttr::get(context, "module"),
76 StringAttr::get(context, "placeholder"))) {}
77
78 /// The context we're parsing into.
79 MLIRContext *const context;
80
81 // Options that control the behavior of the parser.
82 const FIRParserOptions options;
83
84 /// A map from identifiers to type aliases.
85 llvm::StringMap<FIRRTLType> aliasMap;
86
87 /// A map from identifiers to class ops.
88 llvm::DenseMap<StringRef, ClassLike> classMap;
89
90 /// A map from identifiers to domain ops.
91 llvm::DenseMap<StringRef, DomainOp> domainMap;
92
93 /// An empty array attribute.
94 const ArrayAttr emptyArrayAttr;
95
96 /// Cached identifiers used in primitives.
97 const StringAttr loIdentifier, hiIdentifier, amountIdentifier;
98
99 /// Cached placeholder inner-ref used until fixed up.
100 const hw::InnerRefAttr placeholderInnerRef;
101
102private:
103 SharedParserConstants(const SharedParserConstants &) = delete;
104 void operator=(const SharedParserConstants &) = delete;
105};
106
107} // end anonymous namespace
108
109//===----------------------------------------------------------------------===//
110// FIRParser
111//===----------------------------------------------------------------------===//
112
113namespace {
114/// This class implements logic common to all levels of the parser, including
115/// things like types and helper logic.
116struct FIRParser {
117 FIRParser(SharedParserConstants &constants, FIRLexer &lexer,
118 FIRVersion version)
119 : version(version), constants(constants), lexer(lexer),
120 locatorFilenameCache(constants.loIdentifier /*arbitrary non-null id*/) {
121 }
122
123 // Helper methods to get stuff from the shared parser constants.
124 SharedParserConstants &getConstants() const { return constants; }
125 MLIRContext *getContext() const { return constants.context; }
126
127 FIRLexer &getLexer() { return lexer; }
128
129 /// Return the indentation level of the specified token.
130 std::optional<unsigned> getIndentation() const {
131 return lexer.getIndentation(getToken());
132 }
133
134 /// Return the current token the parser is inspecting.
135 const FIRToken &getToken() const { return lexer.getToken(); }
136 StringRef getTokenSpelling() const { return getToken().getSpelling(); }
137
138 //===--------------------------------------------------------------------===//
139 // Error Handling
140 //===--------------------------------------------------------------------===//
141
142 /// Emit an error and return failure.
143 InFlightDiagnostic emitError(const Twine &message = {}) {
144 return emitError(getToken().getLoc(), message);
145 }
146 InFlightDiagnostic emitError(SMLoc loc, const Twine &message = {});
147
148 /// Emit a warning.
149 InFlightDiagnostic emitWarning(const Twine &message = {}) {
150 return emitWarning(getToken().getLoc(), message);
151 }
152
153 InFlightDiagnostic emitWarning(SMLoc loc, const Twine &message = {});
154
155 //===--------------------------------------------------------------------===//
156 // Location Handling
157 //===--------------------------------------------------------------------===//
158
159 class LocWithInfo;
160
161 /// Encode the specified source location information into an attribute for
162 /// attachment to the IR.
163 Location translateLocation(llvm::SMLoc loc) {
164 return lexer.translateLocation(loc);
165 }
166
167 /// Parse an @info marker if present. If so, fill in the specified Location,
168 /// if not, ignore it.
169 ParseResult parseOptionalInfoLocator(LocationAttr &result);
170
171 /// Parse an optional name that may appear in Stop, Printf, or Verification
172 /// statements.
173 ParseResult parseOptionalName(StringAttr &name);
174
175 //===--------------------------------------------------------------------===//
176 // Version and Feature Checking
177 //===--------------------------------------------------------------------===//
178
179 ParseResult requireFeature(FIRVersion minimum, StringRef feature) {
180 return requireFeature(minimum, feature, getToken().getLoc());
181 }
182
183 ParseResult requireFeature(FIRVersion minimum, StringRef feature, SMLoc loc) {
184 if (version < minimum)
185 return emitError(loc)
186 << feature << " are a FIRRTL " << minimum
187 << "+ feature, but the specified FIRRTL version was " << version;
188 return success();
189 }
190
191 ParseResult removedFeature(FIRVersion removedVersion, StringRef feature) {
192 return removedFeature(removedVersion, feature, getToken().getLoc());
193 }
194
195 ParseResult removedFeature(FIRVersion removedVersion, StringRef feature,
196 SMLoc loc) {
197 if (version >= removedVersion)
198 return emitError(loc)
199 << feature << " were removed in FIRRTL " << removedVersion
200 << ", but the specified FIRRTL version was " << version;
201 return success();
202 }
203
204 //===--------------------------------------------------------------------===//
205 // Annotation Parsing
206 //===--------------------------------------------------------------------===//
207
208 /// Parse a non-standard inline Annotation JSON blob if present. This uses
209 /// the info-like encoding of %[<JSON Blob>].
210 ParseResult parseOptionalAnnotations(SMLoc &loc, StringRef &result);
211
212 //===--------------------------------------------------------------------===//
213 // Token Parsing
214 //===--------------------------------------------------------------------===//
215
216 /// If the current token has the specified kind, consume it and return true.
217 /// If not, return false.
218 bool consumeIf(FIRToken::Kind kind) {
219 if (getToken().isNot(kind))
220 return false;
221 consumeToken(kind);
222 return true;
223 }
224
225 /// Advance the current lexer onto the next token.
226 ///
227 /// This returns the consumed token.
228 FIRToken consumeToken() {
229 FIRToken consumedToken = getToken();
230 assert(consumedToken.isNot(FIRToken::eof, FIRToken::error) &&
231 "shouldn't advance past EOF or errors");
232 lexer.lexToken();
233 return consumedToken;
234 }
235
236 /// Advance the current lexer onto the next token, asserting what the expected
237 /// current token is. This is preferred to the above method because it leads
238 /// to more self-documenting code with better checking.
239 ///
240 /// This returns the consumed token.
241 FIRToken consumeToken(FIRToken::Kind kind) {
242 FIRToken consumedToken = getToken();
243 assert(consumedToken.is(kind) && "consumed an unexpected token");
244 consumeToken();
245 return consumedToken;
246 }
247
248 /// Capture the current token's spelling into the specified value. This
249 /// always succeeds.
250 ParseResult parseGetSpelling(StringRef &spelling) {
251 spelling = getTokenSpelling();
252 return success();
253 }
254
255 /// Consume the specified token if present and return success. On failure,
256 /// output a diagnostic and return failure.
257 ParseResult parseToken(FIRToken::Kind expectedToken, const Twine &message);
258
259 /// Parse a comma-separated list of elements, terminated with an arbitrary
260 /// token.
261 ParseResult parseListUntil(FIRToken::Kind rightToken,
262 const std::function<ParseResult()> &parseElement);
263
264 //===--------------------------------------------------------------------===//
265 // Common Parser Rules
266 //===--------------------------------------------------------------------===//
267
268 /// Parse 'intLit' into the specified value.
269 ParseResult parseIntLit(APInt &result, const Twine &message);
270 ParseResult parseIntLit(int64_t &result, const Twine &message);
271 ParseResult parseIntLit(int32_t &result, const Twine &message);
272
273 // Parse 'verLit' into specified value
274 ParseResult parseVersionLit(const Twine &message);
275
276 // Parse 'intLit' '>' assuming '<' was already consumed.
277 ParseResult parseWidth(int32_t &result);
278
279 // Parse the 'id' grammar, which is an identifier or an allowed keyword.
280 ParseResult parseId(StringRef &result, const Twine &message);
281 ParseResult parseId(StringAttr &result, const Twine &message);
282 ParseResult parseFieldId(StringRef &result, const Twine &message);
283 ParseResult parseFieldIdSeq(SmallVectorImpl<StringRef> &result,
284 const Twine &message);
285 ParseResult parseEnumType(FIRRTLType &result);
286 ParseResult parseListType(FIRRTLType &result);
287 ParseResult parseOptionType(FIRRTLType &result);
288 ParseResult parseRegistryType(FIRRTLType &result);
289 ParseResult parseType(FIRRTLType &result, const Twine &message);
290 // Parse a property type specifically.
291 ParseResult parsePropertyType(PropertyType &result, const Twine &message);
292
293 ParseResult parseRUW(RUWBehavior &result);
294 ParseResult parseOptionalRUW(RUWBehavior &result);
295
296 ParseResult parseParameter(StringAttr &resultName, Attribute &resultValue,
297 SMLoc &resultLoc, bool allowAggregates = false);
298 ParseResult parseParameterValue(Attribute &resultValue,
299 bool allowAggregates = false);
300
301 /// The version of FIRRTL to use for this parser.
302 FIRVersion version;
303
304private:
305 FIRParser(const FIRParser &) = delete;
306 void operator=(const FIRParser &) = delete;
307
308 /// FIRParser is subclassed and reinstantiated. Do not add additional
309 /// non-trivial state here, add it to SharedParserConstants.
310 SharedParserConstants &constants;
311 FIRLexer &lexer;
312
313 /// This is a single-entry cache for filenames in locators.
314 StringAttr locatorFilenameCache;
315 /// This is a single-entry cache for FileLineCol locations.
316 FileLineColLoc fileLineColLocCache;
317};
318
319} // end anonymous namespace
320
321//===----------------------------------------------------------------------===//
322// Error Handling
323//===----------------------------------------------------------------------===//
324
325InFlightDiagnostic FIRParser::emitError(SMLoc loc, const Twine &message) {
326 auto diag = mlir::emitError(translateLocation(loc), message);
327
328 // If we hit a parse error in response to a lexer error, then the lexer
329 // already reported the error.
330 if (getToken().is(FIRToken::error))
331 diag.abandon();
332 return diag;
333}
334
335InFlightDiagnostic FIRParser::emitWarning(SMLoc loc, const Twine &message) {
336 return mlir::emitWarning(translateLocation(loc), message);
337}
338
339//===----------------------------------------------------------------------===//
340// Token Parsing
341//===----------------------------------------------------------------------===//
342
343/// Consume the specified token if present and return success. On failure,
344/// output a diagnostic and return failure.
345ParseResult FIRParser::parseToken(FIRToken::Kind expectedToken,
346 const Twine &message) {
347 if (consumeIf(expectedToken))
348 return success();
349 return emitError(message);
350}
351
352/// Parse a comma-separated list of zero or more elements, terminated with an
353/// arbitrary token.
354ParseResult
355FIRParser::parseListUntil(FIRToken::Kind rightToken,
356 const std::function<ParseResult()> &parseElement) {
357 if (consumeIf(rightToken))
358 return success();
359
360 if (parseElement())
361 return failure();
362
363 while (consumeIf(FIRToken::comma)) {
364 if (parseElement())
365 return failure();
366 }
367
368 if (parseToken(rightToken, "expected ','"))
369 return failure();
370
371 return success();
372}
373
374//===--------------------------------------------------------------------===//
375// Location Processing
376//===--------------------------------------------------------------------===//
377
378/// This helper class is used to handle Info records, which specify higher level
379/// symbolic source location, that may be missing from the file. If the higher
380/// level source information is missing, we fall back to the location in the
381/// .fir file.
383public:
384 explicit LocWithInfo(SMLoc firLoc, FIRParser *parser)
385 : parser(parser), firLoc(firLoc) {}
386
387 SMLoc getFIRLoc() const { return firLoc; }
388
389 Location getLoc() {
390 if (infoLoc)
391 return *infoLoc;
392 auto result = parser->translateLocation(firLoc);
393 infoLoc = result;
394 return result;
395 }
396
397 /// Parse an @info marker if present and update our location.
398 ParseResult parseOptionalInfo() {
399 LocationAttr loc;
400 if (failed(parser->parseOptionalInfoLocator(loc)))
401 return failure();
402 if (loc) {
404 switch (parser->constants.options.infoLocatorHandling) {
405 case ILH::IgnoreInfo:
406 assert(0 && "Should not return info locations if ignoring");
407 break;
408 case ILH::PreferInfo:
409 infoLoc = loc;
410 break;
411 case ILH::FusedInfo:
412 infoLoc = FusedLoc::get(loc.getContext(),
413 {loc, parser->translateLocation(firLoc)});
414 break;
415 }
416 }
417 return success();
418 }
419
420 /// If we didn't parse an info locator for the specified value, this sets a
421 /// default, overriding a fall back to a location in the .fir file.
422 void setDefaultLoc(Location loc) {
423 if (!infoLoc)
424 infoLoc = loc;
425 }
426
427private:
428 FIRParser *const parser;
429
430 /// This is the designated location in the .fir file for use when there is no
431 /// @ info marker.
432 SMLoc firLoc;
433
434 /// This is the location specified by the @ marker if present.
435 std::optional<Location> infoLoc;
436};
437
438/// Parse an @info marker if present. If so, fill in the specified Location,
439/// if not, ignore it.
440ParseResult FIRParser::parseOptionalInfoLocator(LocationAttr &result) {
441 if (getToken().isNot(FIRToken::fileinfo))
442 return success();
443
444 auto loc = getToken().getLoc();
445
446 auto spelling = getTokenSpelling();
447 consumeToken(FIRToken::fileinfo);
448
449 auto locationPair = maybeStringToLocation(
450 spelling,
451 constants.options.infoLocatorHandling ==
453 locatorFilenameCache, fileLineColLocCache, getContext());
454
455 // If parsing failed, then indicate that a weird info was found.
456 if (!locationPair.first) {
457 mlir::emitWarning(translateLocation(loc),
458 "ignoring unknown @ info record format");
459 return success();
460 }
461
462 // If the parsing succeeded, but we are supposed to drop locators, then just
463 // return.
464 if (locationPair.first && constants.options.infoLocatorHandling ==
465 FIRParserOptions::InfoLocHandling::IgnoreInfo)
466 return success();
467
468 // Otherwise, set the location attribute and return.
469 result = *locationPair.second;
470 return success();
471}
472
473/// Parse an optional trailing name that may show up on assert, assume, cover,
474/// stop, or printf.
475///
476/// optional_name ::= ( ':' id )?
477ParseResult FIRParser::parseOptionalName(StringAttr &name) {
478
479 if (getToken().isNot(FIRToken::colon)) {
480 name = StringAttr::get(getContext(), "");
481 return success();
482 }
483
484 consumeToken(FIRToken::colon);
485 StringRef nameRef;
486 if (parseId(nameRef, "expected result name"))
487 return failure();
488
489 name = StringAttr::get(getContext(), nameRef);
490
491 return success();
492}
493
494//===--------------------------------------------------------------------===//
495// Annotation Handling
496//===--------------------------------------------------------------------===//
497
498/// Parse a non-standard inline Annotation JSON blob if present. This uses
499/// the info-like encoding of %[<JSON Blob>].
500ParseResult FIRParser::parseOptionalAnnotations(SMLoc &loc, StringRef &result) {
501
502 if (getToken().isNot(FIRToken::inlineannotation))
503 return success();
504
505 loc = getToken().getLoc();
506
507 result = getTokenSpelling().drop_front(2).drop_back(1);
508 consumeToken(FIRToken::inlineannotation);
509
510 return success();
511}
512
513//===--------------------------------------------------------------------===//
514// Common Parser Rules
515//===--------------------------------------------------------------------===//
516
517/// intLit ::= UnsignedInt
518/// ::= SignedInt
519/// ::= HexLit
520/// ::= OctalLit
521/// ::= BinaryLit
522/// HexLit ::= '"' 'h' ( '+' | '-' )? ( HexDigit )+ '"'
523/// OctalLit ::= '"' 'o' ( '+' | '-' )? ( OctalDigit )+ '"'
524/// BinaryLit ::= '"' 'b' ( '+' | '-' )? ( BinaryDigit )+ '"'
525///
526ParseResult FIRParser::parseIntLit(APInt &result, const Twine &message) {
527 auto spelling = getTokenSpelling();
528 bool isNegative = false;
529 switch (getToken().getKind()) {
530 case FIRToken::signed_integer:
531 isNegative = spelling[0] == '-';
532 assert(spelling[0] == '+' || spelling[0] == '-');
533 spelling = spelling.drop_front();
534 [[fallthrough]];
535 case FIRToken::integer:
536 if (spelling.getAsInteger(10, result))
537 return emitError(message), failure();
538
539 // Make sure that the returned APInt has a zero at the top so clients don't
540 // confuse it with a negative number.
541 if (result.isNegative())
542 result = result.zext(result.getBitWidth() + 1);
543
544 if (isNegative)
545 result = -result;
546
547 // If this was parsed as >32 bits, but can be represented in 32 bits,
548 // truncate off the extra width. This is important for extmodules which
549 // like parameters to be 32-bits, and insulates us from some arbitraryness
550 // in StringRef::getAsInteger.
551 if (result.getBitWidth() > 32 && result.getSignificantBits() <= 32)
552 result = result.trunc(32);
553
554 consumeToken();
555 return success();
556 case FIRToken::radix_specified_integer: {
557 if (requireFeature({2, 4, 0}, "radix-specified integer literals"))
558 return failure();
559 if (spelling[0] == '-') {
560 isNegative = true;
561 spelling = spelling.drop_front();
562 }
563 unsigned base = llvm::StringSwitch<unsigned>(spelling.take_front(2))
564 .Case("0b", 2)
565 .Case("0o", 8)
566 .Case("0d", 10)
567 .Case("0h", 16);
568 spelling = spelling.drop_front(2);
569 if (spelling.getAsInteger(base, result))
570 return emitError("invalid character in integer literal"), failure();
571 if (result.isNegative())
572 result = result.zext(result.getBitWidth() + 1);
573 if (isNegative)
574 result = -result;
575 consumeToken();
576 return success();
577 }
578 case FIRToken::string: {
579 if (FIRVersion(3, 0, 0) <= version)
580 return emitError(
581 "String-encoded integer literals are unsupported after FIRRTL 3.0.0");
582
583 // Drop the quotes.
584 assert(spelling.front() == '"' && spelling.back() == '"');
585 spelling = spelling.drop_back().drop_front();
586
587 // Decode the base.
588 unsigned base;
589 switch (spelling.empty() ? ' ' : spelling.front()) {
590 case 'h':
591 base = 16;
592 break;
593 case 'o':
594 base = 8;
595 break;
596 case 'b':
597 base = 2;
598 break;
599 default:
600 return emitError("expected base specifier (h/o/b) in integer literal"),
601 failure();
602 }
603 spelling = spelling.drop_front();
604
605 // Handle the optional sign.
606 bool isNegative = false;
607 if (!spelling.empty() && spelling.front() == '+')
608 spelling = spelling.drop_front();
609 else if (!spelling.empty() && spelling.front() == '-') {
610 isNegative = true;
611 spelling = spelling.drop_front();
612 }
613
614 // Parse the digits.
615 if (spelling.empty())
616 return emitError("expected digits in integer literal"), failure();
617
618 if (spelling.getAsInteger(base, result))
619 return emitError("invalid character in integer literal"), failure();
620
621 // We just parsed the positive version of this number. Make sure it has
622 // a zero at the top so clients don't confuse it with a negative number and
623 // so the negation (in the case of a negative sign) doesn't overflow.
624 if (result.isNegative())
625 result = result.zext(result.getBitWidth() + 1);
626
627 if (isNegative)
628 result = -result;
629
630 consumeToken(FIRToken::string);
631 return success();
632 }
633
634 default:
635 return emitError("expected integer literal"), failure();
636 }
637}
638
639ParseResult FIRParser::parseIntLit(int64_t &result, const Twine &message) {
640 APInt value;
641 auto loc = getToken().getLoc();
642 if (parseIntLit(value, message))
643 return failure();
644
645 result = (int64_t)value.getLimitedValue(INT64_MAX);
646 if (result != value)
647 return emitError(loc, "value is too big to handle"), failure();
648 return success();
649}
650
651ParseResult FIRParser::parseIntLit(int32_t &result, const Twine &message) {
652 APInt value;
653 auto loc = getToken().getLoc();
654 if (parseIntLit(value, message))
655 return failure();
656
657 result = (int32_t)value.getLimitedValue(INT32_MAX);
658 if (result != value)
659 return emitError(loc, "value is too big to handle"), failure();
660 return success();
661}
662
663/// versionLit ::= version
664/// deconstruct a version literal into parts and returns those.
665ParseResult FIRParser::parseVersionLit(const Twine &message) {
666 auto spelling = getTokenSpelling();
667 if (getToken().getKind() != FIRToken::version)
668 return emitError(message), failure();
669 auto ver = FIRVersion::fromString(spelling);
670 if (!ver)
671 return emitError("failed to parse version string"), failure();
672 version = *ver;
673 if (version < minimumFIRVersion)
674 return emitError() << "FIRRTL version must be >=" << minimumFIRVersion,
675 failure();
676 consumeToken(FIRToken::version);
677 return success();
678}
679
680/// Parse a width specifier: intLit '>'
681/// This is used when the '<' has already been consumed.
682ParseResult FIRParser::parseWidth(int32_t &result) {
683 auto widthLoc = getToken().getLoc();
684 if (parseIntLit(result, "expected width") ||
685 parseToken(FIRToken::greater, "expected '>'"))
686 return failure();
687 if (result < 0)
688 return emitError(widthLoc, "invalid width specifier"), failure();
689 return success();
690}
691
692/// id ::= Id | keywordAsId
693///
694/// Parse the 'id' grammar, which is an identifier or an allowed keyword. On
695/// success, this returns the identifier in the result attribute.
696ParseResult FIRParser::parseId(StringRef &result, const Twine &message) {
697 switch (getToken().getKind()) {
698 // The most common case is an identifier.
699 case FIRToken::identifier:
700 case FIRToken::literal_identifier:
701// Otherwise it may be a keyword that we're allowing in an id position.
702#define TOK_KEYWORD(spelling) case FIRToken::kw_##spelling:
703#include "FIRTokenKinds.def"
704
705 // Yep, this is a valid identifier or literal identifier. Turn it into an
706 // attribute. If it is a literal identifier, then drop the leading and
707 // trailing '`' (backticks).
708 if (getToken().getKind() == FIRToken::literal_identifier)
709 result = getTokenSpelling().drop_front().drop_back();
710 else
711 result = getTokenSpelling();
712 consumeToken();
713 return success();
714
715 default:
716 emitError(message);
717 return failure();
718 }
719}
720
721ParseResult FIRParser::parseId(StringAttr &result, const Twine &message) {
722 StringRef name;
723 if (parseId(name, message))
724 return failure();
725
726 result = StringAttr::get(getContext(), name);
727 return success();
728}
729
730/// fieldId ::= Id
731/// ::= RelaxedId
732/// ::= UnsignedInt
733/// ::= keywordAsId
734///
735ParseResult FIRParser::parseFieldId(StringRef &result, const Twine &message) {
736 // Handle the UnsignedInt case.
737 result = getTokenSpelling();
738 if (consumeIf(FIRToken::integer))
739 return success();
740
741 // FIXME: Handle RelaxedId
742
743 // Otherwise, it must be Id or keywordAsId.
744 if (parseId(result, message))
745 return failure();
746
747 return success();
748}
749
750/// fieldId ::= Id
751/// ::= Float
752/// ::= version
753/// ::= UnsignedInt
754/// ::= keywordAsId
755///
756ParseResult FIRParser::parseFieldIdSeq(SmallVectorImpl<StringRef> &result,
757 const Twine &message) {
758 // Handle the UnsignedInt case.
759 StringRef tmp = getTokenSpelling();
760
761 if (consumeIf(FIRToken::integer)) {
762 result.push_back(tmp);
763 return success();
764 }
765
766 if (consumeIf(FIRToken::floatingpoint)) {
767 // form a.b
768 // Both a and b could have more floating point stuff, but just ignore that
769 // for now.
770 auto [a, b] = tmp.split(".");
771 result.push_back(a);
772 result.push_back(b);
773 return success();
774 }
775
776 if (consumeIf(FIRToken::version)) {
777 // form a.b.c
778 auto [a, d] = tmp.split(".");
779 auto [b, c] = d.split(".");
780 result.push_back(a);
781 result.push_back(b);
782 result.push_back(c);
783 return success();
784 }
785
786 // Otherwise, it must be Id or keywordAsId.
787 if (parseId(tmp, message))
788 return failure();
789 result.push_back(tmp);
790 return success();
791}
792
793/// enum-field ::= Id ( '=' int )? ( ':' type )? ;
794/// enum-type ::= '{|' enum-field* '|}'
795ParseResult FIRParser::parseEnumType(FIRRTLType &result) {
796 if (parseToken(FIRToken::l_brace_bar,
797 "expected leading '{|' in enumeration type"))
798 return failure();
799 SmallVector<StringAttr> names;
800 SmallVector<APInt> values;
801 SmallVector<FIRRTLBaseType> types;
802 SmallVector<SMLoc> locs;
803 if (parseListUntil(FIRToken::r_brace_bar, [&]() -> ParseResult {
804 auto fieldLoc = getToken().getLoc();
805 locs.push_back(fieldLoc);
806
807 // Parse the name of the tag.
808 StringRef nameStr;
809 if (parseId(nameStr, "expected valid identifier for enumeration tag"))
810 return failure();
811 auto name = StringAttr::get(getContext(), nameStr);
812 names.push_back(name);
813
814 // Parse the integer value if it exists. If its the first element of the
815 // enum, it implicitly has a value of 0, otherwise it has the previous
816 // value + 1.
817 APInt value;
818 if (consumeIf(FIRToken::equal)) {
819 if (parseIntLit(value, "expected integer value for enumeration tag"))
820 return failure();
821 if (value.isNegative())
822 return emitError(fieldLoc, "enum tag value must be non-negative");
823 } else if (values.empty()) {
824 // This is the first enum variant, so it defaults to 0.
825 value = APInt(1, 0);
826 } else {
827 // This value is not specified, so it defaults to the previous value
828 // + 1.
829 auto &prev = values.back();
830 if (prev.isMaxValue())
831 value = prev.zext(prev.getBitWidth() + 1);
832 else
833 value = prev;
834 ++value;
835 }
836 values.push_back(std::move(value));
837
838 // Parse an optional type ascription.
839 FIRRTLBaseType type;
840 if (consumeIf(FIRToken::colon)) {
841 FIRRTLType parsedType;
842 if (parseType(parsedType, "expected enumeration type"))
843 return failure();
844 type = type_dyn_cast<FIRRTLBaseType>(parsedType);
845 if (!type)
846 return emitError(fieldLoc, "field must be a base type");
847 } else {
848 // If there is no type specified, default to UInt<0>.
849 type = UIntType::get(getContext(), 0);
850 }
851 types.push_back(type);
852
853 auto r = type.getRecursiveTypeProperties();
854 if (!r.isPassive)
855 return emitError(fieldLoc) << "enum field " << name << " not passive";
856 if (r.containsAnalog)
857 return emitError(fieldLoc)
858 << "enum field " << name << " contains analog";
859 if (r.hasUninferredWidth)
860 return emitError(fieldLoc)
861 << "enum field " << name << " has uninferred width";
862 if (r.hasUninferredReset)
863 return emitError(fieldLoc)
864 << "enum field " << name << " has uninferred reset";
865 return success();
866 }))
867 return failure();
868
869 // Verify that the names of each variant are unique.
870 SmallPtrSet<StringAttr, 4> nameSet;
871 for (auto [name, loc] : llvm::zip(names, locs))
872 if (!nameSet.insert(name).second)
873 return emitError(loc,
874 "duplicate variant name in enum: " + name.getValue());
875
876 // Find the bitwidth of the enum.
877 unsigned bitwidth = 0;
878 for (auto &value : values)
879 bitwidth = std::max(bitwidth, value.getActiveBits());
880 auto tagType =
881 IntegerType::get(getContext(), bitwidth, IntegerType::Unsigned);
882
883 // Extend all tag values to the same width, and check that they are all
884 // unique.
885 SmallPtrSet<IntegerAttr, 4> valueSet;
886 SmallVector<FEnumType::EnumElement, 4> elements;
887 for (auto [name, value, type, loc] : llvm::zip(names, values, types, locs)) {
888 auto tagValue = value.zextOrTrunc(bitwidth);
889 auto attr = IntegerAttr::get(tagType, tagValue);
890 // Verify that the names of each variant are unique.
891 if (!valueSet.insert(attr).second)
892 return emitError(loc, "duplicate variant value in enum: ") << attr;
893 elements.push_back({name, attr, type});
894 }
895
896 llvm::sort(elements);
897 result = FEnumType::get(getContext(), elements);
898 return success();
899}
900
901ParseResult FIRParser::parsePropertyType(PropertyType &result,
902 const Twine &message) {
903 auto loc = getToken().getLoc();
904
905 FIRRTLType type;
906 if (parseType(type, message))
907 return failure();
908 auto prop = type_dyn_cast<PropertyType>(type);
909 if (!prop)
910 return emitError(loc, "expected property type");
911 result = prop;
912 return success();
913}
914
915/// list-type ::= 'List' '<' type '>'
916ParseResult FIRParser::parseListType(FIRRTLType &result) {
917 consumeToken(FIRToken::kw_List);
918
919 PropertyType elementType;
920 if (parseToken(FIRToken::less, "expected '<' in List type") ||
921 parsePropertyType(elementType, "expected List element type") ||
922 parseToken(FIRToken::greater, "expected '>' in List type"))
923 return failure();
924
925 result = ListType::get(getContext(), elementType);
926 return success();
927}
928
929/// option-type ::= 'Option' '<' type-property '>'
930// NOLINTNEXTLINE(misc-no-recursion)
931ParseResult FIRParser::parseOptionType(FIRRTLType &result) {
932 bool hasLAngle = getToken().is(FIRToken::langle_Option);
933 consumeToken();
934
935 PropertyType elementType;
936 if ((!hasLAngle &&
937 parseToken(FIRToken::less, "expected '<' in Option type")) ||
938 parsePropertyType(elementType, "expected Option element type") ||
939 parseToken(FIRToken::greater, "expected '>' in Option type"))
940 return failure();
941
942 result = OptionType::get(getContext(), elementType);
943 return success();
944}
945
946/// registry-type ::= 'Registry' '<' type '>'
947ParseResult FIRParser::parseRegistryType(FIRRTLType &result) {
948 consumeToken(FIRToken::kw_Registry);
949
950 PropertyType elementType;
951 if (parseToken(FIRToken::less, "expected '<' in Registry type") ||
952 parsePropertyType(elementType, "expected Registry element type") ||
953 parseToken(FIRToken::greater, "expected '>' in Registry type"))
954 return failure();
955
956 result = RegistryType::get(getContext(), elementType);
957 return success();
958}
959
960/// type ::= 'Clock'
961/// ::= 'Reset'
962/// ::= 'AsyncReset'
963/// ::= 'UInt' optional-width
964/// ::= 'SInt' optional-width
965/// ::= 'Analog' optional-width
966/// ::= 'Domain'
967/// ::= {' field* '}'
968/// ::= type '[' intLit ']'
969/// ::= 'Probe' '<' type '>'
970/// ::= 'RWProbe' '<' type '>'
971/// ::= 'const' type
972/// ::= 'String'
973/// ::= list-type
974/// ::= registry-type
975/// ::= id
976///
977/// field: 'flip'? fieldId ':' type
978///
979// NOLINTNEXTLINE(misc-no-recursion)
980ParseResult FIRParser::parseType(FIRRTLType &result, const Twine &message) {
981 auto typeLoc = getToken().getLoc();
982 switch (getToken().getKind()) {
983 default:
984 return emitError(message), failure();
985
986 case FIRToken::kw_Clock:
987 consumeToken(FIRToken::kw_Clock);
988 result = ClockType::get(getContext());
989 break;
990
991 case FIRToken::kw_Inst: {
992 if (requireFeature({6, 0, 0}, "Inst types"))
993 return failure();
994
995 consumeToken(FIRToken::kw_Inst);
996 if (parseToken(FIRToken::less, "expected < in Inst type"))
997 return failure();
998
999 auto loc = getToken().getLoc();
1000 StringRef id;
1001 if (parseId(id, "expected class name in Inst type"))
1002 return failure();
1003
1004 // Look up the class that is being referenced.
1005 const auto &classMap = getConstants().classMap;
1006 auto lookup = classMap.find(id);
1007 if (lookup == classMap.end())
1008 return emitError(loc) << "unknown class '" << id << "'";
1009
1010 auto classOp = lookup->second;
1011
1012 if (parseToken(FIRToken::greater, "expected > in Inst type"))
1013 return failure();
1014
1015 result = classOp.getInstanceType();
1016 break;
1017 }
1018
1019 case FIRToken::kw_AnyRef: {
1020 if (requireFeature({6, 0, 0}, "AnyRef types"))
1021 return failure();
1022
1023 consumeToken(FIRToken::kw_AnyRef);
1024 result = AnyRefType::get(getContext());
1025 break;
1026 }
1027
1028 case FIRToken::kw_Reset:
1029 consumeToken(FIRToken::kw_Reset);
1030 result = ResetType::get(getContext());
1031 break;
1032
1033 case FIRToken::kw_AsyncReset:
1034 consumeToken(FIRToken::kw_AsyncReset);
1035 result = AsyncResetType::get(getContext());
1036 break;
1037
1038 case FIRToken::kw_UInt:
1039 consumeToken(FIRToken::kw_UInt);
1040 // Width is not present since langle_UInt would have been lexed instead.
1041 result = UIntType::get(getContext(), -1);
1042 break;
1043
1044 case FIRToken::kw_SInt:
1045 consumeToken(FIRToken::kw_SInt);
1046 // Width is not present since langle_SInt would have been lexed instead.
1047 result = SIntType::get(getContext(), -1);
1048 break;
1049
1050 case FIRToken::kw_Analog:
1051 consumeToken(FIRToken::kw_Analog);
1052 // Width is not present since langle_Analog would have been lexed instead.
1053 result = AnalogType::get(getContext(), -1);
1054 break;
1055
1056 case FIRToken::langle_UInt:
1057 case FIRToken::langle_SInt:
1058 case FIRToken::langle_Analog: {
1059 // The '<' has already been consumed by the lexer, so we need to parse
1060 // the mandatory width and the trailing '>'.
1061 auto kind = getToken().getKind();
1062 consumeToken();
1063
1064 int32_t width;
1065 if (parseWidth(width))
1066 return failure();
1067
1068 if (kind == FIRToken::langle_SInt)
1069 result = SIntType::get(getContext(), width);
1070 else if (kind == FIRToken::langle_UInt)
1071 result = UIntType::get(getContext(), width);
1072 else {
1073 assert(kind == FIRToken::langle_Analog);
1074 result = AnalogType::get(getContext(), width);
1075 }
1076 break;
1077 }
1078
1079 case FIRToken::kw_Domain: {
1080 if (requireFeature(missingSpecFIRVersion, "domains"))
1081 return failure();
1082 consumeToken();
1083
1084 // Parse: Domain of SymbolName
1085 auto loc = getToken().getLoc();
1086 StringRef domainKindStr;
1087 if (parseToken(FIRToken::kw_of, "expected 'of' after Domain type") ||
1088 parseId(domainKindStr, "expected domain kind"))
1089 return failure();
1090
1091 // Look up the domain to get its fields
1092 const auto &domainMap = getConstants().domainMap;
1093 auto lookup = domainMap.find(domainKindStr);
1094 if (lookup == domainMap.end())
1095 return emitError(loc) << "unknown domain '" << domainKindStr << "'";
1096
1097 result = DomainType::getFromDomainOp(lookup->second);
1098 break;
1099 }
1100
1101 case FIRToken::kw_Probe:
1102 case FIRToken::kw_RWProbe: {
1103 auto kind = getToken().getKind();
1104 auto loc = getToken().getLoc();
1105 consumeToken();
1106
1107 // Inner Type
1108 FIRRTLType type;
1109 if (parseToken(FIRToken::less, "expected '<' in reference type") ||
1110 parseType(type, "expected probe data type"))
1111 return failure();
1112
1113 SmallVector<StringRef> layers;
1114 if (consumeIf(FIRToken::comma)) {
1115 if (requireFeature({4, 0, 0}, "colored probes"))
1116 return failure();
1117 // Probe Color
1118 do {
1119 StringRef layer;
1120 loc = getToken().getLoc();
1121 if (parseId(layer, "expected layer name"))
1122 return failure();
1123 layers.push_back(layer);
1124 } while (consumeIf(FIRToken::period));
1125 }
1126
1127 if (!consumeIf(FIRToken::greater))
1128 return emitError(loc, "expected '>' to end reference type");
1129
1130 bool forceable = kind == FIRToken::kw_RWProbe;
1131
1133 if (!innerType)
1134 return emitError(loc, "invalid probe inner type, must be base-type");
1135
1136 if (!innerType.isPassive())
1137 return emitError(loc, "probe inner type must be passive");
1138
1139 if (forceable && innerType.containsConst())
1140 return emitError(loc, "rwprobe cannot contain const");
1141
1142 SymbolRefAttr layer;
1143 if (!layers.empty()) {
1144 auto nestedLayers =
1145 llvm::map_range(ArrayRef(layers).drop_front(), [&](StringRef a) {
1146 return FlatSymbolRefAttr::get(getContext(), a);
1147 });
1148 layer = SymbolRefAttr::get(getContext(), layers.front(),
1149 llvm::to_vector(nestedLayers));
1150 }
1151
1152 result = RefType::get(innerType, forceable, layer);
1153 break;
1154 }
1155
1156 case FIRToken::l_brace: {
1157 consumeToken(FIRToken::l_brace);
1158
1159 SmallVector<OpenBundleType::BundleElement, 4> elements;
1160 SmallPtrSet<StringAttr, 4> nameSet;
1161 bool bundleCompatible = true;
1162 if (parseListUntil(FIRToken::r_brace, [&]() -> ParseResult {
1163 bool isFlipped = consumeIf(FIRToken::kw_flip);
1164
1165 auto loc = getToken().getLoc();
1166 StringRef fieldNameStr;
1167 if (parseFieldId(fieldNameStr, "expected bundle field name") ||
1168 parseToken(FIRToken::colon, "expected ':' in bundle"))
1169 return failure();
1170 auto fieldName = StringAttr::get(getContext(), fieldNameStr);
1171
1172 // Verify that the names of each field are unique.
1173 if (!nameSet.insert(fieldName).second)
1174 return emitError(loc, "duplicate field name in bundle: " +
1175 fieldName.getValue());
1176
1177 FIRRTLType type;
1178 if (parseType(type, "expected bundle field type"))
1179 return failure();
1180
1181 elements.push_back({fieldName, isFlipped, type});
1182 bundleCompatible &= isa<BundleType::ElementType>(type);
1183
1184 return success();
1185 }))
1186 return failure();
1187
1188 // Try to emit base-only bundle.
1189 if (bundleCompatible) {
1190 auto bundleElements = llvm::map_range(elements, [](auto element) {
1191 return BundleType::BundleElement{
1192 element.name, element.isFlip,
1193 cast<BundleType::ElementType>(element.type)};
1194 });
1195 result = BundleType::get(getContext(), llvm::to_vector(bundleElements));
1196 } else {
1197 result = OpenBundleType::getChecked(
1198 [&]() { return emitError(typeLoc); }, getContext(),
1199 ArrayRef<OpenBundleType::BundleElement>(elements));
1200 if (!result)
1201 return failure();
1202 }
1203 break;
1204 }
1205
1206 case FIRToken::l_brace_bar: {
1207 if (parseEnumType(result))
1208 return failure();
1209 break;
1210 }
1211
1212 case FIRToken::identifier: {
1213 StringRef id;
1214 auto loc = getToken().getLoc();
1215 if (parseId(id, "expected a type alias name"))
1216 return failure();
1217 auto it = constants.aliasMap.find(id);
1218 if (it == constants.aliasMap.end()) {
1219 emitError(loc) << "type identifier `" << id << "` is not declared";
1220 return failure();
1221 }
1222 result = it->second;
1223 break;
1224 }
1225
1226 case FIRToken::kw_const: {
1227 consumeToken(FIRToken::kw_const);
1228 auto nextToken = getToken();
1229 auto loc = nextToken.getLoc();
1230
1231 // Guard against multiple 'const' specifications
1232 if (nextToken.is(FIRToken::kw_const))
1233 return emitError(loc, "'const' can only be specified once on a type");
1234
1235 if (failed(parseType(result, message)))
1236 return failure();
1237
1238 auto baseType = type_dyn_cast<FIRRTLBaseType>(result);
1239 if (!baseType)
1240 return emitError(loc, "only hardware types can be 'const'");
1241
1242 result = baseType.getConstType(true);
1243 return success();
1244 }
1245
1246 case FIRToken::kw_String:
1247 if (requireFeature({3, 1, 0}, "Strings"))
1248 return failure();
1249 consumeToken(FIRToken::kw_String);
1250 result = StringType::get(getContext());
1251 break;
1252 case FIRToken::kw_Integer:
1253 if (requireFeature({3, 1, 0}, "Integers"))
1254 return failure();
1255 consumeToken(FIRToken::kw_Integer);
1256 result = FIntegerType::get(getContext());
1257 break;
1258 case FIRToken::kw_Bool:
1259 if (requireFeature({6, 0, 0}, "Bools"))
1260 return failure();
1261 consumeToken(FIRToken::kw_Bool);
1262 result = BoolType::get(getContext());
1263 break;
1264 case FIRToken::kw_Double:
1265 if (requireFeature({6, 0, 0}, "Doubles"))
1266 return failure();
1267 consumeToken(FIRToken::kw_Double);
1268 result = DoubleType::get(getContext());
1269 break;
1270 case FIRToken::kw_Path:
1271 if (requireFeature({6, 0, 0}, "Paths"))
1272 return failure();
1273 consumeToken(FIRToken::kw_Path);
1274 result = PathType::get(getContext());
1275 break;
1276 case FIRToken::kw_List:
1277 if (requireFeature({4, 0, 0}, "Lists") || parseListType(result))
1278 return failure();
1279 break;
1280
1281 case FIRToken::langle_List: {
1282 // The '<' has already been consumed by the lexer, so we need to parse
1283 // the element type and the trailing '>'.
1284 if (requireFeature({4, 0, 0}, "Lists"))
1285 return failure();
1286 consumeToken();
1287
1288 PropertyType elementType;
1289 if (parsePropertyType(elementType, "expected List element type") ||
1290 parseToken(FIRToken::greater, "expected '>' in List type"))
1291 return failure();
1292
1293 result = ListType::get(getContext(), elementType);
1294 break;
1295 }
1296
1297 case FIRToken::kw_Option:
1298 case FIRToken::langle_Option:
1299 if (requireFeature(nextFIRVersion, "Options") || parseOptionType(result))
1300 return failure();
1301 break;
1302
1303 case FIRToken::kw_Registry:
1304 if (requireFeature(missingSpecFIRVersion, "Registries") ||
1305 parseRegistryType(result))
1306 return failure();
1307 break;
1308
1309 case FIRToken::langle_Registry: {
1310 // The '<' has already been consumed by the lexer, so we need to parse
1311 // the element type and the trailing '>'.
1312 if (requireFeature(missingSpecFIRVersion, "Registries"))
1313 return failure();
1314 consumeToken();
1315
1316 PropertyType elementType;
1317 if (parsePropertyType(elementType, "expected Registry element type") ||
1318 parseToken(FIRToken::greater, "expected '>' in Registry type"))
1319 return failure();
1320
1321 result = RegistryType::get(getContext(), elementType);
1322 break;
1323 }
1324 }
1325
1326 // Handle postfix vector sizes.
1327 while (consumeIf(FIRToken::l_square)) {
1328 auto sizeLoc = getToken().getLoc();
1329 int64_t size;
1330 if (parseIntLit(size, "expected width") ||
1331 parseToken(FIRToken::r_square, "expected ]"))
1332 return failure();
1333
1334 if (size < 0)
1335 return emitError(sizeLoc, "invalid size specifier"), failure();
1336
1337 auto baseType = type_dyn_cast<FIRRTLBaseType>(result);
1338 if (baseType)
1339 result = FVectorType::get(baseType, size);
1340 else {
1341 result = OpenVectorType::getChecked([&]() { return emitError(typeLoc); },
1342 result, size);
1343 if (!result)
1344 return failure();
1345 }
1346 }
1347
1348 return success();
1349}
1350
1351/// ruw ::= 'old' | 'new' | 'undefined'
1352ParseResult FIRParser::parseRUW(RUWBehavior &result) {
1353 switch (getToken().getKind()) {
1354
1355 case FIRToken::kw_old:
1356 result = RUWBehavior::Old;
1357 consumeToken(FIRToken::kw_old);
1358 break;
1359 case FIRToken::kw_new:
1360 result = RUWBehavior::New;
1361 consumeToken(FIRToken::kw_new);
1362 break;
1363 case FIRToken::kw_undefined:
1364 result = RUWBehavior::Undefined;
1365 consumeToken(FIRToken::kw_undefined);
1366 break;
1367 default:
1368 return failure();
1369 }
1370
1371 return success();
1372}
1373
1374/// ruw ::= 'old' | 'new' | 'undefined'
1375ParseResult FIRParser::parseOptionalRUW(RUWBehavior &result) {
1376 switch (getToken().getKind()) {
1377 default:
1378 break;
1379
1380 case FIRToken::kw_old:
1381 result = RUWBehavior::Old;
1382 consumeToken(FIRToken::kw_old);
1383 break;
1384 case FIRToken::kw_new:
1385 result = RUWBehavior::New;
1386 consumeToken(FIRToken::kw_new);
1387 break;
1388 case FIRToken::kw_undefined:
1389 result = RUWBehavior::Undefined;
1390 consumeToken(FIRToken::kw_undefined);
1391 break;
1392 }
1393
1394 return success();
1395}
1396
1397/// param ::= id '=' param-value
1398ParseResult FIRParser::parseParameter(StringAttr &resultName,
1399 Attribute &resultValue, SMLoc &resultLoc,
1400 bool allowAggregates) {
1401 auto loc = getToken().getLoc();
1402
1403 // Parse the name of the parameter.
1404 StringRef name;
1405 if (parseId(name, "expected parameter name") ||
1406 parseToken(FIRToken::equal, "expected '=' in parameter"))
1407 return failure();
1408
1409 // Parse the value of the parameter.
1410 Attribute value;
1411 if (parseParameterValue(value, allowAggregates))
1412 return failure();
1413
1414 resultName = StringAttr::get(getContext(), name);
1415 resultValue = value;
1416 resultLoc = loc;
1417 return success();
1418}
1419
1420/// param-value ::= intLit
1421/// ::= StringLit
1422/// ::= floatingpoint
1423/// ::= VerbatimStringLit
1424/// ::= '[' (param-value)','* ']' (if allowAggregates)
1425/// ::= '{' (id '=' param)','* '}' (if allowAggregates)
1426ParseResult FIRParser::parseParameterValue(Attribute &value,
1427 bool allowAggregates) {
1428 mlir::Builder builder(getContext());
1429 switch (getToken().getKind()) {
1430
1431 // param-value ::= intLit
1432 case FIRToken::integer:
1433 case FIRToken::signed_integer: {
1434 APInt result;
1435 if (parseIntLit(result, "invalid integer parameter"))
1436 return failure();
1437
1438 // If the integer parameter is less than 32-bits, sign extend this to a
1439 // 32-bit value. This needs to eventually emit as a 32-bit value in
1440 // Verilog and we want to get the size correct immediately.
1441 if (result.getBitWidth() < 32)
1442 result = result.sext(32);
1443
1444 value = builder.getIntegerAttr(
1445 builder.getIntegerType(result.getBitWidth(), result.isSignBitSet()),
1446 result);
1447 return success();
1448 }
1449
1450 // param-value ::= StringLit
1451 case FIRToken::string: {
1452 // Drop the double quotes and unescape.
1453 value = builder.getStringAttr(getToken().getStringValue());
1454 consumeToken(FIRToken::string);
1455 return success();
1456 }
1457
1458 // param-value ::= VerbatimStringLit
1459 case FIRToken::verbatim_string: {
1460 // Drop the single quotes and unescape the ones inside.
1461 auto text = builder.getStringAttr(getToken().getVerbatimStringValue());
1462 value = hw::ParamVerbatimAttr::get(text);
1463 consumeToken(FIRToken::verbatim_string);
1464 return success();
1465 }
1466
1467 // param-value ::= floatingpoint
1468 case FIRToken::floatingpoint: {
1469 double v;
1470 if (!llvm::to_float(getTokenSpelling(), v))
1471 return emitError("invalid float parameter syntax"), failure();
1472
1473 value = builder.getF64FloatAttr(v);
1474 consumeToken(FIRToken::floatingpoint);
1475 return success();
1476 }
1477
1478 // param-value ::= '[' (param)','* ']'
1479 case FIRToken::l_square: {
1480 if (!allowAggregates)
1481 return emitError("expected non-aggregate parameter value");
1482 consumeToken();
1483
1484 SmallVector<Attribute> elements;
1485 auto parseElement = [&] {
1486 return parseParameterValue(elements.emplace_back(),
1487 /*allowAggregates=*/true);
1488 };
1489 if (parseListUntil(FIRToken::r_square, parseElement))
1490 return failure();
1491
1492 value = builder.getArrayAttr(elements);
1493 return success();
1494 }
1495
1496 // param-value ::= '{' (id '=' param)','* '}'
1497 case FIRToken::l_brace: {
1498 if (!allowAggregates)
1499 return emitError("expected non-aggregate parameter value");
1500 consumeToken();
1501
1502 NamedAttrList fields;
1503 auto parseField = [&]() -> ParseResult {
1504 StringAttr fieldName;
1505 Attribute fieldValue;
1506 SMLoc fieldLoc;
1507 if (parseParameter(fieldName, fieldValue, fieldLoc,
1508 /*allowAggregates=*/true))
1509 return failure();
1510 if (fields.set(fieldName, fieldValue))
1511 return emitError(fieldLoc)
1512 << "redefinition of parameter '" << fieldName.getValue() << "'";
1513 return success();
1514 };
1515 if (parseListUntil(FIRToken::r_brace, parseField))
1516 return failure();
1517
1518 value = fields.getDictionary(getContext());
1519 return success();
1520 }
1521
1522 default:
1523 return emitError("expected parameter value");
1524 }
1525}
1526
1527//===----------------------------------------------------------------------===//
1528// FIRModuleContext
1529//===----------------------------------------------------------------------===//
1530
1531// Entries in a symbol table are either an mlir::Value for the operation that
1532// defines the value or an unbundled ID tracking the index in the
1533// UnbundledValues list.
1534using UnbundledID = llvm::PointerEmbeddedInt<unsigned, 31>;
1535using SymbolValueEntry = llvm::PointerUnion<Value, UnbundledID>;
1536
1538 llvm::StringMap<std::pair<SMLoc, SymbolValueEntry>, llvm::BumpPtrAllocator>;
1539using ModuleSymbolTableEntry = ModuleSymbolTable::MapEntryTy;
1540
1541using UnbundledValueEntry = SmallVector<std::pair<Attribute, Value>>;
1542using UnbundledValuesList = std::vector<UnbundledValueEntry>;
1543namespace {
1544/// This structure is used to track which entries are added while inside a scope
1545/// and remove them upon exiting the scope.
1546struct UnbundledValueRestorer {
1547 UnbundledValuesList &list;
1548 size_t startingSize;
1549 UnbundledValueRestorer(UnbundledValuesList &list) : list(list) {
1550 startingSize = list.size();
1551 }
1552 ~UnbundledValueRestorer() { list.resize(startingSize); }
1553};
1554} // namespace
1555
1556using SubaccessCache = llvm::DenseMap<std::pair<Value, unsigned>, Value>;
1557
1558namespace {
1559/// This struct provides context information that is global to the module we're
1560/// currently parsing into.
1561struct FIRModuleContext : public FIRParser {
1562 explicit FIRModuleContext(Block *topLevelBlock,
1563 SharedParserConstants &constants, FIRLexer &lexer,
1564 FIRVersion version)
1565 : FIRParser(constants, lexer, version), topLevelBlock(topLevelBlock) {}
1566
1567 /// Get a cached constant.
1568 template <typename OpTy = ConstantOp, typename... Args>
1569 Value getCachedConstant(ImplicitLocOpBuilder &builder, Attribute attr,
1570 Type type, Args &&...args) {
1571 auto &result = constantCache[{attr, type}];
1572 if (result)
1573 return result;
1574
1575 // Make sure to insert constants at the top level of the module to maintain
1576 // dominance.
1577 OpBuilder::InsertPoint savedIP;
1578
1579 // Find the insertion point.
1580 if (builder.getInsertionBlock() != topLevelBlock) {
1581 savedIP = builder.saveInsertionPoint();
1582 auto *block = builder.getInsertionBlock();
1583 while (true) {
1584 auto *op = block->getParentOp();
1585 if (!op || !op->getBlock()) {
1586 // We are inserting into an unknown region.
1587 builder.setInsertionPointToEnd(topLevelBlock);
1588 break;
1589 }
1590 if (op->getBlock() == topLevelBlock) {
1591 builder.setInsertionPoint(op);
1592 break;
1593 }
1594 block = op->getBlock();
1595 }
1596 }
1597
1598 result = OpTy::create(builder, type, std::forward<Args>(args)...);
1599
1600 if (savedIP.isSet())
1601 builder.setInsertionPoint(savedIP.getBlock(), savedIP.getPoint());
1602
1603 return result;
1604 }
1605
1606 //===--------------------------------------------------------------------===//
1607 // SubaccessCache
1608
1609 /// This returns a reference with the assumption that the caller will fill in
1610 /// the cached value. We keep track of inserted subaccesses so that we can
1611 /// remove them when we exit a scope.
1612 Value &getCachedSubaccess(Value value, unsigned index) {
1613 auto &result = subaccessCache[{value, index}];
1614 if (!result) {
1615 // The outer most block won't be in the map.
1616 auto it = scopeMap.find(value.getParentBlock());
1617 if (it != scopeMap.end())
1618 it->second->scopedSubaccesses.push_back({result, index});
1619 }
1620 return result;
1621 }
1622
1623 //===--------------------------------------------------------------------===//
1624 // SymbolTable
1625
1626 /// Add a symbol entry with the specified name, returning failure if the name
1627 /// is already defined.
1628 ParseResult addSymbolEntry(StringRef name, SymbolValueEntry entry, SMLoc loc,
1629 bool insertNameIntoGlobalScope = false);
1630 ParseResult addSymbolEntry(StringRef name, Value value, SMLoc loc,
1631 bool insertNameIntoGlobalScope = false) {
1632 return addSymbolEntry(name, SymbolValueEntry(value), loc,
1633 insertNameIntoGlobalScope);
1634 }
1635
1636 // Removes a symbol from symbolTable (Workaround since symbolTable is private)
1637 void removeSymbolEntry(StringRef name);
1638
1639 /// Resolved a symbol table entry to a value. Emission of error is optional.
1640 ParseResult resolveSymbolEntry(Value &result, SymbolValueEntry &entry,
1641 SMLoc loc, bool fatal = true);
1642
1643 /// Resolved a symbol table entry if it is an expanded bundle e.g. from an
1644 /// instance. Emission of error is optional.
1645 ParseResult resolveSymbolEntry(Value &result, SymbolValueEntry &entry,
1646 StringRef field, SMLoc loc);
1647
1648 /// Look up the specified name, emitting an error and returning failure if the
1649 /// name is unknown.
1650 ParseResult lookupSymbolEntry(SymbolValueEntry &result, StringRef name,
1651 SMLoc loc);
1652
1653 UnbundledValueEntry &getUnbundledEntry(unsigned index) {
1654 assert(index < unbundledValues.size());
1655 return unbundledValues[index];
1656 }
1657
1658 /// This contains one entry for each value in FIRRTL that is represented as a
1659 /// bundle type in the FIRRTL spec but for which we represent as an exploded
1660 /// set of elements in the FIRRTL dialect.
1661 UnbundledValuesList unbundledValues;
1662
1663 /// Provide a symbol table scope that automatically pops all the entries off
1664 /// the symbol table when the scope is exited.
1665 struct ContextScope {
1666 friend struct FIRModuleContext;
1667 ContextScope(FIRModuleContext &moduleContext, Block *block)
1668 : moduleContext(moduleContext), block(block),
1669 previousScope(moduleContext.currentScope) {
1670 moduleContext.currentScope = this;
1671 moduleContext.scopeMap[block] = this;
1672 }
1673 ~ContextScope() {
1674 // Mark all entries in this scope as being invalid. We track validity
1675 // through the SMLoc field instead of deleting entries.
1676 for (auto *entryPtr : scopedDecls)
1677 entryPtr->second.first = SMLoc();
1678 // Erase the scoped subacceses from the cache. If the block is deleted we
1679 // could resuse the memory, although the chances are quite small.
1680 for (auto subaccess : scopedSubaccesses)
1681 moduleContext.subaccessCache.erase(subaccess);
1682 // Erase this context from the map.
1683 moduleContext.scopeMap.erase(block);
1684 // Reset to the previous scope.
1685 moduleContext.currentScope = previousScope;
1686 }
1687
1688 private:
1689 void operator=(const ContextScope &) = delete;
1690 ContextScope(const ContextScope &) = delete;
1691
1692 FIRModuleContext &moduleContext;
1693 Block *block;
1694 ContextScope *previousScope;
1695 std::vector<ModuleSymbolTableEntry *> scopedDecls;
1696 std::vector<std::pair<Value, unsigned>> scopedSubaccesses;
1697 };
1698
1699private:
1700 /// The top level block in which we insert cached constants.
1701 Block *topLevelBlock;
1702
1703 /// The expression-oriented nature of firrtl syntax produces tons of constant
1704 /// nodes which are obviously redundant. Instead of literally producing them
1705 /// in the parser, do an implicit CSE to reduce parse time and silliness in
1706 /// the resulting IR.
1707 llvm::DenseMap<std::pair<Attribute, Type>, Value> constantCache;
1708
1709 /// This symbol table holds the names of ports, wires, and other local decls.
1710 /// This is scoped because conditional statements introduce subscopes.
1711 ModuleSymbolTable symbolTable;
1712
1713 /// This is a cache of subindex and subfield operations so we don't constantly
1714 /// recreate large chains of them. This maps a bundle value + index to the
1715 /// subaccess result.
1716 SubaccessCache subaccessCache;
1717
1718 /// This maps a block to related ContextScope.
1719 DenseMap<Block *, ContextScope *> scopeMap;
1720
1721 /// If non-null, all new entries added to the symbol table are added to this
1722 /// list. This allows us to "pop" the entries by resetting them to null when
1723 /// scope is exited.
1724 ContextScope *currentScope = nullptr;
1725};
1726
1727} // end anonymous namespace
1728
1729// Removes a symbol from symbolTable (Workaround since symbolTable is private)
1730void FIRModuleContext::removeSymbolEntry(StringRef name) {
1731 symbolTable.erase(name);
1732}
1733
1734/// Add a symbol entry with the specified name, returning failure if the name
1735/// is already defined.
1736///
1737/// When 'insertNameIntoGlobalScope' is true, we don't allow the name to be
1738/// popped. This is a workaround for (firrtl scala bug) that should eventually
1739/// be fixed.
1740ParseResult FIRModuleContext::addSymbolEntry(StringRef name,
1741 SymbolValueEntry entry, SMLoc loc,
1742 bool insertNameIntoGlobalScope) {
1743 // Do a lookup by trying to do an insertion. Do so in a way that we can tell
1744 // if we hit a missing element (SMLoc is null).
1745 auto [entryIt, inserted] =
1746 symbolTable.try_emplace(name, SMLoc(), SymbolValueEntry());
1747
1748 // If insertion failed, the name already exists
1749 if (!inserted) {
1750 if (entryIt->second.first.isValid()) {
1751 // Valid activeSMLoc: active symbol in current scope redeclared
1752 emitError(loc, "redefinition of name '" + name + "' ")
1753 .attachNote(translateLocation(entryIt->second.first))
1754 << "previous definition here.";
1755 } else {
1756 // Invalid activeSMLoc: symbol from a completed scope redeclared
1757 emitError(loc, "redefinition of name '" + name + "' ")
1758 << "- FIRRTL has flat namespace and requires all "
1759 << "declarations in a module to have unique names.";
1760 }
1761 return failure();
1762 }
1763
1764 // If we didn't have a hit, then record the location, and remember that this
1765 // was new to this scope.
1766 entryIt->second = {loc, entry};
1767 if (currentScope && !insertNameIntoGlobalScope)
1768 currentScope->scopedDecls.push_back(&*entryIt);
1769 return success();
1770}
1771
1772/// Look up the specified name, emitting an error and returning null if the
1773/// name is unknown.
1774ParseResult FIRModuleContext::lookupSymbolEntry(SymbolValueEntry &result,
1775 StringRef name, SMLoc loc) {
1776 auto &entry = symbolTable[name];
1777 if (!entry.first.isValid())
1778 return emitError(loc, "use of unknown declaration '" + name + "'");
1779 result = entry.second;
1780 assert(result && "name in symbol table without definition");
1781 return success();
1782}
1783
1784ParseResult FIRModuleContext::resolveSymbolEntry(Value &result,
1785 SymbolValueEntry &entry,
1786 SMLoc loc, bool fatal) {
1787 if (!isa<Value>(entry)) {
1788 if (fatal)
1789 emitError(loc, "bundle value should only be used from subfield");
1790 return failure();
1791 }
1792 result = cast<Value>(entry);
1793 return success();
1794}
1795
1796ParseResult FIRModuleContext::resolveSymbolEntry(Value &result,
1797 SymbolValueEntry &entry,
1798 StringRef fieldName,
1799 SMLoc loc) {
1800 if (!isa<UnbundledID>(entry)) {
1801 emitError(loc, "value should not be used from subfield");
1802 return failure();
1803 }
1804
1805 auto fieldAttr = StringAttr::get(getContext(), fieldName);
1806
1807 unsigned unbundledId = cast<UnbundledID>(entry) - 1;
1808 assert(unbundledId < unbundledValues.size());
1809 UnbundledValueEntry &ubEntry = unbundledValues[unbundledId];
1810 for (auto elt : ubEntry) {
1811 if (elt.first == fieldAttr) {
1812 result = elt.second;
1813 break;
1814 }
1815 }
1816 if (!result) {
1817 emitError(loc, "use of invalid field name '")
1818 << fieldName << "' on bundle value";
1819 return failure();
1820 }
1821
1822 return success();
1823}
1824
1825//===----------------------------------------------------------------------===//
1826// FIRStmtParser
1827//===----------------------------------------------------------------------===//
1828
1829namespace {
1830/// This class is used when building expression nodes for a statement: we need
1831/// to parse a bunch of expressions and build MLIR operations for them, and then
1832/// we see the locator that specifies the location for those operations
1833/// afterward.
1834///
1835/// It is wasteful in time and memory to create a bunch of temporary FileLineCol
1836/// location's that point into the .fir file when they're destined to get
1837/// overwritten by a location specified by a Locator. To avoid this, we create
1838/// all of the operations with a temporary location on them, then remember the
1839/// [Operation*, SMLoc] pair for the newly created operation.
1840///
1841/// At the end of the operation we'll see a Locator (or not). If we see a
1842/// locator, we apply it to all the operations we've parsed and we're done. If
1843/// not, we lazily create the locators in the .fir file.
1844struct LazyLocationListener : public OpBuilder::Listener {
1845 LazyLocationListener(OpBuilder &builder) : builder(builder) {
1846 assert(builder.getListener() == nullptr);
1847 builder.setListener(this);
1848 }
1849
1850 ~LazyLocationListener() {
1851 assert(subOps.empty() && "didn't process parsed operations");
1852 assert(builder.getListener() == this);
1853 builder.setListener(nullptr);
1854 }
1855
1856 void startStatement() {
1857 assert(!isActive && "Already processing a statement");
1858 isActive = true;
1859 }
1860
1861 /// Compute the location an operation created at `loc` should be given,
1862 /// or that a diagnostic about it should be emitted on, honoring the
1863 /// the @info handling policy. This will only translate the SMLoc when the
1864 /// policy actually needs it, since that will intern a location into the
1865 /// context permanently.
1866 Location getLoc(FIRParser &parser, SMLoc loc) {
1868 switch (parser.getConstants().options.infoLocatorHandling) {
1869 case ILH::IgnoreInfo:
1870 // Shouldn't have an infoLoc, but if we do ignore it.
1871 break;
1872 case ILH::PreferInfo:
1873 if (infoLoc)
1874 return infoLoc;
1875 break;
1876 case ILH::FusedInfo:
1877 if (infoLoc)
1878 return FusedLoc::get(infoLoc.getContext(),
1879 {infoLoc, parser.translateLocation(loc)});
1880 break;
1881 }
1882 return parser.translateLocation(loc);
1883 }
1884
1885 /// This is called when done with each statement. This applies the locations
1886 /// to each statement.
1887 void endStatement(FIRParser &parser) {
1888 assert(isActive && "Not parsing a statement");
1889
1890 // Apply a location to each subop, following user preference to use the
1891 // @info location, a fused location, or the location in the .fir file.
1892 for (auto opAndSMLoc : subOps)
1893 opAndSMLoc.first->setLoc(getLoc(parser, opAndSMLoc.second));
1894
1895 // Reset our state.
1896 isActive = false;
1897 infoLoc = LocationAttr();
1898 currentSMLoc = SMLoc();
1899 subOps.clear();
1900 }
1901
1902 /// Specify the location to be used for the next operations that are created.
1903 void setLoc(SMLoc loc) { currentSMLoc = loc; }
1904
1905 /// When a @Info locator is parsed, this method captures it.
1906 void setInfoLoc(LocationAttr loc) {
1907 assert(!infoLoc && "Info location multiply specified");
1908 infoLoc = loc;
1909 }
1910
1911 // Notification handler for when an operation is inserted into the builder.
1912 /// `op` is the operation that was inserted.
1913 void notifyOperationInserted(Operation *op,
1914 mlir::IRRewriter::InsertPoint) override {
1915 assert(currentSMLoc != SMLoc() && "No .fir file location specified");
1916 assert(isActive && "Not parsing a statement");
1917 subOps.push_back({op, currentSMLoc});
1918 }
1919
1920private:
1921 /// This is set to true while parsing a statement. It is used for assertions.
1922 bool isActive = false;
1923
1924 /// This is the current position in the source file that the next operation
1925 /// will be parsed into.
1926 SMLoc currentSMLoc;
1927
1928 /// This is the @ location attribute for the current statement, or null if
1929 /// not set.
1930 LocationAttr infoLoc;
1931
1932 /// This is the builder we're installed into.
1933 OpBuilder &builder;
1934
1935 /// This is the set of operations we've enqueued along with their location in
1936 /// the source file.
1937 SmallVector<std::pair<Operation *, SMLoc>, 8> subOps;
1938
1939 void operator=(const LazyLocationListener &) = delete;
1940 LazyLocationListener(const LazyLocationListener &) = delete;
1941};
1942} // end anonymous namespace
1943
1944namespace {
1945/// This class tracks inner-ref users and their intended targets,
1946/// (presently there must be just one) for post-processing at a point
1947/// where adding the symbols is safe without risk of races.
1948struct InnerSymFixups {
1949 /// Add a fixup to be processed later.
1950 void add(hw::InnerRefUserOpInterface user, hw::InnerSymTarget target) {
1951 fixups.push_back({user, target});
1952 }
1953
1954 /// Resolve all stored fixups, if any. Not expected to fail,
1955 /// as checking should primarily occur during original parsing.
1956 LogicalResult resolve(hw::InnerSymbolNamespaceCollection &isnc);
1957
1958private:
1959 struct Fixup {
1960 hw::InnerRefUserOpInterface innerRefUser;
1961 hw::InnerSymTarget target;
1962 };
1963 SmallVector<Fixup, 0> fixups;
1964};
1965} // end anonymous namespace
1966
1967LogicalResult
1968InnerSymFixups::resolve(hw::InnerSymbolNamespaceCollection &isnc) {
1969 for (auto &f : fixups) {
1970 auto ref = getInnerRefTo(
1971 f.target, [&isnc](FModuleLike module) -> hw::InnerSymbolNamespace & {
1972 return isnc.get(module);
1973 });
1974 assert(ref && "unable to resolve inner symbol target");
1975
1976 // Per-op fixup logic. Only RWProbeOp's presently.
1977 auto result =
1978 TypeSwitch<Operation *, LogicalResult>(f.innerRefUser.getOperation())
1979 .Case<RWProbeOp>([ref](RWProbeOp op) {
1980 op.setTargetAttr(ref);
1981 return success();
1982 })
1983 .Default([](auto *op) {
1984 return op->emitError("unknown inner-ref user requiring fixup");
1985 });
1986 if (failed(result))
1987 return failure();
1988 }
1989 return success();
1990}
1991
1992namespace {
1993/// This class implements logic and state for parsing statements, suites, and
1994/// similar module body constructs.
1995struct FIRStmtParser : public FIRParser {
1996 explicit FIRStmtParser(Block &blockToInsertInto,
1997 FIRModuleContext &moduleContext,
1998 InnerSymFixups &innerSymFixups,
1999 const SymbolTable &circuitSymTbl, FIRVersion version,
2000 SymbolRefAttr layerSym = {})
2001 : FIRParser(moduleContext.getConstants(), moduleContext.getLexer(),
2002 version),
2003 builder(UnknownLoc::get(getContext()), getContext()),
2004 locationProcessor(this->builder), moduleContext(moduleContext),
2005 innerSymFixups(innerSymFixups), layerSym(layerSym),
2006 circuitSymTbl(circuitSymTbl) {
2007 builder.setInsertionPointToEnd(&blockToInsertInto);
2008 }
2009
2010 ParseResult parseSimpleStmt(unsigned stmtIndent);
2011 ParseResult parseSimpleStmtBlock(unsigned indent);
2012
2013private:
2014 ParseResult parseSimpleStmtImpl(unsigned stmtIndent);
2015
2016 /// Attach invalid values to every element of the value.
2017 void emitInvalidate(Value val, Flow flow);
2018
2019 // The FIRRTL specification describes Invalidates as a statement with
2020 // implicit connect semantics. The FIRRTL dialect models it as a primitive
2021 // that returns an "Invalid Value", followed by an explicit connect to make
2022 // the representation simpler and more consistent.
2023 void emitInvalidate(Value val) { emitInvalidate(val, foldFlow(val)); }
2024
2025 /// Parse an @info marker if present and inform locationProcessor about it.
2026 ParseResult parseOptionalInfo() {
2027 LocationAttr loc;
2028 if (failed(parseOptionalInfoLocator(loc)))
2029 return failure();
2030 locationProcessor.setInfoLoc(loc);
2031 return success();
2032 }
2033
2034 // Exp Parsing
2035 ParseResult parseExpImpl(Value &result, const Twine &message,
2036 bool isLeadingStmt);
2037 ParseResult parseExp(Value &result, const Twine &message) {
2038 return parseExpImpl(result, message, /*isLeadingStmt:*/ false);
2039 }
2040 ParseResult parseExpLeadingStmt(Value &result, const Twine &message) {
2041 return parseExpImpl(result, message, /*isLeadingStmt:*/ true);
2042 }
2043 /// Insert an implicit object- or domain-to-AnyRef cast if required by the
2044 /// expected type. Leave other values unchanged for the caller to type-check.
2045 Value emitImplicitAnyRefCast(Value value, Type expectedType) {
2046 if (!isa<AnyRefType>(expectedType))
2047 return value;
2048 if (isa<ClassType>(value.getType()))
2049 return ObjectAnyRefCastOp::create(builder, value);
2050 if (isa<DomainType>(value.getType()))
2051 return DomainAnyRefCastOp::create(builder, value);
2052 return value;
2053 }
2054
2055 ParseResult parseEnumExp(Value &result);
2056 ParseResult parsePathExp(Value &result);
2057 ParseResult parseDomainExp(Value &result);
2058 ParseResult parseRefExp(Value &result, const Twine &message);
2059 ParseResult parseStaticRefExp(Value &result, const Twine &message);
2060 ParseResult parseRWProbeStaticRefExp(FieldRef &refResult, Type &type,
2061 const Twine &message);
2062
2063 // Generic intrinsic parsing.
2064 ParseResult parseIntrinsic(Value &result, bool isStatement);
2065 ParseResult parseIntrinsicStmt() {
2066 Value unused;
2067 return parseIntrinsic(unused, /*isStatement=*/true);
2068 }
2069 ParseResult parseIntrinsicExp(Value &result) {
2070 return parseIntrinsic(result, /*isStatement=*/false);
2071 }
2072 ParseResult parseOptionalParams(ArrayAttr &resultParameters);
2073
2074 template <typename subop>
2075 FailureOr<Value> emitCachedSubAccess(Value base, unsigned indexNo, SMLoc loc);
2076 ParseResult parseOptionalExpPostscript(Value &result,
2077 bool allowDynamic = true);
2078 ParseResult parsePostFixFieldId(Value &result);
2079 ParseResult parsePostFixIntSubscript(Value &result);
2080 ParseResult parsePostFixDynamicSubscript(Value &result);
2081 ParseResult
2082 parseIntegerLiteralExp(Value &result, bool isSigned,
2083 std::optional<int32_t> allocatedWidth = {});
2084 ParseResult parseListExp(Value &result);
2085 ParseResult parseListConcatExp(Value &result);
2086 ParseResult parseOptionExp(Value &result);
2087 ParseResult parseOptionGetOrElseExp(Value &result);
2088 ParseResult parseCatExp(Value &result);
2089 ParseResult parseStringConcatExp(Value &result);
2090 ParseResult parsePropEqExp(Value &result);
2091 ParseResult parseListLengthExp(Value &result);
2092 ParseResult parseListContainsExp(Value &result);
2093 ParseResult parseUnsafeDomainCast(Value &result);
2094 ParseResult parseUnknownProperty(Value &result);
2095
2096 template <typename T, size_t M, size_t N, size_t... Ms, size_t... Ns>
2097 ParseResult parsePrim(std::index_sequence<Ms...>, std::index_sequence<Ns...>,
2098 Value &result) {
2099 auto loc = getToken().getLoc();
2100 locationProcessor.setLoc(loc);
2101 consumeToken();
2102
2103 auto vals = std::array<Value, M>();
2104 auto ints = std::array<int64_t, N>();
2105
2106 // Parse all the values.
2107 bool first = true;
2108 for (size_t i = 0; i < M; ++i) {
2109 if (!first)
2110 if (parseToken(FIRToken::comma, "expected ','"))
2111 return failure();
2112 if (parseExp(vals[i], "expected expression in primitive operand"))
2113 return failure();
2114 first = false;
2115 }
2116
2117 // Parse all the attributes.
2118 for (size_t i = 0; i < N; ++i) {
2119 if (!first)
2120 if (parseToken(FIRToken::comma, "expected ','"))
2121 return failure();
2122 if (parseIntLit(ints[i], "expected integer in primitive operand"))
2123 return failure();
2124 first = false;
2125 }
2126
2127 if (parseToken(FIRToken::r_paren, "expected ')'"))
2128 return failure();
2129
2130 // Infer the type.
2131 auto type = T::inferReturnType(cast<FIRRTLType>(vals[Ms].getType())...,
2132 ints[Ns]..., {});
2133 if (!type) {
2134 // Only call translateLocation on an error case, it is expensive.
2135 T::inferReturnType(cast<FIRRTLType>(vals[Ms].getType())..., ints[Ns]...,
2136 translateLocation(loc));
2137 return failure();
2138 }
2139
2140 // Create the operation.
2141 auto op = T::create(builder, type, vals[Ms]..., ints[Ns]...);
2142 result = op.getResult();
2143 return success();
2144 }
2145
2146 template <typename T, unsigned M, unsigned N>
2147 ParseResult parsePrimExp(Value &result) {
2148 auto ms = std::make_index_sequence<M>();
2149 auto ns = std::make_index_sequence<N>();
2150 return parsePrim<T, M, N>(ms, ns, result);
2151 }
2152
2153 std::optional<ParseResult> parseExpWithLeadingKeyword(FIRToken keyword);
2154
2155 // Stmt Parsing
2156 ParseResult parseSubBlock(Block &blockToInsertInto, unsigned indent,
2157 SymbolRefAttr layerSym);
2158 ParseResult parseAttach();
2159 ParseResult parseMemPort(MemDirAttr direction);
2160
2161 // Parse a format string and build operations for FIRRTL "special"
2162 // substitutions. Set `formatStringResult` to the validated format string and
2163 // `operands` to the list of actual operands.
2164 ParseResult parseFormatString(SMLoc formatStringLoc, StringRef formatString,
2165 ArrayRef<Value> specOperands,
2166 StringAttr &formatStringResult,
2167 SmallVectorImpl<Value> &operands);
2168 ParseResult parsePrintf();
2169 ParseResult parseFPrintf();
2170 ParseResult parseFFlush();
2171 ParseResult parseSkip();
2172 ParseResult parseStop();
2173 ParseResult parseAssert();
2174 ParseResult parseAssume();
2175 ParseResult parseCover();
2176 ParseResult parseWhen(unsigned whenIndent);
2177 ParseResult parseMatch(unsigned matchIndent);
2178 ParseResult parseDomainInstantiation();
2179 ParseResult parseDomainDefine();
2180 ParseResult parseRefDefine();
2181 ParseResult parseRefForce();
2182 ParseResult parseRefForceInitial();
2183 ParseResult parseRefRelease();
2184 ParseResult parseRefReleaseInitial();
2185 ParseResult parseRefRead(Value &result);
2186 ParseResult parseProbe(Value &result);
2187 ParseResult parsePropAssert();
2188 ParseResult parsePropAssign();
2189 ParseResult parseRWProbe(Value &result);
2190 ParseResult parseLeadingExpStmt(Value lhs);
2191 ParseResult parseConnect();
2192 ParseResult parseInvalidate();
2193 ParseResult parseLayerBlockOrGroup(unsigned indent);
2194
2195 // Declarations
2196 ParseResult parseInstance();
2197 ParseResult parseInstanceChoice();
2198 ParseResult parseObject();
2199 ParseResult parseCombMem();
2200 ParseResult parseSeqMem();
2201 ParseResult parseMem(unsigned memIndent);
2202 ParseResult parseNode();
2203 ParseResult parseWire();
2204 ParseResult parseRegister(unsigned regIndent);
2205 ParseResult parseRegisterWithReset();
2206 ParseResult parseContract(unsigned blockIndent);
2207
2208 // Helper to fetch a module referenced by an instance-like statement.
2209 FModuleLike getReferencedModule(SMLoc loc, StringRef moduleName);
2210
2211 // The builder to build into.
2212 ImplicitLocOpBuilder builder;
2213 LazyLocationListener locationProcessor;
2214
2215 // Extra information maintained across a module.
2216 FIRModuleContext &moduleContext;
2217
2218 /// Inner symbol users to fixup after parsing.
2219 InnerSymFixups &innerSymFixups;
2220
2221 // An optional symbol that contains the current layer block that we are in.
2222 // This is used to construct a nested symbol for a layer block operation.
2223 SymbolRefAttr layerSym;
2224
2225 const SymbolTable &circuitSymTbl;
2226};
2227
2228} // end anonymous namespace
2229
2230/// Attach invalid values to every element of the value.
2231// NOLINTNEXTLINE(misc-no-recursion)
2232void FIRStmtParser::emitInvalidate(Value val, Flow flow) {
2233 auto tpe = type_dyn_cast<FIRRTLBaseType>(val.getType());
2234 // Invalidate does nothing for non-base types.
2235 // When aggregates-of-refs are supported, instead check 'containsReference'
2236 // below.
2237 if (!tpe)
2238 return;
2239
2240 auto props = tpe.getRecursiveTypeProperties();
2241 if (props.isPassive && !props.containsAnalog) {
2242 if (flow == Flow::Source)
2243 return;
2244 emitConnect(builder, val, InvalidValueOp::create(builder, tpe),
2245 getConstants().options.warnOnTruncation);
2246 return;
2247 }
2248
2249 // Recurse until we hit passive leaves. Connect any leaves which have sink or
2250 // duplex flow.
2251 //
2252 // TODO: This is very similar to connect expansion in the LowerTypes pass
2253 // works. Find a way to unify this with methods common to LowerTypes or to
2254 // have LowerTypes to the actual work here, e.g., emitting a partial connect
2255 // to only the leaf sources.
2256 TypeSwitch<FIRRTLType>(tpe)
2257 .Case<BundleType>([&](auto tpe) {
2258 for (size_t i = 0, e = tpe.getNumElements(); i < e; ++i) {
2259 auto &subfield = moduleContext.getCachedSubaccess(val, i);
2260 if (!subfield) {
2261 OpBuilder::InsertionGuard guard(builder);
2262 builder.setInsertionPointAfterValue(val);
2263 subfield = SubfieldOp::create(builder, val, i);
2264 }
2265 emitInvalidate(subfield,
2266 tpe.getElement(i).isFlip ? swapFlow(flow) : flow);
2267 }
2268 })
2269 .Case<FVectorType>([&](auto tpe) {
2270 auto tpex = tpe.getElementType();
2271 for (size_t i = 0, e = tpe.getNumElements(); i != e; ++i) {
2272 auto &subindex = moduleContext.getCachedSubaccess(val, i);
2273 if (!subindex) {
2274 OpBuilder::InsertionGuard guard(builder);
2275 builder.setInsertionPointAfterValue(val);
2276 subindex = SubindexOp::create(builder, tpex, val, i);
2277 }
2278 emitInvalidate(subindex, flow);
2279 }
2280 });
2281}
2282
2283//===-------------------------------
2284// FIRStmtParser Expression Parsing.
2285
2286/// Parse the 'exp' grammar, returning all of the suboperations in the
2287/// specified vector, and the ultimate SSA value in value.
2288///
2289/// exp ::= id // Ref
2290/// ::= prim
2291/// ::= integer-literal-exp
2292/// ::= enum-exp
2293/// ::= list-exp
2294/// ::= 'String(' stringLit ')'
2295/// ::= exp '.' fieldId
2296/// ::= exp '[' intLit ']'
2297/// XX ::= exp '.' DoubleLit // TODO Workaround for #470
2298/// ::= exp '[' exp ']'
2299///
2300///
2301/// If 'isLeadingStmt' is true, then this is being called to parse the first
2302/// expression in a statement. We can handle some weird cases due to this if
2303/// we end up parsing the whole statement. In that case we return success, but
2304/// set the 'result' value to null.
2305// NOLINTNEXTLINE(misc-no-recursion)
2306ParseResult FIRStmtParser::parseExpImpl(Value &result, const Twine &message,
2307 bool isLeadingStmt) {
2308 auto token = getToken();
2309 auto kind = token.getKind();
2310 switch (kind) {
2311 case FIRToken::lp_integer_add:
2312 case FIRToken::lp_integer_mul:
2313 case FIRToken::lp_integer_shr:
2314 case FIRToken::lp_integer_shl:
2315 if (requireFeature({4, 0, 0}, "Integer arithmetic expressions"))
2316 return failure();
2317 break;
2318 default:
2319 break;
2320 }
2321
2322 switch (kind) {
2323 // Handle all primitive's.
2324#define TOK_LPKEYWORD_PRIM(SPELLING, CLASS, NUMOPERANDS, NUMATTRIBUTES, \
2325 VERSION, FEATURE) \
2326 case FIRToken::lp_##SPELLING: \
2327 if (requireFeature(VERSION, FEATURE)) \
2328 return failure(); \
2329 if (parsePrimExp<CLASS, NUMOPERANDS, NUMATTRIBUTES>(result)) \
2330 return failure(); \
2331 break;
2332#include "FIRTokenKinds.def"
2333
2334 case FIRToken::l_brace_bar:
2335 if (isLeadingStmt)
2336 return emitError("unexpected enumeration as start of statement");
2337 if (parseEnumExp(result))
2338 return failure();
2339 break;
2340 case FIRToken::lp_read:
2341 if (isLeadingStmt)
2342 return emitError("unexpected read() as start of statement");
2343 if (parseRefRead(result))
2344 return failure();
2345 break;
2346 case FIRToken::lp_probe:
2347 if (isLeadingStmt)
2348 return emitError("unexpected probe() as start of statement");
2349 if (parseProbe(result))
2350 return failure();
2351 break;
2352 case FIRToken::lp_rwprobe:
2353 if (isLeadingStmt)
2354 return emitError("unexpected rwprobe() as start of statement");
2355 if (parseRWProbe(result))
2356 return failure();
2357 break;
2358
2359 case FIRToken::langle_UInt:
2360 case FIRToken::langle_SInt: {
2361 // The '<' has already been consumed by the lexer, so we need to parse
2362 // the mandatory width and '>'.
2363 bool isSigned = getToken().is(FIRToken::langle_SInt);
2364 consumeToken();
2365 int32_t width;
2366 if (parseWidth(width))
2367 return failure();
2368
2369 // Now parse the '(' intLit ')' part.
2370 if (parseIntegerLiteralExp(result, isSigned, width))
2371 return failure();
2372 break;
2373 }
2374
2375 case FIRToken::lp_UInt:
2376 if (parseIntegerLiteralExp(result, /*isSigned=*/false))
2377 return failure();
2378 break;
2379 case FIRToken::lp_SInt:
2380 if (parseIntegerLiteralExp(result, /*isSigned=*/true))
2381 return failure();
2382 break;
2383 case FIRToken::lp_String: {
2384 if (requireFeature({3, 1, 0}, "Strings"))
2385 return failure();
2386 locationProcessor.setLoc(getToken().getLoc());
2387 consumeToken(FIRToken::lp_String);
2388 StringRef spelling;
2389 if (parseGetSpelling(spelling) ||
2390 parseToken(FIRToken::string,
2391 "expected string literal in String expression") ||
2392 parseToken(FIRToken::r_paren, "expected ')' in String expression"))
2393 return failure();
2394 auto attr = builder.getStringAttr(FIRToken::getStringValue(spelling));
2395 result = moduleContext.getCachedConstant<StringConstantOp>(
2396 builder, attr, builder.getType<StringType>(), attr);
2397 break;
2398 }
2399 case FIRToken::lp_Integer: {
2400 if (requireFeature({3, 1, 0}, "Integers"))
2401 return failure();
2402 locationProcessor.setLoc(getToken().getLoc());
2403 consumeToken(FIRToken::lp_Integer);
2404 APInt value;
2405 if (parseIntLit(value, "expected integer literal in Integer expression") ||
2406 parseToken(FIRToken::r_paren, "expected ')' in Integer expression"))
2407 return failure();
2408 APSInt apint(value, /*isUnsigned=*/false);
2409 result = moduleContext.getCachedConstant<FIntegerConstantOp>(
2410 builder, IntegerAttr::get(getContext(), apint),
2411 builder.getType<FIntegerType>(), apint);
2412 break;
2413 }
2414 case FIRToken::lp_Bool: {
2415 if (requireFeature({6, 0, 0}, "Bools"))
2416 return failure();
2417 locationProcessor.setLoc(getToken().getLoc());
2418 consumeToken(FIRToken::lp_Bool);
2419 bool value;
2420 if (consumeIf(FIRToken::kw_true))
2421 value = true;
2422 else if (consumeIf(FIRToken::kw_false))
2423 value = false;
2424 else
2425 return emitError("expected true or false in Bool expression");
2426 if (parseToken(FIRToken::r_paren, "expected ')' in Bool expression"))
2427 return failure();
2428 auto attr = builder.getBoolAttr(value);
2429 result = moduleContext.getCachedConstant<BoolConstantOp>(
2430 builder, attr, builder.getType<BoolType>(), value);
2431 break;
2432 }
2433 case FIRToken::lp_Double: {
2434 if (requireFeature({6, 0, 0}, "Doubles"))
2435 return failure();
2436 locationProcessor.setLoc(getToken().getLoc());
2437 consumeToken(FIRToken::lp_Double);
2438 auto spelling = getTokenSpelling();
2439 if (parseToken(FIRToken::floatingpoint,
2440 "expected floating point in Double expression") ||
2441 parseToken(FIRToken::r_paren, "expected ')' in Double expression"))
2442 return failure();
2443 // NaN, INF, exponent, hex, integer?
2444 // This uses `strtod` internally, FWIW. See `man 3 strtod`.
2445 double d;
2446 if (!llvm::to_float(spelling, d))
2447 return emitError("invalid double");
2448 auto attr = builder.getF64FloatAttr(d);
2449 result = moduleContext.getCachedConstant<DoubleConstantOp>(
2450 builder, attr, builder.getType<DoubleType>(), attr);
2451 break;
2452 }
2453 case FIRToken::lp_List:
2454 case FIRToken::langle_List: {
2455 if (requireFeature({4, 0, 0}, "Lists"))
2456 return failure();
2457 if (isLeadingStmt)
2458 return emitError("unexpected List<>() as start of statement");
2459 if (parseListExp(result))
2460 return failure();
2461 break;
2462 }
2463
2464 case FIRToken::kw_Option:
2465 case FIRToken::langle_Option:
2466 if (requireFeature(nextFIRVersion, "Options"))
2467 return failure();
2468 if (isLeadingStmt)
2469 return emitError("unexpected Option<>() as start of statement");
2470 if (parseOptionExp(result))
2471 return failure();
2472 break;
2473
2474 case FIRToken::lp_option_get_or_else:
2475 if (requireFeature(nextFIRVersion, "option get or else") ||
2476 parseOptionGetOrElseExp(result))
2477 return failure();
2478 break;
2479
2480 case FIRToken::lp_list_concat: {
2481 if (isLeadingStmt)
2482 return emitError("unexpected list_create() as start of statement");
2483 if (requireFeature({4, 0, 0}, "List concat") || parseListConcatExp(result))
2484 return failure();
2485 break;
2486 }
2487
2488 case FIRToken::lp_path:
2489 if (isLeadingStmt)
2490 return emitError("unexpected path() as start of statement");
2491 if (requireFeature({6, 0, 0}, "Paths") || parsePathExp(result))
2492 return failure();
2493 break;
2494
2495 case FIRToken::lp_intrinsic:
2496 if (requireFeature({4, 0, 0}, "generic intrinsics") ||
2497 parseIntrinsicExp(result))
2498 return failure();
2499 break;
2500
2501 case FIRToken::lp_cat:
2502 if (parseCatExp(result))
2503 return failure();
2504 break;
2505
2506 case FIRToken::lp_string_concat:
2507 if (parseStringConcatExp(result))
2508 return failure();
2509 break;
2510
2511 case FIRToken::lp_prop_eq:
2512 if (requireFeature({6, 0, 0}, "property equality") ||
2513 parsePropEqExp(result))
2514 return failure();
2515 break;
2516
2517 case FIRToken::lp_list_length:
2518 if (requireFeature(nextFIRVersion, "list length") ||
2519 parseListLengthExp(result))
2520 return failure();
2521 break;
2522
2523 case FIRToken::lp_list_contains:
2524 if (requireFeature(missingSpecFIRVersion, "list contains") ||
2525 parseListContainsExp(result))
2526 return failure();
2527 break;
2528
2529 case FIRToken::lp_unsafe_domain_cast:
2530 if (requireFeature(nextFIRVersion, "unsafe_domain_cast") ||
2531 parseUnsafeDomainCast(result))
2532 return failure();
2533 break;
2534 case FIRToken::lp_Unknown:
2535 if (requireFeature(nextFIRVersion, "unknown property expressions") ||
2536 parseUnknownProperty(result))
2537 return failure();
2538 break;
2539
2540 // Otherwise there are a bunch of keywords that are treated as identifiers
2541 // try them.
2542 case FIRToken::identifier: // exp ::= id
2543 case FIRToken::literal_identifier:
2544 case FIRToken::kw_UInt:
2545 case FIRToken::kw_SInt:
2546 case FIRToken::kw_String:
2547 case FIRToken::kw_Integer:
2548 case FIRToken::kw_Bool:
2549 case FIRToken::kw_Double:
2550 case FIRToken::kw_List:
2551 default: {
2552 StringRef name;
2553 auto loc = getToken().getLoc();
2554 SymbolValueEntry symtabEntry;
2555 if (parseId(name, message) ||
2556 moduleContext.lookupSymbolEntry(symtabEntry, name, loc))
2557 return failure();
2558
2559 // If we looked up a normal value, then we're done.
2560 if (!moduleContext.resolveSymbolEntry(result, symtabEntry, loc, false))
2561 break;
2562
2563 assert(isa<UnbundledID>(symtabEntry) && "should be an instance");
2564
2565 // Otherwise we referred to an implicitly bundled value. We *must* be in
2566 // the midst of processing a field ID reference or 'is invalid'. If not,
2567 // this is an error.
2568 if (isLeadingStmt && consumeIf(FIRToken::kw_is)) {
2569 if (parseToken(FIRToken::kw_invalid, "expected 'invalid'") ||
2570 parseOptionalInfo())
2571 return failure();
2572
2573 locationProcessor.setLoc(loc);
2574 // Invalidate all of the results of the bundled value.
2575 unsigned unbundledId = cast<UnbundledID>(symtabEntry) - 1;
2576 UnbundledValueEntry &ubEntry =
2577 moduleContext.getUnbundledEntry(unbundledId);
2578 for (auto elt : ubEntry)
2579 emitInvalidate(elt.second);
2580
2581 // Signify that we parsed the whole statement.
2582 result = Value();
2583 return success();
2584 }
2585
2586 // Handle the normal "instance.x" reference.
2587 StringRef fieldName;
2588 if (parseToken(FIRToken::period, "expected '.' in field reference") ||
2589 parseFieldId(fieldName, "expected field name") ||
2590 moduleContext.resolveSymbolEntry(result, symtabEntry, fieldName, loc))
2591 return failure();
2592 break;
2593 }
2594 }
2595 // Don't add code here, the common cases of these switch statements will be
2596 // merged. This allows for fixing up primops after they have been created.
2597 switch (kind) {
2598 case FIRToken::lp_shr:
2599 // For FIRRTL versions earlier than 4.0.0, insert pad(_, 1) around any
2600 // unsigned shr This ensures the minimum width is 1 (but can be greater)
2601 if (version < FIRVersion(4, 0, 0) && type_isa<UIntType>(result.getType()))
2602 result = PadPrimOp::create(builder, result, 1);
2603 break;
2604 default:
2605 break;
2606 }
2607
2608 return parseOptionalExpPostscript(result);
2609}
2610
2611/// Parse the postfix productions of expression after the leading expression
2612/// has been parsed.
2613///
2614/// exp ::= exp '.' fieldId
2615/// ::= exp '[' intLit ']'
2616/// XX ::= exp '.' DoubleLit // TODO Workaround for #470
2617/// ::= exp '[' exp ']'
2618ParseResult FIRStmtParser::parseOptionalExpPostscript(Value &result,
2619 bool allowDynamic) {
2620
2621 // Handle postfix expressions.
2622 while (true) {
2623 // Subfield: exp ::= exp '.' fieldId
2624 if (consumeIf(FIRToken::period)) {
2625 if (parsePostFixFieldId(result))
2626 return failure();
2627
2628 continue;
2629 }
2630
2631 // Subindex: exp ::= exp '[' intLit ']' | exp '[' exp ']'
2632 if (consumeIf(FIRToken::l_square)) {
2633 if (getToken().isAny(FIRToken::integer, FIRToken::string)) {
2634 if (parsePostFixIntSubscript(result))
2635 return failure();
2636 continue;
2637 }
2638 if (!allowDynamic)
2639 return emitError("subaccess not allowed here");
2640 if (parsePostFixDynamicSubscript(result))
2641 return failure();
2642
2643 continue;
2644 }
2645
2646 return success();
2647 }
2648}
2649
2650template <typename subop>
2651FailureOr<Value>
2652FIRStmtParser::emitCachedSubAccess(Value base, unsigned indexNo, SMLoc loc) {
2653 // Check if we already have created this Subindex op.
2654 auto &value = moduleContext.getCachedSubaccess(base, indexNo);
2655 if (value)
2656 return value;
2657
2658 // Make sure the field name matches up with the input value's type and
2659 // compute the result type for the expression.
2660 auto baseType = cast<FIRRTLType>(base.getType());
2661 auto resultType = subop::inferReturnType(baseType, indexNo, {});
2662 if (!resultType) {
2663 // Emit the error at the right location. translateLocation is expensive.
2664 (void)subop::inferReturnType(baseType, indexNo, translateLocation(loc));
2665 return failure();
2666 }
2667
2668 // Create the result operation, inserting at the location of the declaration.
2669 // This will cache the subfield operation for further uses.
2670 locationProcessor.setLoc(loc);
2671 OpBuilder::InsertionGuard guard(builder);
2672 builder.setInsertionPointAfterValue(base);
2673 auto op = subop::create(builder, resultType, base, indexNo);
2674
2675 // Insert the newly created operation into the cache.
2676 return value = op.getResult();
2677}
2678
2679/// exp ::= exp '.' fieldId
2680///
2681/// The "exp '.'" part of the production has already been parsed.
2682///
2683ParseResult FIRStmtParser::parsePostFixFieldId(Value &result) {
2684 auto loc = getToken().getLoc();
2685 SmallVector<StringRef, 3> fields;
2686 if (parseFieldIdSeq(fields, "expected field name"))
2687 return failure();
2688 for (auto fieldName : fields) {
2689 std::optional<unsigned> indexV;
2690 auto type = result.getType();
2691 if (auto refTy = type_dyn_cast<RefType>(type))
2692 type = refTy.getType();
2693 if (auto bundle = type_dyn_cast<BundleType>(type))
2694 indexV = bundle.getElementIndex(fieldName);
2695 else if (auto bundle = type_dyn_cast<OpenBundleType>(type))
2696 indexV = bundle.getElementIndex(fieldName);
2697 else if (auto klass = type_dyn_cast<ClassType>(type))
2698 indexV = klass.getElementIndex(fieldName);
2699 else if (auto domain = type_dyn_cast<DomainType>(type))
2700 indexV = domain.getFieldIndex(fieldName);
2701 else
2702 return emitError(loc,
2703 "subfield requires bundle, object, or domain operand ");
2704 if (!indexV)
2705 return emitError(loc, "unknown field '" + fieldName + "' in type ")
2706 << result.getType();
2707 auto indexNo = *indexV;
2708
2709 FailureOr<Value> subResult;
2710 if (type_isa<RefType>(result.getType()))
2711 subResult = emitCachedSubAccess<RefSubOp>(result, indexNo, loc);
2712 else if (type_isa<ClassType>(type))
2713 subResult = emitCachedSubAccess<ObjectSubfieldOp>(result, indexNo, loc);
2714 else if (type_isa<DomainType>(type))
2715 subResult = emitCachedSubAccess<DomainSubfieldOp>(result, indexNo, loc);
2716 else if (type_isa<BundleType>(type))
2717 subResult = emitCachedSubAccess<SubfieldOp>(result, indexNo, loc);
2718 else
2719 subResult = emitCachedSubAccess<OpenSubfieldOp>(result, indexNo, loc);
2720
2721 if (failed(subResult))
2722 return failure();
2723 result = *subResult;
2724 }
2725 return success();
2726}
2727
2728/// exp ::= exp '[' intLit ']'
2729///
2730/// The "exp '['" part of the production has already been parsed.
2731///
2732ParseResult FIRStmtParser::parsePostFixIntSubscript(Value &result) {
2733 auto loc = getToken().getLoc();
2734 int32_t indexNo;
2735 if (parseIntLit(indexNo, "expected index") ||
2736 parseToken(FIRToken::r_square, "expected ']'"))
2737 return failure();
2738
2739 if (indexNo < 0)
2740 return emitError(loc, "invalid index specifier"), failure();
2741
2742 FailureOr<Value> subResult;
2743 if (type_isa<RefType>(result.getType()))
2744 subResult = emitCachedSubAccess<RefSubOp>(result, indexNo, loc);
2745 else if (type_isa<FVectorType>(result.getType()))
2746 subResult = emitCachedSubAccess<SubindexOp>(result, indexNo, loc);
2747 else
2748 subResult = emitCachedSubAccess<OpenSubindexOp>(result, indexNo, loc);
2749
2750 if (failed(subResult))
2751 return failure();
2752 result = *subResult;
2753 return success();
2754}
2755
2756/// exp ::= exp '[' exp ']'
2757///
2758/// The "exp '['" part of the production has already been parsed.
2759///
2760ParseResult FIRStmtParser::parsePostFixDynamicSubscript(Value &result) {
2761 auto loc = getToken().getLoc();
2762 Value index;
2763 if (parseExp(index, "expected subscript index expression") ||
2764 parseToken(FIRToken::r_square, "expected ']' in subscript"))
2765 return failure();
2766
2767 // If the index expression is a flip type, strip it off.
2768 auto indexType = type_dyn_cast<FIRRTLBaseType>(index.getType());
2769 if (!indexType)
2770 return emitError("expected base type for index expression");
2771 indexType = indexType.getPassiveType();
2772 locationProcessor.setLoc(loc);
2773
2774 // Make sure the index expression is valid and compute the result type for the
2775 // expression.
2776 auto resultType =
2777 SubaccessOp::inferReturnType(result.getType(), index.getType(), {});
2778 if (!resultType) {
2779 // Emit the error at the right location. translateLocation is expensive.
2780 (void)SubaccessOp::inferReturnType(result.getType(), index.getType(),
2781 translateLocation(loc));
2782 return failure();
2783 }
2784
2785 // Create the result operation.
2786 auto op = SubaccessOp::create(builder, resultType, result, index);
2787 result = op.getResult();
2788 return success();
2789}
2790
2791/// integer-literal-exp ::= 'UInt' optional-width '(' intLit ')'
2792/// ::= 'SInt' optional-width '(' intLit ')'
2793///
2794/// If allocatedWidth is provided, it means the width was already parsed
2795/// (e.g., from a langle_UInt token) and should be used instead of parsing
2796/// it from the token stream.
2797ParseResult
2798FIRStmtParser::parseIntegerLiteralExp(Value &result, bool isSigned,
2799 std::optional<int32_t> allocatedWidth) {
2800 auto loc = getToken().getLoc();
2801
2802 // Determine if '(' was already consumed by the lexer.
2803 bool hasLParen = getToken().isAny(FIRToken::lp_UInt, FIRToken::lp_SInt);
2804 if (hasLParen)
2805 consumeToken();
2806
2807 // Parse a width specifier if not already provided.
2808 int32_t width = allocatedWidth.value_or(-1);
2809 APInt value;
2810
2811 // If we consumed an lp_ token, the '(' was already consumed by the lexer.
2812 // Otherwise, we need to parse it.
2813 if (!hasLParen &&
2814 parseToken(FIRToken::l_paren, "expected '(' in integer expression"))
2815 return failure();
2816
2817 if (parseIntLit(value, "expected integer value") ||
2818 parseToken(FIRToken::r_paren, "expected ')' in integer expression"))
2819 return failure();
2820
2821 // Construct an integer attribute of the right width.
2822 // Literals are parsed as 'const' types.
2823 auto type = IntType::get(builder.getContext(), isSigned, width, true);
2824
2825 IntegerType::SignednessSemantics signedness =
2826 isSigned ? IntegerType::Signed : IntegerType::Unsigned;
2827 if (width == 0) {
2828 if (!value.isZero())
2829 return emitError(loc, "zero bit constant must be zero");
2830 value = value.trunc(0);
2831 } else if (width != -1) {
2832 // Convert to the type's width, checking value fits in destination width.
2833 bool valueFits = isSigned ? value.isSignedIntN(width) : value.isIntN(width);
2834 if (!valueFits)
2835 return emitError(loc, "initializer too wide for declared width");
2836 value = isSigned ? value.sextOrTrunc(width) : value.zextOrTrunc(width);
2837 }
2838
2839 Type attrType =
2840 IntegerType::get(type.getContext(), value.getBitWidth(), signedness);
2841 auto attr = builder.getIntegerAttr(attrType, value);
2842
2843 locationProcessor.setLoc(loc);
2844 result = moduleContext.getCachedConstant(builder, attr, type, attr);
2845 return success();
2846}
2847
2848/// list-exp ::= list-type '(' exp* ')'
2849ParseResult FIRStmtParser::parseListExp(Value &result) {
2850 auto loc = getToken().getLoc();
2851 bool hasLAngle = getToken().is(FIRToken::langle_List);
2852 bool hasLParen = getToken().is(FIRToken::lp_List);
2853 consumeToken();
2854
2855 PropertyType elementType;
2856 // If we consumed a langle_ token, the '<' was already consumed by the lexer.
2857 if (!hasLAngle && parseToken(FIRToken::less, "expected '<' in List type"))
2858 return failure();
2859
2860 if (parsePropertyType(elementType, "expected List element type") ||
2861 parseToken(FIRToken::greater, "expected '>' in List type"))
2862 return failure();
2863
2864 auto listType = ListType::get(getContext(), elementType);
2865
2866 // If we consumed an lp_ token, the '(' was already consumed by the lexer.
2867 if (!hasLParen &&
2868 parseToken(FIRToken::l_paren, "expected '(' in List expression"))
2869 return failure();
2870
2871 SmallVector<Value, 3> operands;
2872 if (parseListUntil(FIRToken::r_paren, [&]() -> ParseResult {
2873 Value operand;
2874 locationProcessor.setLoc(loc);
2875 if (parseExp(operand, "expected expression in List expression"))
2876 return failure();
2877
2878 operand = emitImplicitAnyRefCast(operand, elementType);
2879 if (operand.getType() != elementType)
2880 return emitError(loc, "unexpected expression of type ")
2881 << operand.getType() << " in List expression of type "
2882 << elementType;
2883
2884 operands.push_back(operand);
2885 return success();
2886 }))
2887 return failure();
2888
2889 locationProcessor.setLoc(loc);
2890 result = ListCreateOp::create(builder, listType, operands);
2891 return success();
2892}
2893
2894/// option-exp ::= option-type '(' exp? ')'
2895// NOLINTNEXTLINE(misc-no-recursion)
2896ParseResult FIRStmtParser::parseOptionExp(Value &result) {
2897 auto loc = getToken().getLoc();
2898 FIRRTLType type;
2899 if (parseOptionType(type) ||
2900 parseToken(FIRToken::l_paren, "expected '(' in Option expression"))
2901 return failure();
2902
2903 Value value;
2904 if (!getToken().is(FIRToken::r_paren)) {
2905 if (parseExp(value, "expected expression in Option expression"))
2906 return failure();
2907 auto elementType = cast<OptionType>(type).getElementType();
2908 locationProcessor.setLoc(loc);
2909 value = emitImplicitAnyRefCast(value, elementType);
2910 if (value.getType() != elementType)
2911 return emitError(loc, "unexpected expression of type ")
2912 << value.getType() << " in Option expression of type "
2913 << elementType;
2914 }
2915 if (parseToken(FIRToken::r_paren, "expected ')' in Option expression"))
2916 return failure();
2917
2918 locationProcessor.setLoc(loc);
2919 result = OptionCreateOp::create(builder, type, value);
2920 return success();
2921}
2922
2923/// option-get-or-else-exp ::= 'option_get_or_else' '(' exp ',' exp ')'
2924// NOLINTNEXTLINE(misc-no-recursion)
2925ParseResult FIRStmtParser::parseOptionGetOrElseExp(Value &result) {
2926 consumeToken(FIRToken::lp_option_get_or_else);
2927 auto loc = getToken().getLoc();
2928 Value option, defaultValue;
2929 locationProcessor.setLoc(loc);
2930 if (parseExp(option, "expected option expression in option_get_or_else") ||
2931 parseToken(FIRToken::comma, "expected ','") ||
2932 parseExp(defaultValue,
2933 "expected default expression in option_get_or_else") ||
2934 parseToken(FIRToken::r_paren, "expected ')'"))
2935 return failure();
2936
2937 auto optionType = dyn_cast<OptionType>(option.getType());
2938 if (!optionType)
2939 return emitError(loc,
2940 "first operand of option_get_or_else must be an Option");
2941
2942 auto elementType = optionType.getElementType();
2943 locationProcessor.setLoc(loc);
2944 defaultValue = emitImplicitAnyRefCast(defaultValue, elementType);
2945 if (defaultValue.getType() != elementType)
2946 return emitError(loc, "option_get_or_else default type ")
2947 << defaultValue.getType() << " does not match option element type "
2948 << elementType;
2949
2950 locationProcessor.setLoc(loc);
2951 result = OptionGetOrElseOp::create(builder, option, defaultValue);
2952 return success();
2953}
2954
2955/// list-concat-exp ::= 'list_concat' '(' exp* ')'
2956ParseResult FIRStmtParser::parseListConcatExp(Value &result) {
2957 consumeToken(FIRToken::lp_list_concat);
2958
2959 auto loc = getToken().getLoc();
2960 ListType type;
2961 SmallVector<Value, 3> operands;
2962 if (parseListUntil(FIRToken::r_paren, [&]() -> ParseResult {
2963 Value operand;
2964 locationProcessor.setLoc(loc);
2965 if (parseExp(operand, "expected expression in List concat expression"))
2966 return failure();
2967
2968 if (!type_isa<ListType>(operand.getType()))
2969 return emitError(loc, "unexpected expression of type ")
2970 << operand.getType() << " in List concat expression";
2971
2972 if (!type)
2973 type = type_cast<ListType>(operand.getType());
2974
2975 if (operand.getType() != type)
2976 return emitError(loc, "unexpected expression of type ")
2977 << operand.getType() << " in List concat expression of type "
2978 << type;
2979
2980 operands.push_back(operand);
2981 return success();
2982 }))
2983 return failure();
2984
2985 if (operands.empty())
2986 return emitError(loc, "need at least one List to concatenate");
2987
2988 locationProcessor.setLoc(loc);
2989 result = ListConcatOp::create(builder, type, operands);
2990 return success();
2991}
2992
2993/// cat-exp ::= 'cat(' exp* ')'
2994ParseResult FIRStmtParser::parseCatExp(Value &result) {
2995 consumeToken(FIRToken::lp_cat);
2996
2997 auto loc = getToken().getLoc();
2998 SmallVector<Value, 3> operands;
2999 std::optional<bool> isSigned;
3000 if (parseListUntil(FIRToken::r_paren, [&]() -> ParseResult {
3001 Value operand;
3002 locationProcessor.setLoc(loc);
3003 auto operandLoc = getToken().getLoc();
3004 if (parseExp(operand, "expected expression in cat expression"))
3005 return failure();
3006 if (!type_isa<IntType>(operand.getType())) {
3007 auto diag = emitError(loc, "all operands must be Int type");
3008 diag.attachNote(translateLocation(operandLoc))
3009 << "non-integer operand is here";
3010 return failure();
3011 }
3012 if (!isSigned)
3013 isSigned = type_isa<SIntType>(operand.getType());
3014 else if (type_isa<SIntType>(operand.getType()) != *isSigned) {
3015 auto diag = emitError(loc, "all operands must have same signedness");
3016 diag.attachNote(translateLocation(operandLoc))
3017 << "operand with different signedness is here";
3018 return failure();
3019 }
3020
3021 operands.push_back(operand);
3022 return success();
3023 }))
3024 return failure();
3025
3026 if (operands.size() != 2) {
3027 if (requireFeature({6, 0, 0}, "variadic cat", loc))
3028 return failure();
3029 }
3030
3031 locationProcessor.setLoc(loc);
3032 result = CatPrimOp::create(builder, operands);
3033 return success();
3034}
3035
3036/// string_concat-exp ::= 'string_concat(' exp* ')'
3037ParseResult FIRStmtParser::parseStringConcatExp(Value &result) {
3038 consumeToken(FIRToken::lp_string_concat);
3039
3040 auto loc = getToken().getLoc();
3041 SmallVector<Value, 3> operands;
3042 if (parseListUntil(FIRToken::r_paren, [&]() -> ParseResult {
3043 Value operand;
3044 locationProcessor.setLoc(loc);
3045 if (parseExp(operand,
3046 "expected expression in string_concat expression"))
3047 return failure();
3048 if (!type_isa<StringType>(operand.getType()))
3049 return emitError(loc, "all operands must be String type");
3050 operands.push_back(operand);
3051 return success();
3052 }))
3053 return failure();
3054
3055 if (operands.empty())
3056 return emitError(loc, "need at least one String to concatenate");
3057
3058 locationProcessor.setLoc(loc);
3059 auto type = StringType::get(builder.getContext());
3060 result = builder.create<StringConcatOp>(type, operands);
3061 return success();
3062}
3063
3064/// prop_eq-exp ::= 'prop_eq(' expr ',' expr ')'
3065ParseResult FIRStmtParser::parsePropEqExp(Value &result) {
3066 consumeToken(FIRToken::lp_prop_eq);
3067
3068 auto loc = getToken().getLoc();
3069 Value lhs, rhs;
3070 locationProcessor.setLoc(loc);
3071 if (parseExp(lhs, "expected lhs expression in prop_eq expression") ||
3072 parseToken(FIRToken::comma, "expected ','") ||
3073 parseExp(rhs, "expected rhs expression in prop_eq expression") ||
3074 parseToken(FIRToken::r_paren, "expected ')'"))
3075 return failure();
3076
3077 auto isValidType = [](Type t) {
3079 t);
3080 };
3081 if (!isValidType(lhs.getType()))
3082 return emitError(
3083 loc,
3084 "lhs of prop_eq must be String, Bool, Integer, Inst, or AnyRef type");
3085 if (!isValidType(rhs.getType()))
3086 return emitError(
3087 loc,
3088 "rhs of prop_eq must be String, Bool, Integer, Inst, or AnyRef type");
3089 if (lhs.getType() != rhs.getType())
3090 return emitError(loc, "prop_eq operands must have the same type");
3091 if (type_isa<ClassType, AnyRefType>(lhs.getType()) &&
3092 requireFeature(nextFIRVersion,
3093 "property equality comparisons with AnyRef or Class types",
3094 loc))
3095 return failure();
3096
3097 locationProcessor.setLoc(loc);
3098 result = PropEqOp::create(builder, lhs, rhs);
3099 return success();
3100}
3101
3102/// list-length-exp ::= 'list_length' '(' exp ')'
3103// NOLINTNEXTLINE(misc-no-recursion)
3104ParseResult FIRStmtParser::parseListLengthExp(Value &result) {
3105 consumeToken(FIRToken::lp_list_length);
3106
3107 auto loc = getToken().getLoc();
3108 Value list;
3109 locationProcessor.setLoc(loc);
3110 if (parseExp(list, "expected list expression in list_length expression") ||
3111 parseToken(FIRToken::r_paren, "expected ')'"))
3112 return failure();
3113
3114 if (!isa<ListType>(list.getType()))
3115 return emitError(loc, "operand of list_length must be a List");
3116
3117 locationProcessor.setLoc(loc);
3118 result = ListLengthOp::create(builder, list);
3119 return success();
3120}
3121
3122/// list-contains-exp ::= 'list_contains' '(' exp ',' exp ')'
3123ParseResult FIRStmtParser::parseListContainsExp(Value &result) {
3124 consumeToken(FIRToken::lp_list_contains);
3125
3126 auto loc = getToken().getLoc();
3127 Value list, element;
3128 locationProcessor.setLoc(loc);
3129 if (parseExp(list, "expected list expression in list_contains expression") ||
3130 parseToken(FIRToken::comma, "expected ','") ||
3131 parseExp(element,
3132 "expected element expression in list_contains expression") ||
3133 parseToken(FIRToken::r_paren, "expected ')'"))
3134 return failure();
3135
3136 auto listType = dyn_cast<ListType>(list.getType());
3137 if (!listType)
3138 return emitError(loc, "first operand of list_contains must be a List");
3139
3140 auto elementType = listType.getElementType();
3141 locationProcessor.setLoc(loc);
3142 element = emitImplicitAnyRefCast(element, elementType);
3143 if (element.getType() != elementType)
3144 return emitError(loc, "list_contains element type ")
3145 << element.getType() << " does not match list element type "
3146 << elementType;
3147
3148 if (!isa<StringType, FIntegerType, BoolType, ClassType, AnyRefType>(
3149 elementType))
3150 return emitError(loc, "list_contains does not support elements of type ")
3151 << elementType;
3152
3153 locationProcessor.setLoc(loc);
3154 result = ListContainsOp::create(builder, list, element);
3155 return success();
3156}
3157
3158ParseResult FIRStmtParser::parseUnsafeDomainCast(Value &result) {
3159 consumeToken(FIRToken::lp_unsafe_domain_cast);
3160
3161 auto loc = getToken().getLoc();
3162 Value input;
3163 if (parseExp(input, "expected input"))
3164 return failure();
3165
3166 SmallVector<Value> domains;
3167 if (consumeIf(FIRToken::comma)) {
3168 if (parseListUntil(FIRToken::r_paren, [&]() -> ParseResult {
3169 Value domain;
3170 if (parseExp(domain, "expected domain"))
3171 return failure();
3172 domains.push_back(domain);
3173 return success();
3174 }))
3175 return failure();
3176 } else if (parseToken(FIRToken::r_paren, "expected closing parenthesis")) {
3177 return failure();
3178 }
3179
3180 locationProcessor.setLoc(loc);
3181 result = UnsafeDomainCastOp::create(builder, input, domains);
3182 return success();
3183}
3184
3185ParseResult FIRStmtParser::parseUnknownProperty(Value &result) {
3186 auto loc = getToken().getLoc();
3187 consumeToken(FIRToken::lp_Unknown);
3188 // The '(' has already been consumed by the lexer.
3189
3190 PropertyType type;
3191 if (parsePropertyType(type, "expected property type") ||
3192 parseToken(FIRToken::r_paren, "expected ')' in unknown property"))
3193 return failure();
3194
3195 locationProcessor.setLoc(loc);
3196 result = UnknownValueOp::create(builder, type);
3197 return success();
3198}
3199
3200/// The .fir grammar has the annoying property where:
3201/// 1) some statements start with keywords
3202/// 2) some start with an expression
3203/// 3) it allows the 'reference' expression to either be an identifier or a
3204/// keyword.
3205///
3206/// One example of this is something like, where this is not a register decl:
3207/// reg <- thing
3208///
3209/// Solving this requires lookahead to the second token. We handle it by
3210/// factoring the lookahead inline into the code to keep the parser fast.
3211///
3212/// As such, statements that start with a leading keyword call this method to
3213/// check to see if the keyword they consumed was actually the start of an
3214/// expression. If so, they parse the expression-based statement and return the
3215/// parser result. If not, they return None and the statement is parsed like
3216/// normal.
3217std::optional<ParseResult>
3218FIRStmtParser::parseExpWithLeadingKeyword(FIRToken keyword) {
3219 switch (getToken().getKind()) {
3220 default:
3221 // This isn't part of an expression, and isn't part of a statement.
3222 return std::nullopt;
3223
3224 case FIRToken::period: // exp `.` identifier
3225 case FIRToken::l_square: // exp `[` index `]`
3226 case FIRToken::kw_is: // exp is invalid
3227 case FIRToken::less_equal: // exp <= thing
3228 break;
3229 }
3230
3231 Value lhs;
3232 SymbolValueEntry symtabEntry;
3233 auto loc = keyword.getLoc();
3234
3235 if (moduleContext.lookupSymbolEntry(symtabEntry, keyword.getSpelling(), loc))
3236 return ParseResult(failure());
3237
3238 // If we have a '.', we might have a symbol or an expanded port. If we
3239 // resolve to a symbol, use that, otherwise check for expanded bundles of
3240 // other ops.
3241 // Non '.' ops take the plain symbol path.
3242 if (moduleContext.resolveSymbolEntry(lhs, symtabEntry, loc, false)) {
3243 // Ok if the base name didn't resolve by itself, it might be part of an
3244 // expanded dot reference. That doesn't work then we fail.
3245 if (!consumeIf(FIRToken::period))
3246 return ParseResult(failure());
3247
3248 StringRef fieldName;
3249 if (parseFieldId(fieldName, "expected field name") ||
3250 moduleContext.resolveSymbolEntry(lhs, symtabEntry, fieldName, loc))
3251 return ParseResult(failure());
3252 }
3253
3254 // Parse any further trailing things like "mem.x.y".
3255 if (parseOptionalExpPostscript(lhs))
3256 return ParseResult(failure());
3257
3258 return parseLeadingExpStmt(lhs);
3259}
3260//===-----------------------------
3261// FIRStmtParser Statement Parsing
3262
3263/// simple_stmt_block ::= simple_stmt*
3264ParseResult FIRStmtParser::parseSimpleStmtBlock(unsigned indent) {
3265 while (true) {
3266 // The outer level parser can handle these tokens.
3267 if (getToken().isAny(FIRToken::eof, FIRToken::error))
3268 return success();
3269
3270 auto subIndent = getIndentation();
3271 if (!subIndent.has_value())
3272 return emitError("expected statement to be on its own line"), failure();
3273
3274 if (*subIndent <= indent)
3275 return success();
3276
3277 // Let the statement parser handle this.
3278 if (parseSimpleStmt(*subIndent))
3279 return failure();
3280 }
3281}
3282
3283ParseResult FIRStmtParser::parseSimpleStmt(unsigned stmtIndent) {
3284 locationProcessor.startStatement();
3285 auto result = parseSimpleStmtImpl(stmtIndent);
3286 locationProcessor.endStatement(*this);
3287 return result;
3288}
3289
3290/// simple_stmt ::= stmt
3291///
3292/// stmt ::= attach
3293/// ::= memport
3294/// ::= printf
3295/// ::= skip
3296/// ::= stop
3297/// ::= when
3298/// ::= leading-exp-stmt
3299/// ::= define
3300/// ::= propassert
3301/// ::= propassign
3302///
3303/// stmt ::= instance
3304/// ::= cmem | smem | mem
3305/// ::= node | wire
3306/// ::= register
3307/// ::= contract
3308///
3309ParseResult FIRStmtParser::parseSimpleStmtImpl(unsigned stmtIndent) {
3310 auto kind = getToken().getKind();
3311 /// Massage the kind based on the FIRRTL Version.
3312 switch (kind) {
3313 case FIRToken::kw_invalidate:
3314 case FIRToken::kw_connect:
3315 case FIRToken::kw_regreset:
3316 /// The "invalidate", "connect", and "regreset" keywords were added
3317 /// in 3.0.0.
3318 if (version < FIRVersion(3, 0, 0))
3319 kind = FIRToken::identifier;
3320 break;
3321 default:
3322 break;
3323 };
3324 switch (kind) {
3325 // Statements.
3326 case FIRToken::kw_attach:
3327 return parseAttach();
3328 case FIRToken::kw_infer:
3329 return parseMemPort(MemDirAttr::Infer);
3330 case FIRToken::kw_read:
3331 return parseMemPort(MemDirAttr::Read);
3332 case FIRToken::kw_write:
3333 return parseMemPort(MemDirAttr::Write);
3334 case FIRToken::kw_rdwr:
3335 return parseMemPort(MemDirAttr::ReadWrite);
3336 case FIRToken::kw_connect:
3337 return parseConnect();
3338 case FIRToken::kw_propassert:
3339 if (requireFeature({6, 0, 0}, "property assertions"))
3340 return failure();
3341 return parsePropAssert();
3342 case FIRToken::kw_propassign:
3343 if (requireFeature({3, 1, 0}, "properties"))
3344 return failure();
3345 return parsePropAssign();
3346 case FIRToken::kw_invalidate:
3347 return parseInvalidate();
3348 case FIRToken::lp_printf:
3349 return parsePrintf();
3350 case FIRToken::lp_fprintf:
3351 return parseFPrintf();
3352 case FIRToken::lp_fflush:
3353 return parseFFlush();
3354 case FIRToken::kw_skip:
3355 return parseSkip();
3356 case FIRToken::lp_stop:
3357 return parseStop();
3358 case FIRToken::lp_assert:
3359 return parseAssert();
3360 case FIRToken::lp_assume:
3361 return parseAssume();
3362 case FIRToken::lp_cover:
3363 return parseCover();
3364 case FIRToken::kw_when:
3365 return parseWhen(stmtIndent);
3366 case FIRToken::kw_match:
3367 return parseMatch(stmtIndent);
3368 case FIRToken::kw_domain:
3369 // In module context, 'domain' is only valid for domain instantiation
3370 return parseDomainInstantiation();
3371 case FIRToken::kw_domain_define:
3372 return parseDomainDefine();
3373 case FIRToken::kw_define:
3374 return parseRefDefine();
3375 case FIRToken::lp_force:
3376 return parseRefForce();
3377 case FIRToken::lp_force_initial:
3378 return parseRefForceInitial();
3379 case FIRToken::lp_release:
3380 return parseRefRelease();
3381 case FIRToken::lp_release_initial:
3382 return parseRefReleaseInitial();
3383 case FIRToken::kw_group:
3384 if (requireFeature({3, 2, 0}, "optional groups") ||
3385 removedFeature({3, 3, 0}, "optional groups"))
3386 return failure();
3387 return parseLayerBlockOrGroup(stmtIndent);
3388 case FIRToken::kw_layerblock:
3389 if (requireFeature({3, 3, 0}, "layers"))
3390 return failure();
3391 return parseLayerBlockOrGroup(stmtIndent);
3392 case FIRToken::lp_intrinsic:
3393 if (requireFeature({4, 0, 0}, "generic intrinsics"))
3394 return failure();
3395 return parseIntrinsicStmt();
3396 default: {
3397 // Statement productions that start with an expression.
3398 Value lhs;
3399 if (parseExpLeadingStmt(lhs, "unexpected token in module"))
3400 return failure();
3401 // We use parseExp in a special mode that can complete the entire stmt
3402 // at once in unusual cases. If this happened, then we are done.
3403 if (!lhs)
3404 return success();
3405
3406 return parseLeadingExpStmt(lhs);
3407 }
3408
3409 // Declarations
3410 case FIRToken::kw_inst:
3411 return parseInstance();
3412 case FIRToken::kw_instchoice:
3413 return parseInstanceChoice();
3414 case FIRToken::kw_object:
3415 return parseObject();
3416 case FIRToken::kw_cmem:
3417 return parseCombMem();
3418 case FIRToken::kw_smem:
3419 return parseSeqMem();
3420 case FIRToken::kw_mem:
3421 return parseMem(stmtIndent);
3422 case FIRToken::kw_node:
3423 return parseNode();
3424 case FIRToken::kw_wire:
3425 return parseWire();
3426 case FIRToken::kw_reg:
3427 return parseRegister(stmtIndent);
3428 case FIRToken::kw_regreset:
3429 return parseRegisterWithReset();
3430 case FIRToken::kw_contract:
3431 return parseContract(stmtIndent);
3432 }
3433}
3434
3435ParseResult FIRStmtParser::parseSubBlock(Block &blockToInsertInto,
3436 unsigned indent,
3437 SymbolRefAttr layerSym) {
3438 // Declarations within the suite are scoped to within the suite.
3439 auto suiteScope = std::make_unique<FIRModuleContext::ContextScope>(
3440 moduleContext, &blockToInsertInto);
3441
3442 // After parsing the when region, we can release any new entries in
3443 // unbundledValues since the symbol table entries that refer to them will be
3444 // gone.
3445 UnbundledValueRestorer x(moduleContext.unbundledValues);
3446
3447 // We parse the substatements into their own parser, so they get inserted
3448 // into the specified 'when' region.
3449 auto subParser = std::make_unique<FIRStmtParser>(
3450 blockToInsertInto, moduleContext, innerSymFixups, circuitSymTbl, version,
3451 layerSym);
3452
3453 // Figure out whether the body is a single statement or a nested one.
3454 auto stmtIndent = getIndentation();
3455
3456 // Parsing a single statment is straightforward.
3457 if (!stmtIndent.has_value())
3458 return subParser->parseSimpleStmt(indent);
3459
3460 if (*stmtIndent <= indent)
3461 return emitError("statement must be indented more than previous statement"),
3462 failure();
3463
3464 // Parse a block of statements that are indented more than the when.
3465 return subParser->parseSimpleStmtBlock(indent);
3466}
3467
3468/// attach ::= 'attach' '(' exp+ ')' info?
3469ParseResult FIRStmtParser::parseAttach() {
3470 auto startTok = consumeToken(FIRToken::kw_attach);
3471
3472 // If this was actually the start of a connect or something else handle that.
3473 if (auto isExpr = parseExpWithLeadingKeyword(startTok))
3474 return *isExpr;
3475
3476 if (parseToken(FIRToken::l_paren, "expected '(' after attach"))
3477 return failure();
3478
3479 SmallVector<Value, 4> operands;
3480 operands.push_back({});
3481 if (parseExp(operands.back(), "expected operand in attach"))
3482 return failure();
3483
3484 while (consumeIf(FIRToken::comma)) {
3485 operands.push_back({});
3486 if (parseExp(operands.back(), "expected operand in attach"))
3487 return failure();
3488 }
3489 if (parseToken(FIRToken::r_paren, "expected close paren"))
3490 return failure();
3491
3492 if (parseOptionalInfo())
3493 return failure();
3494
3495 locationProcessor.setLoc(startTok.getLoc());
3496 AttachOp::create(builder, operands);
3497 return success();
3498}
3499
3500/// stmt ::= mdir 'mport' id '=' id '[' exp ']' exp info?
3501/// mdir ::= 'infer' | 'read' | 'write' | 'rdwr'
3502///
3503ParseResult FIRStmtParser::parseMemPort(MemDirAttr direction) {
3504 auto startTok = consumeToken();
3505 auto startLoc = startTok.getLoc();
3506
3507 // If this was actually the start of a connect or something else handle
3508 // that.
3509 if (auto isExpr = parseExpWithLeadingKeyword(startTok))
3510 return *isExpr;
3511
3512 StringRef id;
3513 StringRef memName;
3514 SymbolValueEntry memorySym;
3515 Value memory, indexExp, clock;
3516 if (parseToken(FIRToken::kw_mport, "expected 'mport' in memory port") ||
3517 parseId(id, "expected result name") ||
3518 parseToken(FIRToken::equal, "expected '=' in memory port") ||
3519 parseId(memName, "expected memory name") ||
3520 moduleContext.lookupSymbolEntry(memorySym, memName, startLoc) ||
3521 moduleContext.resolveSymbolEntry(memory, memorySym, startLoc) ||
3522 parseToken(FIRToken::l_square, "expected '[' in memory port") ||
3523 parseExp(indexExp, "expected index expression") ||
3524 parseToken(FIRToken::r_square, "expected ']' in memory port") ||
3525 parseToken(FIRToken::comma, "expected ','") ||
3526 parseExp(clock, "expected clock expression") || parseOptionalInfo())
3527 return failure();
3528
3529 auto memVType = type_dyn_cast<CMemoryType>(memory.getType());
3530 if (!memVType)
3531 return emitError(startLoc,
3532 "memory port should have behavioral memory type");
3533 auto resultType = memVType.getElementType();
3534
3535 ArrayAttr annotations = getConstants().emptyArrayAttr;
3536 locationProcessor.setLoc(startLoc);
3537
3538 // Create the memory port at the location of the cmemory.
3539 Value memoryPort, memoryData;
3540 {
3541 OpBuilder::InsertionGuard guard(builder);
3542 builder.setInsertionPointAfterValue(memory);
3543 auto memoryPortOp = MemoryPortOp::create(
3544 builder, resultType, CMemoryPortType::get(getContext()), memory,
3545 direction, id, annotations);
3546 memoryData = memoryPortOp.getResult(0);
3547 memoryPort = memoryPortOp.getResult(1);
3548 }
3549
3550 // Create a memory port access in the current scope.
3551 MemoryPortAccessOp::create(builder, memoryPort, indexExp, clock);
3552
3553 return moduleContext.addSymbolEntry(id, memoryData, startLoc, true);
3554}
3555
3556// Parse a format string and build operations for FIRRTL "special"
3557// substitutions. Set `formatStringResult` to the validated format string and
3558// `operands` to the list of actual operands.
3559ParseResult FIRStmtParser::parseFormatString(SMLoc formatStringLoc,
3560 StringRef formatString,
3561 ArrayRef<Value> specOperands,
3562 StringAttr &formatStringResult,
3563 SmallVectorImpl<Value> &operands) {
3564 // For FIRRTL versions < 5.0.0, don't process special substitutions
3565 if (version < FIRVersion(5, 0, 0)) {
3566 operands.append(specOperands.begin(), specOperands.end());
3567 formatStringResult =
3568 builder.getStringAttr(FIRToken::getStringValue(formatString));
3569 return success();
3570 }
3571
3572 // Use the utility function to parse the format string
3573 auto loc = translateLocation(formatStringLoc);
3575 builder, loc, FIRToken::getStringValue(formatString), specOperands,
3576 formatStringResult, operands);
3577 return result;
3578}
3579
3580/// printf ::= 'printf(' exp exp StringLit exp* ')' name? info?
3581ParseResult FIRStmtParser::parsePrintf() {
3582 auto startTok = consumeToken(FIRToken::lp_printf);
3583
3584 Value clock, condition;
3585 StringRef formatString;
3586 if (parseExp(clock, "expected clock expression in printf") ||
3587 parseToken(FIRToken::comma, "expected ','") ||
3588 parseExp(condition, "expected condition in printf") ||
3589 parseToken(FIRToken::comma, "expected ','"))
3590 return failure();
3591
3592 auto formatStringLoc = getToken().getLoc();
3593 if (parseGetSpelling(formatString) ||
3594 parseToken(FIRToken::string, "expected format string in printf"))
3595 return failure();
3596
3597 SmallVector<Value, 4> specOperands;
3598 while (consumeIf(FIRToken::comma)) {
3599 specOperands.push_back({});
3600 if (parseExp(specOperands.back(), "expected operand in printf"))
3601 return failure();
3602 }
3603
3604 StringAttr name;
3605 if (parseToken(FIRToken::r_paren, "expected ')'") ||
3606 parseOptionalName(name) || parseOptionalInfo())
3607 return failure();
3608
3609 locationProcessor.setLoc(startTok.getLoc());
3610
3611 StringAttr formatStrUnescaped;
3612 SmallVector<Value> operands;
3613 if (parseFormatString(formatStringLoc, formatString, specOperands,
3614 formatStrUnescaped, operands))
3615 return failure();
3616
3617 PrintFOp::create(builder, clock, condition, formatStrUnescaped, operands,
3618 name);
3619 return success();
3620}
3621
3622/// fprintf ::= 'fprintf(' exp exp StringLit StringLit exp* ')' name? info?
3623ParseResult FIRStmtParser::parseFPrintf() {
3624 if (requireFeature({6, 0, 0}, "fprintf"))
3625 return failure();
3626 auto startTok = consumeToken(FIRToken::lp_fprintf);
3627
3628 Value clock, condition;
3629 StringRef outputFile, formatString;
3630 if (parseExp(clock, "expected clock expression in fprintf") ||
3631 parseToken(FIRToken::comma, "expected ','") ||
3632 parseExp(condition, "expected condition in fprintf") ||
3633 parseToken(FIRToken::comma, "expected ','"))
3634 return failure();
3635
3636 auto outputFileLoc = getToken().getLoc();
3637 if (parseGetSpelling(outputFile) ||
3638 parseToken(FIRToken::string, "expected output file in fprintf"))
3639 return failure();
3640
3641 SmallVector<Value, 4> outputFileSpecOperands;
3642 while (consumeIf(FIRToken::comma)) {
3643 // Stop parsing operands when we see the format string.
3644 if (getToken().getKind() == FIRToken::string)
3645 break;
3646 outputFileSpecOperands.push_back({});
3647 if (parseExp(outputFileSpecOperands.back(), "expected operand in fprintf"))
3648 return failure();
3649 }
3650
3651 auto formatStringLoc = getToken().getLoc();
3652 if (parseGetSpelling(formatString) ||
3653 parseToken(FIRToken::string, "expected format string in printf"))
3654 return failure();
3655
3656 SmallVector<Value, 4> specOperands;
3657 while (consumeIf(FIRToken::comma)) {
3658 specOperands.push_back({});
3659 if (parseExp(specOperands.back(), "expected operand in fprintf"))
3660 return failure();
3661 }
3662
3663 StringAttr name;
3664 if (parseToken(FIRToken::r_paren, "expected ')'") ||
3665 parseOptionalName(name) || parseOptionalInfo())
3666 return failure();
3667
3668 locationProcessor.setLoc(startTok.getLoc());
3669
3670 StringAttr outputFileNameStrUnescaped;
3671 SmallVector<Value> outputFileOperands;
3672 if (parseFormatString(outputFileLoc, outputFile, outputFileSpecOperands,
3673 outputFileNameStrUnescaped, outputFileOperands))
3674 return failure();
3675
3676 StringAttr formatStrUnescaped;
3677 SmallVector<Value> operands;
3678 if (parseFormatString(formatStringLoc, formatString, specOperands,
3679 formatStrUnescaped, operands))
3680 return failure();
3681
3682 FPrintFOp::create(builder, clock, condition, outputFileNameStrUnescaped,
3683 outputFileOperands, formatStrUnescaped, operands, name);
3684 return success();
3685}
3686
3687/// fflush ::= 'fflush(' exp exp (StringLit exp*)? ')' info?
3688ParseResult FIRStmtParser::parseFFlush() {
3689 if (requireFeature({6, 0, 0}, "fflush"))
3690 return failure();
3691
3692 auto startTok = consumeToken(FIRToken::lp_fflush);
3693
3694 Value clock, condition;
3695 if (parseExp(clock, "expected clock expression in 'fflush'") ||
3696 parseToken(FIRToken::comma, "expected ','") ||
3697 parseExp(condition, "expected condition in 'fflush'"))
3698 return failure();
3699
3700 locationProcessor.setLoc(startTok.getLoc());
3701 StringAttr outputFileNameStrUnescaped;
3702 SmallVector<Value> outputFileOperands;
3703 // Parse file name if present.
3704 if (consumeIf(FIRToken::comma)) {
3705 SmallVector<Value, 4> outputFileSpecOperands;
3706 auto outputFileLoc = getToken().getLoc();
3707 StringRef outputFile;
3708 if (parseGetSpelling(outputFile) ||
3709 parseToken(FIRToken::string, "expected output file in fflush"))
3710 return failure();
3711
3712 while (consumeIf(FIRToken::comma)) {
3713 outputFileSpecOperands.push_back({});
3714 if (parseExp(outputFileSpecOperands.back(), "expected operand in fflush"))
3715 return failure();
3716 }
3717
3718 if (parseFormatString(outputFileLoc, outputFile, outputFileSpecOperands,
3719 outputFileNameStrUnescaped, outputFileOperands))
3720 return failure();
3721 }
3722
3723 if (parseToken(FIRToken::r_paren, "expected ')' in 'fflush'") ||
3724 parseOptionalInfo())
3725 return failure();
3726
3727 FFlushOp::create(builder, clock, condition, outputFileNameStrUnescaped,
3728 outputFileOperands);
3729 return success();
3730}
3731
3732/// skip ::= 'skip' info?
3733ParseResult FIRStmtParser::parseSkip() {
3734 auto startTok = consumeToken(FIRToken::kw_skip);
3735
3736 // If this was actually the start of a connect or something else handle
3737 // that.
3738 if (auto isExpr = parseExpWithLeadingKeyword(startTok))
3739 return *isExpr;
3740
3741 if (parseOptionalInfo())
3742 return failure();
3743
3744 locationProcessor.setLoc(startTok.getLoc());
3745 SkipOp::create(builder);
3746 return success();
3747}
3748
3749/// stop ::= 'stop(' exp exp intLit ')' info?
3750ParseResult FIRStmtParser::parseStop() {
3751 auto startTok = consumeToken(FIRToken::lp_stop);
3752
3753 Value clock, condition;
3754 int64_t exitCode;
3755 StringAttr name;
3756 if (parseExp(clock, "expected clock expression in 'stop'") ||
3757 parseToken(FIRToken::comma, "expected ','") ||
3758 parseExp(condition, "expected condition in 'stop'") ||
3759 parseToken(FIRToken::comma, "expected ','") ||
3760 parseIntLit(exitCode, "expected exit code in 'stop'") ||
3761 parseToken(FIRToken::r_paren, "expected ')' in 'stop'") ||
3762 parseOptionalName(name) || parseOptionalInfo())
3763 return failure();
3764
3765 locationProcessor.setLoc(startTok.getLoc());
3766 StopOp::create(builder, clock, condition, builder.getI32IntegerAttr(exitCode),
3767 name);
3768 return success();
3769}
3770
3771/// assert ::= 'assert(' exp exp exp StringLit exp*')' info?
3772ParseResult FIRStmtParser::parseAssert() {
3773 auto startTok = consumeToken(FIRToken::lp_assert);
3774
3775 Value clock, predicate, enable;
3776 StringRef formatString;
3777 StringAttr name;
3778 if (parseExp(clock, "expected clock expression in 'assert'") ||
3779 parseToken(FIRToken::comma, "expected ','") ||
3780 parseExp(predicate, "expected predicate in 'assert'") ||
3781 parseToken(FIRToken::comma, "expected ','") ||
3782 parseExp(enable, "expected enable in 'assert'") ||
3783 parseToken(FIRToken::comma, "expected ','") ||
3784 parseGetSpelling(formatString) ||
3785 parseToken(FIRToken::string, "expected format string in 'assert'"))
3786 return failure();
3787
3788 SmallVector<Value, 4> operands;
3789 while (!consumeIf(FIRToken::r_paren)) {
3790 operands.push_back({});
3791 if (parseToken(FIRToken::comma, "expected ','") ||
3792 parseExp(operands.back(), "expected operand in 'assert'"))
3793 return failure();
3794 }
3795
3796 if (parseOptionalName(name) || parseOptionalInfo())
3797 return failure();
3798
3799 locationProcessor.setLoc(startTok.getLoc());
3800 auto formatStrUnescaped = FIRToken::getStringValue(formatString);
3801 AssertOp::create(builder, clock, predicate, enable, formatStrUnescaped,
3802 operands, name.getValue());
3803 return success();
3804}
3805
3806/// assume ::= 'assume(' exp exp exp StringLit exp* ')' info?
3807ParseResult FIRStmtParser::parseAssume() {
3808 auto startTok = consumeToken(FIRToken::lp_assume);
3809
3810 Value clock, predicate, enable;
3811 StringRef formatString;
3812 StringAttr name;
3813 if (parseExp(clock, "expected clock expression in 'assume'") ||
3814 parseToken(FIRToken::comma, "expected ','") ||
3815 parseExp(predicate, "expected predicate in 'assume'") ||
3816 parseToken(FIRToken::comma, "expected ','") ||
3817 parseExp(enable, "expected enable in 'assume'") ||
3818 parseToken(FIRToken::comma, "expected ','") ||
3819 parseGetSpelling(formatString) ||
3820 parseToken(FIRToken::string, "expected format string in 'assume'"))
3821 return failure();
3822
3823 SmallVector<Value, 4> operands;
3824 while (!consumeIf(FIRToken::r_paren)) {
3825 operands.push_back({});
3826 if (parseToken(FIRToken::comma, "expected ','") ||
3827 parseExp(operands.back(), "expected operand in 'assume'"))
3828 return failure();
3829 }
3830
3831 if (parseOptionalName(name) || parseOptionalInfo())
3832 return failure();
3833
3834 locationProcessor.setLoc(startTok.getLoc());
3835 auto formatStrUnescaped = FIRToken::getStringValue(formatString);
3836 AssumeOp::create(builder, clock, predicate, enable, formatStrUnescaped,
3837 operands, name.getValue());
3838 return success();
3839}
3840
3841/// cover ::= 'cover(' exp exp exp StringLit ')' info?
3842ParseResult FIRStmtParser::parseCover() {
3843 auto startTok = consumeToken(FIRToken::lp_cover);
3844
3845 Value clock, predicate, enable;
3846 StringRef message;
3847 StringAttr name;
3848 if (parseExp(clock, "expected clock expression in 'cover'") ||
3849 parseToken(FIRToken::comma, "expected ','") ||
3850 parseExp(predicate, "expected predicate in 'cover'") ||
3851 parseToken(FIRToken::comma, "expected ','") ||
3852 parseExp(enable, "expected enable in 'cover'") ||
3853 parseToken(FIRToken::comma, "expected ','") ||
3854 parseGetSpelling(message) ||
3855 parseToken(FIRToken::string, "expected message in 'cover'") ||
3856 parseToken(FIRToken::r_paren, "expected ')' in 'cover'") ||
3857 parseOptionalName(name) || parseOptionalInfo())
3858 return failure();
3859
3860 locationProcessor.setLoc(startTok.getLoc());
3861 auto messageUnescaped = FIRToken::getStringValue(message);
3862 CoverOp::create(builder, clock, predicate, enable, messageUnescaped,
3863 ValueRange{}, name.getValue());
3864 return success();
3865}
3866
3867/// when ::= 'when' exp ':' info? suite? ('else' ( when | ':' info? suite?)
3868/// )? suite ::= simple_stmt | INDENT simple_stmt+ DEDENT
3869ParseResult FIRStmtParser::parseWhen(unsigned whenIndent) {
3870 auto startTok = consumeToken(FIRToken::kw_when);
3871
3872 // If this was actually the start of a connect or something else handle
3873 // that.
3874 if (auto isExpr = parseExpWithLeadingKeyword(startTok))
3875 return *isExpr;
3876
3877 Value condition;
3878 if (parseExp(condition, "expected condition in 'when'") ||
3879 parseToken(FIRToken::colon, "expected ':' in when") ||
3880 parseOptionalInfo())
3881 return failure();
3882
3883 locationProcessor.setLoc(startTok.getLoc());
3884 // Create the IR representation for the when.
3885 auto whenStmt = WhenOp::create(builder, condition, /*createElse*/ false);
3886
3887 // Parse the 'then' body into the 'then' region.
3888 if (parseSubBlock(whenStmt.getThenBlock(), whenIndent, layerSym))
3889 return failure();
3890
3891 // If the else is present, handle it otherwise we're done.
3892 if (getToken().isNot(FIRToken::kw_else))
3893 return success();
3894
3895 // If the 'else' is less indented than the when, then it must belong to some
3896 // containing 'when'.
3897 auto elseIndent = getIndentation();
3898 if (elseIndent && *elseIndent < whenIndent)
3899 return success();
3900
3901 consumeToken(FIRToken::kw_else);
3902
3903 // Create an else block to parse into.
3904 whenStmt.createElseRegion();
3905
3906 // If we have the ':' form, then handle it.
3907
3908 // Syntactic shorthand 'else when'. This uses the same indentation level as
3909 // the outer 'when'.
3910 if (getToken().is(FIRToken::kw_when)) {
3911 // We create a sub parser for the else block.
3912 auto subParser = std::make_unique<FIRStmtParser>(
3913 whenStmt.getElseBlock(), moduleContext, innerSymFixups, circuitSymTbl,
3914 version, layerSym);
3915
3916 return subParser->parseSimpleStmt(whenIndent);
3917 }
3918
3919 // Parse the 'else' body into the 'else' region.
3920 LocationAttr elseLoc; // ignore the else locator.
3921 if (parseToken(FIRToken::colon, "expected ':' after 'else'") ||
3922 parseOptionalInfoLocator(elseLoc) ||
3923 parseSubBlock(whenStmt.getElseBlock(), whenIndent, layerSym))
3924 return failure();
3925
3926 // TODO(firrtl spec): There is no reason for the 'else :' grammar to take an
3927 // info. It doesn't appear to be generated either.
3928 return success();
3929}
3930
3931/// enum-exp ::= enum-type '(' Id ( ',' exp )? ')'
3932ParseResult FIRStmtParser::parseEnumExp(Value &value) {
3933 auto startLoc = getToken().getLoc();
3934 locationProcessor.setLoc(startLoc);
3935 FIRRTLType type;
3936 if (parseEnumType(type))
3937 return failure();
3938
3939 // Check that the input type is a legal enumeration.
3940 auto enumType = type_dyn_cast<FEnumType>(type);
3941 if (!enumType)
3942 return emitError(startLoc,
3943 "expected enumeration type in enumeration expression");
3944
3945 StringRef tag;
3946 if (parseToken(FIRToken::l_paren, "expected '(' in enumeration expression") ||
3947 parseId(tag, "expected enumeration tag"))
3948 return failure();
3949
3950 Value input;
3951 if (consumeIf(FIRToken::r_paren)) {
3952 // If the payload is not specified, we create a 0 bit unsigned integer
3953 // constant.
3954 auto type = IntType::get(builder.getContext(), false, 0, true);
3955 Type attrType = IntegerType::get(getContext(), 0, IntegerType::Unsigned);
3956 auto attr = builder.getIntegerAttr(attrType, APInt(0, 0, false));
3957 input = ConstantOp::create(builder, type, attr);
3958 } else {
3959 // Otherwise we parse an expression.
3960 if (parseToken(FIRToken::comma, "expected ','") ||
3961 parseExp(input, "expected expression in enumeration value") ||
3962 parseToken(FIRToken::r_paren, "expected closing ')'"))
3963 return failure();
3964 }
3965
3966 value = FEnumCreateOp::create(builder, enumType, tag, input);
3967 return success();
3968}
3969
3970/// match ::= 'match' exp ':' info?
3971/// (INDENT ( Id ( '(' Id ')' )? ':'
3972/// (INDENT simple_stmt* DEDENT )?
3973/// )* DEDENT)?
3974ParseResult FIRStmtParser::parseMatch(unsigned matchIndent) {
3975 auto startTok = consumeToken(FIRToken::kw_match);
3976
3977 if (auto isExpr = parseExpWithLeadingKeyword(startTok))
3978 return *isExpr;
3979
3980 Value input;
3981 if (parseExp(input, "expected expression in 'match'") ||
3982 parseToken(FIRToken::colon, "expected ':' in 'match'") ||
3983 parseOptionalInfo())
3984 return failure();
3985
3986 auto enumType = type_dyn_cast<FEnumType>(input.getType());
3987 if (!enumType)
3988 return mlir::emitError(
3989 input.getLoc(),
3990 "expected enumeration type for 'match' statement, but got ")
3991 << input.getType();
3992
3993 locationProcessor.setLoc(startTok.getLoc());
3994
3995 SmallVector<Attribute> tags;
3996 SmallVector<std::unique_ptr<Region>> regions;
3997 while (true) {
3998 auto tagLoc = getToken().getLoc();
3999
4000 // Only consume the keyword if the indentation is correct.
4001 auto caseIndent = getIndentation();
4002 if (!caseIndent || *caseIndent <= matchIndent)
4003 break;
4004
4005 // Parse the tag.
4006 StringRef tagSpelling;
4007 if (parseId(tagSpelling, "expected enumeration tag in match statement"))
4008 return failure();
4009 auto tagIndex = enumType.getElementIndex(tagSpelling);
4010 if (!tagIndex)
4011 return emitError(tagLoc, "tag ")
4012 << tagSpelling << " not a member of enumeration " << enumType;
4013 auto tag = IntegerAttr::get(IntegerType::get(getContext(), 32), *tagIndex);
4014 tags.push_back(tag);
4015
4016 // Add a new case to the match operation.
4017 auto *caseBlock = &regions.emplace_back(new Region)->emplaceBlock();
4018
4019 // Declarations are scoped to the case.
4020 FIRModuleContext::ContextScope scope(moduleContext, caseBlock);
4021
4022 // After parsing the region, we can release any new entries in
4023 // unbundledValues since the symbol table entries that refer to them will be
4024 // gone.
4025 UnbundledValueRestorer x(moduleContext.unbundledValues);
4026
4027 // Parse the argument.
4028 if (consumeIf(FIRToken::l_paren)) {
4029 StringAttr identifier;
4030 if (parseId(identifier, "expected identifier for 'case' binding"))
4031 return failure();
4032
4033 // Add an argument to the block.
4034 auto dataType = enumType.getElementType(*tagIndex);
4035 caseBlock->addArgument(dataType, LocWithInfo(tagLoc, this).getLoc());
4036
4037 if (moduleContext.addSymbolEntry(identifier, caseBlock->getArgument(0),
4038 startTok.getLoc()))
4039 return failure();
4040
4041 if (parseToken(FIRToken::r_paren, "expected ')' in match statement case"))
4042 return failure();
4043
4044 } else {
4045 auto dataType = IntType::get(builder.getContext(), false, 0);
4046 caseBlock->addArgument(dataType, LocWithInfo(tagLoc, this).getLoc());
4047 }
4048
4049 if (parseToken(FIRToken::colon, "expected ':' in match statement case"))
4050 return failure();
4051
4052 // Parse a block of statements that are indented more than the case.
4053 auto subParser = std::make_unique<FIRStmtParser>(
4054 *caseBlock, moduleContext, innerSymFixups, circuitSymTbl, version,
4055 layerSym);
4056 if (subParser->parseSimpleStmtBlock(*caseIndent))
4057 return failure();
4058 }
4059
4060 MatchOp::create(builder, input, ArrayAttr::get(getContext(), tags), regions);
4061 return success();
4062}
4063
4064/// domain_exp ::= id
4065/// domain_exp ::= domain_exp '.' id
4066/// domain_exp ::= domain_exp '[' int ']'
4067ParseResult FIRStmtParser::parseDomainExp(Value &result) {
4068 auto loc = getToken().getLoc();
4069 SymbolValueEntry entry;
4070 StringRef id;
4071 if (parseId(id, "expected domain expression") ||
4072 moduleContext.lookupSymbolEntry(entry, id, loc))
4073 return failure();
4074
4075 if (moduleContext.resolveSymbolEntry(result, entry, loc, false)) {
4076 StringRef field;
4077 if (parseToken(FIRToken::period, "expected '.' in field reference") ||
4078 parseFieldId(field, "expected field name") ||
4079 moduleContext.resolveSymbolEntry(result, entry, field, loc))
4080 return failure();
4081 }
4082
4083 if (parseOptionalExpPostscript(result, /*allowDynamic=*/false))
4084 return failure();
4085
4086 auto type = result.getType();
4087 if (!type_isa<DomainType>(type))
4088 return emitError(loc) << "expected domain-type expression, got " << type;
4089
4090 return success();
4091}
4092
4093/// ref_expr ::= 'probe' '(' static_reference ')'
4094/// ::= 'rwprobe' '(' static_reference ')'
4095/// ::= id
4096/// ::= ref_expr '.' id
4097/// ::= ref_expr '[' int ']'
4098// NOLINTNEXTLINE(misc-no-recursion)
4099ParseResult FIRStmtParser::parseRefExp(Value &result, const Twine &message) {
4100 auto token = getToken().getKind();
4101 if (token == FIRToken::lp_probe)
4102 return failure(parseProbe(result) ||
4103 parseOptionalExpPostscript(result, /*allowDynamic=*/false));
4104 if (token == FIRToken::lp_rwprobe)
4105 return failure(parseRWProbe(result) ||
4106 parseOptionalExpPostscript(result, /*allowDynamic=*/false));
4107
4108 // Default to parsing as static reference expression.
4109 // Don't check token kind, we need to support literal_identifier and keywords,
4110 // let parseId handle this.
4111 return parseStaticRefExp(result, message);
4112}
4113
4114/// static_reference ::= id
4115/// ::= static_reference '.' id
4116/// ::= static_reference '[' int ']'
4117// NOLINTNEXTLINE(misc-no-recursion)
4118ParseResult FIRStmtParser::parseStaticRefExp(Value &result,
4119 const Twine &message) {
4120 auto parseIdOrInstance = [&]() -> ParseResult {
4121 StringRef id;
4122 auto loc = getToken().getLoc();
4123 SymbolValueEntry symtabEntry;
4124 if (parseId(id, message) ||
4125 moduleContext.lookupSymbolEntry(symtabEntry, id, loc))
4126 return failure();
4127
4128 // If we looked up a normal value, then we're done.
4129 if (!moduleContext.resolveSymbolEntry(result, symtabEntry, loc, false))
4130 return success();
4131
4132 assert(isa<UnbundledID>(symtabEntry) && "should be an instance");
4133
4134 // Handle the normal "instance.x" reference.
4135 StringRef fieldName;
4136 return failure(
4137 parseToken(FIRToken::period, "expected '.' in field reference") ||
4138 parseFieldId(fieldName, "expected field name") ||
4139 moduleContext.resolveSymbolEntry(result, symtabEntry, fieldName, loc));
4140 };
4141 return failure(parseIdOrInstance() ||
4142 parseOptionalExpPostscript(result, false));
4143}
4144/// static_reference ::= id
4145/// ::= static_reference '.' id
4146/// ::= static_reference '[' int ']'
4147/// Populate `refResult` with rwprobe "root" and parsed indexing.
4148/// Root is base-type target, and will be block argument or forceable.
4149/// Also set `Type`, so we can handle const-ness while visiting.
4150/// If root is an unbundled entry, replace with bounce wire and update
4151/// the unbundled entry to point to this for future users.
4152// NOLINTNEXTLINE(misc-no-recursion)
4153ParseResult FIRStmtParser::parseRWProbeStaticRefExp(FieldRef &refResult,
4154 Type &type,
4155 const Twine &message) {
4156 auto loc = getToken().getLoc();
4157
4158 StringRef id;
4159 SymbolValueEntry symtabEntry;
4160 if (parseId(id, message) ||
4161 moduleContext.lookupSymbolEntry(symtabEntry, id, loc))
4162 return failure();
4163
4164 // Three kinds of rwprobe targets:
4165 // 1. Instance result. Replace with a forceable wire, handle as (2).
4166 // 2. Forceable declaration.
4167 // 3. BlockArgument.
4168
4169 // We use inner symbols for all.
4170
4171 // Figure out what we have, and parse indexing.
4172 Value result;
4173 if (auto unbundledId = dyn_cast<UnbundledID>(symtabEntry)) {
4174 // This means we have an instance.
4175 auto &ubEntry = moduleContext.getUnbundledEntry(unbundledId - 1);
4176
4177 StringRef fieldName;
4178 auto loc = getToken().getLoc();
4179 if (parseToken(FIRToken::period, "expected '.' in field reference") ||
4180 parseFieldId(fieldName, "expected field name"))
4181 return failure();
4182
4183 // Find unbundled entry for the specified result/port.
4184 // Get a reference to it--as we may update it (!!).
4185 auto fieldAttr = StringAttr::get(getContext(), fieldName);
4186 for (auto &elt : ubEntry) {
4187 if (elt.first == fieldAttr) {
4188 // Grab the unbundled entry /by reference/ so we can update it with the
4189 // new forceable wire we insert (if not already done).
4190 auto &instResult = elt.second;
4191
4192 // If it's already forceable, use that.
4193 auto *defining = instResult.getDefiningOp();
4194 assert(defining);
4195 if (isa<WireOp>(defining)) {
4196 result = instResult;
4197 break;
4198 }
4199
4200 // Otherwise, replace with bounce wire.
4201 auto type = instResult.getType();
4202
4203 // Create bounce wire for the instance result.
4204 // This may be an open aggregate, or other non-base type.
4205 auto annotations = getConstants().emptyArrayAttr;
4206 StringAttr sym = {};
4207 SmallString<64> name;
4208 (id + "_" + fieldName + "_bounce").toVector(name);
4209 locationProcessor.setLoc(loc);
4210 OpBuilder::InsertionGuard guard(builder);
4211 builder.setInsertionPoint(defining);
4212 auto bounce =
4213 WireOp::create(builder, type, name, NameKindEnum::InterestingName,
4214 annotations, sym);
4215 auto bounceVal = bounce.getDataRaw();
4216
4217 // Replace instance result with reads from bounce wire.
4218 instResult.replaceAllUsesWith(bounceVal);
4219
4220 // Connect to/from the result per flow.
4221 builder.setInsertionPointAfter(defining);
4222 if (foldFlow(instResult) == Flow::Source)
4223 emitConnect(builder, bounceVal, instResult,
4224 getConstants().options.warnOnTruncation);
4225 else
4226 emitConnect(builder, instResult, bounceVal,
4227 getConstants().options.warnOnTruncation);
4228 // Set the parse result AND update `instResult` which is a reference to
4229 // the unbundled entry for the instance result, so that future uses also
4230 // find this new wire.
4231 result = instResult = bounce.getDataRaw();
4232 break;
4233 }
4234 }
4235
4236 if (!result) {
4237 emitError(loc, "use of invalid field name '")
4238 << fieldName << "' on bundle value";
4239 return failure();
4240 }
4241 } else {
4242 // This target can be a port or a regular value.
4243 result = cast<Value>(symtabEntry);
4244 }
4245
4246 assert(result);
4247 assert(isa<BlockArgument>(result) ||
4248 result.getDefiningOp<hw::InnerSymbolOpInterface>());
4249
4250 // We have our root value, we just need to parse the field id.
4251 // Build up the FieldRef as processing indexing expressions, and
4252 // compute the type so that we know the const-ness of the final expression.
4253 refResult = FieldRef(result, 0);
4254 type = result.getType();
4255 while (true) {
4256 if (consumeIf(FIRToken::period)) {
4257 SmallVector<StringRef, 3> fields;
4258 if (parseFieldIdSeq(fields, "expected field name"))
4259 return failure();
4260 for (auto fieldName : fields) {
4261 if (auto bundle = type_dyn_cast<BundleType>(type)) {
4262 if (auto index = bundle.getElementIndex(fieldName)) {
4263 refResult = refResult.getSubField(bundle.getFieldID(*index));
4264 type = bundle.getElementTypePreservingConst(*index);
4265 continue;
4266 }
4267 } else if (auto bundle = type_dyn_cast<OpenBundleType>(type)) {
4268 if (auto index = bundle.getElementIndex(fieldName)) {
4269 refResult = refResult.getSubField(bundle.getFieldID(*index));
4270 type = bundle.getElementTypePreservingConst(*index);
4271 continue;
4272 }
4273 } else {
4274 return emitError(loc, "subfield requires bundle operand")
4275 << "got " << type << "\n";
4276 }
4277 return emitError(loc,
4278 "unknown field '" + fieldName + "' in bundle type ")
4279 << type;
4280 }
4281 continue;
4282 }
4283 if (consumeIf(FIRToken::l_square)) {
4284 auto loc = getToken().getLoc();
4285 int32_t index;
4286 if (parseIntLit(index, "expected index") ||
4287 parseToken(FIRToken::r_square, "expected ']'"))
4288 return failure();
4289
4290 if (index < 0)
4291 return emitError(loc, "invalid index specifier");
4292
4293 if (auto vector = type_dyn_cast<FVectorType>(type)) {
4294 if ((unsigned)index < vector.getNumElements()) {
4295 refResult = refResult.getSubField(vector.getFieldID(index));
4296 type = vector.getElementTypePreservingConst();
4297 continue;
4298 }
4299 } else if (auto vector = type_dyn_cast<OpenVectorType>(type)) {
4300 if ((unsigned)index < vector.getNumElements()) {
4301 refResult = refResult.getSubField(vector.getFieldID(index));
4302 type = vector.getElementTypePreservingConst();
4303 continue;
4304 }
4305 } else {
4306 return emitError(loc, "subindex requires vector operand");
4307 }
4308 return emitError(loc, "out of range index '")
4309 << index << "' for vector type " << type;
4310 }
4311 return success();
4312 }
4313}
4314
4315/// intrinsic_expr ::= 'intrinsic(' Id (params)? ':' type exp* ')'
4316/// intrinsic_stmt ::= 'intrinsic(' Id (params)? (':' type )? exp* ')'
4317ParseResult FIRStmtParser::parseIntrinsic(Value &result, bool isStatement) {
4318 auto startTok = consumeToken(FIRToken::lp_intrinsic);
4319 StringRef intrinsic;
4320 ArrayAttr parameters;
4321 FIRRTLType type;
4322
4323 if (parseId(intrinsic, "expected intrinsic identifier") ||
4324 parseOptionalParams(parameters))
4325 return failure();
4326
4327 if (consumeIf(FIRToken::colon)) {
4328 if (parseType(type, "expected intrinsic return type"))
4329 return failure();
4330 } else if (!isStatement)
4331 return emitError("expected ':' in intrinsic expression");
4332
4333 SmallVector<Value> operands;
4334 auto loc = startTok.getLoc();
4335 if (consumeIf(FIRToken::comma)) {
4336 if (parseListUntil(FIRToken::r_paren, [&]() -> ParseResult {
4337 Value operand;
4338 if (parseExp(operand, "expected operand in intrinsic"))
4339 return failure();
4340 operands.push_back(operand);
4341 locationProcessor.setLoc(loc);
4342 return success();
4343 }))
4344 return failure();
4345 } else {
4346 if (parseToken(FIRToken::r_paren, "expected ')' in intrinsic"))
4347 return failure();
4348 }
4349
4350 if (isStatement)
4351 if (parseOptionalInfo())
4352 return failure();
4353
4354 locationProcessor.setLoc(loc);
4355
4356 auto op = GenericIntrinsicOp::create(
4357 builder, type, builder.getStringAttr(intrinsic), operands, parameters);
4358 if (type)
4359 result = op.getResult();
4360 return success();
4361}
4362
4363/// params ::= '<' param','* '>'
4364ParseResult FIRStmtParser::parseOptionalParams(ArrayAttr &resultParameters) {
4365 if (!consumeIf(FIRToken::less))
4366 return success();
4367
4368 SmallVector<Attribute, 8> parameters;
4369 SmallPtrSet<StringAttr, 8> seen;
4370 if (parseListUntil(FIRToken::greater, [&]() -> ParseResult {
4371 StringAttr name;
4372 Attribute value;
4373 SMLoc loc;
4374 if (parseParameter(name, value, loc))
4375 return failure();
4376 auto typedValue = dyn_cast<TypedAttr>(value);
4377 if (!typedValue)
4378 return emitError(loc)
4379 << "invalid value for parameter '" << name.getValue() << "'";
4380 if (!seen.insert(name).second)
4381 return emitError(loc, "redefinition of parameter '" +
4382 name.getValue() + "'");
4383 parameters.push_back(ParamDeclAttr::get(name, typedValue));
4384 return success();
4385 }))
4386 return failure();
4387
4388 resultParameters = ArrayAttr::get(getContext(), parameters);
4389 return success();
4390}
4391
4392/// path ::= 'path(' StringLit ')'
4393// NOLINTNEXTLINE(misc-no-recursion)
4394ParseResult FIRStmtParser::parsePathExp(Value &result) {
4395 auto startTok = consumeToken(FIRToken::lp_path);
4396 locationProcessor.setLoc(startTok.getLoc());
4397 StringRef target;
4398 if (parseGetSpelling(target) ||
4399 parseToken(FIRToken::string,
4400 "expected target string in path expression") ||
4401 parseToken(FIRToken::r_paren, "expected ')' in path expression"))
4402 return failure();
4403 result = UnresolvedPathOp::create(
4404 builder, StringAttr::get(getContext(), FIRToken::getStringValue(target)));
4405 return success();
4406}
4407
4408/// domain_instantiation ::= 'domain' id 'of' id ('(' exp (',' exp)* ')')? info?
4409ParseResult FIRStmtParser::parseDomainInstantiation() {
4410 auto startTok = consumeToken(FIRToken::kw_domain);
4411 auto startLoc = startTok.getLoc();
4412
4413 // If this was actually the start of a connect or something else handle that.
4414 if (auto isExpr = parseExpWithLeadingKeyword(startTok))
4415 return *isExpr;
4416
4417 locationProcessor.setLoc(startTok.getLoc());
4418
4419 StringAttr instanceName;
4420 StringAttr domainKind;
4421
4422 if (requireFeature(missingSpecFIRVersion, "domains", startLoc) ||
4423 parseId(instanceName, "expected domain instance name") ||
4424 parseToken(FIRToken::kw_of, "expected 'of' after domain instance name") ||
4425 parseId(domainKind, "expected domain type name"))
4426 return failure();
4427
4428 // Create the domain instance
4429 // Look up the domain to get its fields
4430 const auto &domainMap = getConstants().domainMap;
4431 auto lookup = domainMap.find(domainKind.getValue());
4432 if (lookup == domainMap.end())
4433 return emitError(startTok.getLoc())
4434 << "unknown domain '" << domainKind.getValue() << "'";
4435
4436 auto domainType = DomainType::getFromDomainOp(lookup->second);
4437 auto fields = domainType.getFields();
4438
4439 // Parse optional field values
4440 SmallVector<Value> fieldValues;
4441 if (consumeIf(FIRToken::l_paren)) {
4442 // Parse comma-separated list of expressions
4443 if (parseListUntil(FIRToken::r_paren, [&]() -> ParseResult {
4444 if (fieldValues.size() >= fields.size())
4445 return emitError(getToken().getLoc())
4446 << "too many field values for domain '"
4447 << domainKind.getValue() << "': expected " << fields.size();
4448
4449 Value value;
4450 if (parseExp(value, "expected field value expression"))
4451 return failure();
4452
4453 value = emitImplicitAnyRefCast(
4454 value,
4455 cast<DomainFieldAttr>(fields[fieldValues.size()]).getType());
4456
4457 fieldValues.push_back(value);
4458 return success();
4459 }))
4460 return failure();
4461 }
4462
4463 if (parseOptionalInfo())
4464 return failure();
4465
4466 if (fieldValues.size() < fields.size())
4467 return emitError(startLoc)
4468 << "not enough field values for domain '" << domainKind.getValue()
4469 << "': expected " << fields.size() << ", got " << fieldValues.size();
4470
4471 locationProcessor.setLoc(startLoc);
4472 auto result =
4473 DomainCreateOp::create(builder, domainType, instanceName, fieldValues);
4474
4475 // Add to symbol table
4476 return moduleContext.addSymbolEntry(instanceName.getValue(), result,
4477 startTok.getLoc());
4478}
4479
4480/// domain_define ::= 'domain_define' domain_exp '=' domain_exp info?
4481ParseResult FIRStmtParser::parseDomainDefine() {
4482 auto startTok = consumeToken(FIRToken::kw_domain_define);
4483 auto startLoc = startTok.getLoc();
4484 locationProcessor.setLoc(startLoc);
4485
4486 Value dest, src;
4487 if (requireFeature(missingSpecFIRVersion, "domains", startLoc) ||
4488 parseDomainExp(dest) || parseToken(FIRToken::equal, "expected '='") ||
4489 parseDomainExp(src) || parseOptionalInfo())
4490 return failure();
4491
4492 emitConnect(builder, dest, src, getConstants().options.warnOnTruncation);
4493 return success();
4494}
4495
4496/// define ::= 'define' static_reference '=' ref_expr info?
4497ParseResult FIRStmtParser::parseRefDefine() {
4498 auto startTok = consumeToken(FIRToken::kw_define);
4499
4500 Value src, target;
4501 if (parseStaticRefExp(target,
4502 "expected static reference expression in 'define'") ||
4503 parseToken(FIRToken::equal,
4504 "expected '=' after define reference expression") ||
4505 parseRefExp(src, "expected reference expression in 'define'") ||
4506 parseOptionalInfo())
4507 return failure();
4508
4509 // Check reference expressions are of reference type.
4510 if (!type_isa<RefType>(target.getType()))
4511 return emitError(startTok.getLoc(), "expected reference-type expression in "
4512 "'define' target (LHS), got ")
4513 << target.getType();
4514 if (!type_isa<RefType>(src.getType()))
4515 return emitError(startTok.getLoc(), "expected reference-type expression in "
4516 "'define' source (RHS), got ")
4517 << src.getType();
4518
4519 // static_reference doesn't differentiate which can be ref.sub'd, so check
4520 // this explicitly:
4521 if (isa_and_nonnull<RefSubOp>(target.getDefiningOp()))
4522 return emitError(startTok.getLoc(),
4523 "cannot define into a sub-element of a reference");
4524
4525 locationProcessor.setLoc(startTok.getLoc());
4526
4527 if (!areTypesRefCastable(target.getType(), src.getType()))
4528 return emitError(startTok.getLoc(), "cannot define reference of type ")
4529 << target.getType() << " with incompatible reference of type "
4530 << src.getType();
4531
4532 emitConnect(builder, target, src, getConstants().options.warnOnTruncation);
4533
4534 return success();
4535}
4536
4537/// read ::= 'read' '(' ref_expr ')'
4538ParseResult FIRStmtParser::parseRefRead(Value &result) {
4539 auto startTok = consumeToken(FIRToken::lp_read);
4540
4541 Value ref;
4542 if (parseRefExp(ref, "expected reference expression in 'read'") ||
4543 parseToken(FIRToken::r_paren, "expected ')' in 'read'"))
4544 return failure();
4545
4546 locationProcessor.setLoc(startTok.getLoc());
4547
4548 // Check argument is a ref-type value.
4549 if (!type_isa<RefType>(ref.getType()))
4550 return emitError(startTok.getLoc(),
4551 "expected reference-type expression in 'read', got ")
4552 << ref.getType();
4553
4554 result = RefResolveOp::create(builder, ref);
4555
4556 return success();
4557}
4558
4559/// probe ::= 'probe' '(' static_ref ')'
4560ParseResult FIRStmtParser::parseProbe(Value &result) {
4561 auto startTok = consumeToken(FIRToken::lp_probe);
4562
4563 Value staticRef;
4564 if (parseStaticRefExp(staticRef,
4565 "expected static reference expression in 'probe'") ||
4566 parseToken(FIRToken::r_paren, "expected ')' in 'probe'"))
4567 return failure();
4568
4569 locationProcessor.setLoc(startTok.getLoc());
4570
4571 // Check probe expression is base-type.
4572 if (!type_isa<FIRRTLBaseType>(staticRef.getType()))
4573 return emitError(startTok.getLoc(),
4574 "expected base-type expression in 'probe', got ")
4575 << staticRef.getType();
4576
4577 // Check for other unsupported reference sources.
4578 // TODO: Add to ref.send verifier / inferReturnTypes.
4579 if (isa_and_nonnull<MemOp, CombMemOp, SeqMemOp, MemoryPortOp,
4580 MemoryDebugPortOp, MemoryPortAccessOp>(
4581 staticRef.getDefiningOp()))
4582 return emitError(startTok.getLoc(), "cannot probe memories or their ports");
4583
4584 result = RefSendOp::create(builder, staticRef);
4585
4586 return success();
4587}
4588
4589/// rwprobe ::= 'rwprobe' '(' static_ref ')'
4590ParseResult FIRStmtParser::parseRWProbe(Value &result) {
4591 auto startTok = consumeToken(FIRToken::lp_rwprobe);
4592
4593 FieldRef staticRef;
4594 Type parsedTargetType;
4595 if (parseRWProbeStaticRefExp(
4596 staticRef, parsedTargetType,
4597 "expected static reference expression in 'rwprobe'") ||
4598 parseToken(FIRToken::r_paren, "expected ')' in 'rwprobe'"))
4599 return failure();
4600
4601 locationProcessor.setLoc(startTok.getLoc());
4602
4603 // Checks:
4604 // Not public port (verifier)
4605
4606 // Check probe expression is base-type.
4607 auto targetType = type_dyn_cast<FIRRTLBaseType>(parsedTargetType);
4608 if (!targetType)
4609 return emitError(startTok.getLoc(),
4610 "expected base-type expression in 'rwprobe', got ")
4611 << parsedTargetType;
4612
4613 auto root = staticRef.getValue();
4614 auto *definingOp = root.getDefiningOp();
4615
4616 if (isa_and_nonnull<MemOp, CombMemOp, SeqMemOp, MemoryPortOp,
4617 MemoryDebugPortOp, MemoryPortAccessOp>(definingOp))
4618 return emitError(startTok.getLoc(), "cannot probe memories or their ports");
4619
4620 auto forceableType = firrtl::detail::getForceableResultType(true, targetType);
4621 if (!forceableType)
4622 return emitError(startTok.getLoc(), "cannot force target of type ")
4623 << targetType;
4624
4625 // Create the operation with a placeholder reference and add to fixup list.
4626 auto op = RWProbeOp::create(builder, forceableType,
4627 getConstants().placeholderInnerRef);
4628 innerSymFixups.add(op, getTargetFor(staticRef));
4629 result = op;
4630 return success();
4631}
4632
4633/// force ::= 'force(' exp exp ref_expr exp ')' info?
4634ParseResult FIRStmtParser::parseRefForce() {
4635 auto startTok = consumeToken(FIRToken::lp_force);
4636
4637 Value clock, pred, dest, src;
4638 if (parseExp(clock, "expected clock expression in force") ||
4639 parseToken(FIRToken::comma, "expected ','") ||
4640 parseExp(pred, "expected predicate expression in force") ||
4641 parseToken(FIRToken::comma, "expected ','") ||
4642 parseRefExp(dest, "expected destination reference expression in force") ||
4643 parseToken(FIRToken::comma, "expected ','") ||
4644 parseExp(src, "expected source expression in force") ||
4645 parseToken(FIRToken::r_paren, "expected ')' in force") ||
4646 parseOptionalInfo())
4647 return failure();
4648
4649 // Check reference expression is of reference type.
4650 auto ref = type_dyn_cast<RefType>(dest.getType());
4651 if (!ref || !ref.getForceable())
4652 return emitError(
4653 startTok.getLoc(),
4654 "expected rwprobe-type expression for force destination, got ")
4655 << dest.getType();
4656 auto srcBaseType = type_dyn_cast<FIRRTLBaseType>(src.getType());
4657 if (!srcBaseType)
4658 return emitError(startTok.getLoc(),
4659 "expected base-type for force source, got ")
4660 << src.getType();
4661 if (!srcBaseType.isPassive())
4662 return emitError(startTok.getLoc(),
4663 "expected passive value for force source, got ")
4664 << srcBaseType;
4665
4666 locationProcessor.setLoc(startTok.getLoc());
4667
4668 // Cast ref to accommodate uninferred sources.
4669 auto noConstSrcType = srcBaseType.getAllConstDroppedType();
4670 if (noConstSrcType != ref.getType()) {
4671 // Try to cast destination to rwprobe of source type (dropping const).
4672 auto compatibleRWProbe = RefType::get(noConstSrcType, true, ref.getLayer());
4673 if (areTypesRefCastable(compatibleRWProbe, ref))
4674 dest = RefCastOp::create(builder, compatibleRWProbe, dest);
4675 else
4676 return emitError(startTok.getLoc(), "incompatible force source of type ")
4677 << src.getType() << " cannot target destination "
4678 << dest.getType();
4679 }
4680
4681 RefForceOp::create(builder, clock, pred, dest, src);
4682
4683 return success();
4684}
4685
4686/// force_initial ::= 'force_initial(' ref_expr exp ')' info?
4687ParseResult FIRStmtParser::parseRefForceInitial() {
4688 auto startTok = consumeToken(FIRToken::lp_force_initial);
4689
4690 Value dest, src;
4691 if (parseRefExp(
4692 dest, "expected destination reference expression in force_initial") ||
4693 parseToken(FIRToken::comma, "expected ','") ||
4694 parseExp(src, "expected source expression in force_initial") ||
4695 parseToken(FIRToken::r_paren, "expected ')' in force_initial") ||
4696 parseOptionalInfo())
4697 return failure();
4698
4699 // Check reference expression is of reference type.
4700 auto ref = type_dyn_cast<RefType>(dest.getType());
4701 if (!ref || !ref.getForceable())
4702 return emitError(startTok.getLoc(), "expected rwprobe-type expression for "
4703 "force_initial destination, got ")
4704 << dest.getType();
4705 auto srcBaseType = type_dyn_cast<FIRRTLBaseType>(src.getType());
4706 if (!srcBaseType)
4707 return emitError(startTok.getLoc(),
4708 "expected base-type expression for force_initial "
4709 "source, got ")
4710 << src.getType();
4711 if (!srcBaseType.isPassive())
4712 return emitError(startTok.getLoc(),
4713 "expected passive value for force_initial source, got ")
4714 << srcBaseType;
4715
4716 locationProcessor.setLoc(startTok.getLoc());
4717
4718 // Cast ref to accommodate uninferred sources.
4719 auto noConstSrcType = srcBaseType.getAllConstDroppedType();
4720 if (noConstSrcType != ref.getType()) {
4721 // Try to cast destination to rwprobe of source type (dropping const).
4722 auto compatibleRWProbe = RefType::get(noConstSrcType, true, ref.getLayer());
4723 if (areTypesRefCastable(compatibleRWProbe, ref))
4724 dest = RefCastOp::create(builder, compatibleRWProbe, dest);
4725 else
4726 return emitError(startTok.getLoc(),
4727 "incompatible force_initial source of type ")
4728 << src.getType() << " cannot target destination "
4729 << dest.getType();
4730 }
4731
4732 auto value = APInt::getAllOnes(1);
4733 auto type = UIntType::get(builder.getContext(), 1);
4734 auto attr = builder.getIntegerAttr(IntegerType::get(type.getContext(),
4735 value.getBitWidth(),
4736 IntegerType::Unsigned),
4737 value);
4738 auto pred = moduleContext.getCachedConstant(builder, attr, type, attr);
4739 RefForceInitialOp::create(builder, pred, dest, src);
4740
4741 return success();
4742}
4743
4744/// release ::= 'release(' exp exp ref_expr ')' info?
4745ParseResult FIRStmtParser::parseRefRelease() {
4746 auto startTok = consumeToken(FIRToken::lp_release);
4747
4748 Value clock, pred, dest;
4749 if (parseExp(clock, "expected clock expression in release") ||
4750 parseToken(FIRToken::comma, "expected ','") ||
4751 parseExp(pred, "expected predicate expression in release") ||
4752 parseToken(FIRToken::comma, "expected ','") ||
4753 parseRefExp(dest,
4754 "expected destination reference expression in release") ||
4755 parseToken(FIRToken::r_paren, "expected ')' in release") ||
4756 parseOptionalInfo())
4757 return failure();
4758
4759 // Check reference expression is of reference type.
4760 if (auto ref = type_dyn_cast<RefType>(dest.getType());
4761 !ref || !ref.getForceable())
4762 return emitError(
4763 startTok.getLoc(),
4764 "expected rwprobe-type expression for release destination, got ")
4765 << dest.getType();
4766
4767 locationProcessor.setLoc(startTok.getLoc());
4768
4769 RefReleaseOp::create(builder, clock, pred, dest);
4770
4771 return success();
4772}
4773
4774/// release_initial ::= 'release_initial(' ref_expr ')' info?
4775ParseResult FIRStmtParser::parseRefReleaseInitial() {
4776 auto startTok = consumeToken(FIRToken::lp_release_initial);
4777
4778 Value dest;
4779 if (parseRefExp(
4780 dest,
4781 "expected destination reference expression in release_initial") ||
4782 parseToken(FIRToken::r_paren, "expected ')' in release_initial") ||
4783 parseOptionalInfo())
4784 return failure();
4785
4786 // Check reference expression is of reference type.
4787 if (auto ref = type_dyn_cast<RefType>(dest.getType());
4788 !ref || !ref.getForceable())
4789 return emitError(startTok.getLoc(), "expected rwprobe-type expression for "
4790 "release_initial destination, got ")
4791 << dest.getType();
4792
4793 locationProcessor.setLoc(startTok.getLoc());
4794
4795 auto value = APInt::getAllOnes(1);
4796 auto type = UIntType::get(builder.getContext(), 1);
4797 auto attr = builder.getIntegerAttr(IntegerType::get(type.getContext(),
4798 value.getBitWidth(),
4799 IntegerType::Unsigned),
4800 value);
4801 auto pred = moduleContext.getCachedConstant(builder, attr, type, attr);
4802 RefReleaseInitialOp::create(builder, pred, dest);
4803
4804 return success();
4805}
4806
4807/// connect ::= 'connect' expr expr
4808ParseResult FIRStmtParser::parseConnect() {
4809 auto startTok = consumeToken(FIRToken::kw_connect);
4810 auto loc = startTok.getLoc();
4811
4812 Value lhs, rhs;
4813 if (parseExp(lhs, "expected connect expression") ||
4814 parseToken(FIRToken::comma, "expected ','") ||
4815 parseExp(rhs, "expected connect expression") || parseOptionalInfo())
4816 return failure();
4817
4818 auto lhsType = type_dyn_cast<FIRRTLBaseType>(lhs.getType());
4819 auto rhsType = type_dyn_cast<FIRRTLBaseType>(rhs.getType());
4820 if (!lhsType || !rhsType)
4821 return mlir::emitError(locationProcessor.getLoc(*this, loc),
4822 "cannot connect reference or property types");
4823 // TODO: Once support lands for agg-of-ref, add test for this check!
4824 if (lhsType.containsReference() || rhsType.containsReference())
4825 return mlir::emitError(locationProcessor.getLoc(*this, loc),
4826 "cannot connect types containing references");
4827
4828 if (!areTypesEquivalent(lhsType, rhsType))
4829 return mlir::emitError(locationProcessor.getLoc(*this, loc),
4830 "cannot connect non-equivalent type ")
4831 << rhsType << " to " << lhsType;
4832
4833 locationProcessor.setLoc(loc);
4835 builder, lhs, rhs, [&] { return locationProcessor.getLoc(*this, loc); },
4836 getConstants().options.warnOnTruncation);
4837 return success();
4838}
4839
4840/// FIRRTL 6.0.0 <= version < FIRRTL 8.0.0:
4841/// propassert ::= 'propassert' expr ',' string_literal
4842/// FIRRTL 7.0.0 <= version:
4843/// propassert ::= 'propassert' expr ',' expr
4844///
4845/// Before calling, it has already been verified that the FIRRTL version is
4846/// greater than 6.0.0.
4847ParseResult FIRStmtParser::parsePropAssert() {
4848 auto startTok = consumeToken(FIRToken::kw_propassert);
4849 auto loc = startTok.getLoc();
4850
4851 llvm::SMLoc conditionLoc = getToken().getLoc(), messageLoc;
4852 Value condition, message;
4853 if (parseExp(condition, "expected condition in 'propassert'") ||
4854 parseToken(FIRToken::comma, "expected ','"))
4855 return failure();
4856 // String message handling
4857 if (getToken().is(FIRToken::string)) {
4858 if (removedFeature({8, 0, 0}, "string messages in property asserts"))
4859 return failure();
4860 StringRef messageStr;
4861 messageLoc = getToken().getLoc();
4862 if (parseGetSpelling(messageStr) ||
4863 parseToken(FIRToken::string, "expected message string in 'propassert'"))
4864 return failure();
4865 locationProcessor.setLoc(messageLoc);
4866 auto attr = builder.getStringAttr(FIRToken::getStringValue(messageStr));
4867 message = moduleContext.getCachedConstant<StringConstantOp>(
4868 builder, attr, builder.getType<StringType>(), attr);
4869 } else {
4870 if (requireFeature(
4871 {7, 0, 0},
4872 "string property expression message in property asserts"))
4873 return failure();
4874 messageLoc = getToken().getLoc();
4875 if (parseExp(message, "expected message in 'propassert'"))
4876 return failure();
4877 }
4878
4879 if (!isa<BoolType>(condition.getType()))
4880 return emitError(conditionLoc,
4881 "propassert condition must be of boolean type");
4882
4883 // Note: This is a dead check for FIRRTL < 7.0.0.
4884 if (!type_isa<StringType>(message.getType()))
4885 return emitError(messageLoc, "propassert message must be a string type");
4886
4887 if (parseOptionalInfo())
4888 return failure();
4889
4890 locationProcessor.setLoc(loc);
4891 PropertyAssertOp::create(builder, condition, message);
4892 return success();
4893}
4894
4895/// propassign ::= 'propassign' expr expr
4896ParseResult FIRStmtParser::parsePropAssign() {
4897 auto startTok = consumeToken(FIRToken::kw_propassign);
4898 auto loc = startTok.getLoc();
4899
4900 Value lhs, rhs;
4901 if (parseExp(lhs, "expected propassign expression") ||
4902 parseToken(FIRToken::comma, "expected ','") ||
4903 parseExp(rhs, "expected propassign expression") || parseOptionalInfo())
4904 return failure();
4905
4906 auto lhsType = type_dyn_cast<PropertyType>(lhs.getType());
4907 if (!lhsType)
4908 return emitError(loc, "can only propassign property types");
4909 locationProcessor.setLoc(loc);
4910 rhs = emitImplicitAnyRefCast(rhs, lhsType);
4911 auto rhsType = type_dyn_cast<PropertyType>(rhs.getType());
4912 if (!rhsType)
4913 return emitError(loc, "can only propassign property types");
4914 if (lhsType != rhsType)
4915 return emitError(loc, "cannot propassign non-equivalent type ")
4916 << rhsType << " to " << lhsType;
4917 PropAssignOp::create(builder, lhs, rhs);
4918 return success();
4919}
4920
4921/// invalidate ::= 'invalidate' expr
4922ParseResult FIRStmtParser::parseInvalidate() {
4923 auto startTok = consumeToken(FIRToken::kw_invalidate);
4924
4925 Value lhs;
4926
4927 StringRef id;
4928 auto loc = getToken().getLoc();
4929 SymbolValueEntry symtabEntry;
4930 if (parseId(id, "expected static reference expression") ||
4931 moduleContext.lookupSymbolEntry(symtabEntry, id, loc))
4932 return failure();
4933
4934 // If we looked up a normal value (e.g., wire, register, or port), then we
4935 // just need to get any optional trailing expression. Invalidate this.
4936 if (!moduleContext.resolveSymbolEntry(lhs, symtabEntry, loc, false)) {
4937 if (parseOptionalExpPostscript(lhs, /*allowDynamic=*/false) ||
4938 parseOptionalInfo())
4939 return failure();
4940
4941 locationProcessor.setLoc(startTok.getLoc());
4942 emitInvalidate(lhs);
4943 return success();
4944 }
4945
4946 // We're dealing with an instance. This instance may or may not have a
4947 // trailing expression. Handle the special case of no trailing expression
4948 // first by invalidating all of its results.
4949 assert(isa<UnbundledID>(symtabEntry) && "should be an instance");
4950
4951 if (getToken().isNot(FIRToken::period)) {
4952 locationProcessor.setLoc(loc);
4953 // Invalidate all of the results of the bundled value.
4954 unsigned unbundledId = cast<UnbundledID>(symtabEntry) - 1;
4955 UnbundledValueEntry &ubEntry = moduleContext.getUnbundledEntry(unbundledId);
4956 for (auto elt : ubEntry)
4957 emitInvalidate(elt.second);
4958 return success();
4959 }
4960
4961 // Handle the case of an instance with a trailing expression. This must begin
4962 // with a '.' (until we add instance arrays).
4963 StringRef fieldName;
4964 if (parseToken(FIRToken::period, "expected '.' in field reference") ||
4965 parseFieldId(fieldName, "expected field name") ||
4966 moduleContext.resolveSymbolEntry(lhs, symtabEntry, fieldName, loc))
4967 return failure();
4968
4969 // Update with any trailing expression and invalidate it.
4970 if (parseOptionalExpPostscript(lhs, /*allowDynamic=*/false) ||
4971 parseOptionalInfo())
4972 return failure();
4973
4974 locationProcessor.setLoc(startTok.getLoc());
4975 emitInvalidate(lhs);
4976 return success();
4977}
4978
4979ParseResult FIRStmtParser::parseLayerBlockOrGroup(unsigned indent) {
4980
4981 auto startTok = consumeToken();
4982 assert(startTok.isAny(FIRToken::kw_layerblock, FIRToken::kw_group) &&
4983 "consumed an unexpected token");
4984 auto loc = startTok.getLoc();
4985
4986 StringRef id;
4987 if (parseId(id, "expected layer identifer") ||
4988 parseToken(FIRToken::colon, "expected ':' at end of layer block") ||
4989 parseOptionalInfo())
4990 return failure();
4991
4992 locationProcessor.setLoc(loc);
4993
4994 StringRef rootLayer;
4995 SmallVector<FlatSymbolRefAttr> nestedLayers;
4996 if (!layerSym) {
4997 rootLayer = id;
4998 } else {
4999 rootLayer = layerSym.getRootReference();
5000 auto nestedRefs = layerSym.getNestedReferences();
5001 nestedLayers.append(nestedRefs.begin(), nestedRefs.end());
5002 nestedLayers.push_back(FlatSymbolRefAttr::get(builder.getContext(), id));
5003 }
5004
5005 auto layerBlockOp = LayerBlockOp::create(
5006 builder,
5007 SymbolRefAttr::get(builder.getContext(), rootLayer, nestedLayers));
5008 layerBlockOp->getRegion(0).push_back(new Block());
5009
5010 if (getIndentation() > indent)
5011 if (parseSubBlock(layerBlockOp.getRegion().front(), indent,
5012 layerBlockOp.getLayerName()))
5013 return failure();
5014
5015 return success();
5016}
5017
5018/// leading-exp-stmt ::= exp '<=' exp info?
5019/// ::= exp 'is' 'invalid' info?
5020ParseResult FIRStmtParser::parseLeadingExpStmt(Value lhs) {
5021 auto loc = getToken().getLoc();
5022
5023 // If 'is' grammar is special.
5024 if (consumeIf(FIRToken::kw_is)) {
5025 if (parseToken(FIRToken::kw_invalid, "expected 'invalid'") ||
5026 parseOptionalInfo())
5027 return failure();
5028
5029 if (removedFeature({3, 0, 0}, "'is invalid' statements", loc))
5030 return failure();
5031
5032 locationProcessor.setLoc(loc);
5033 emitInvalidate(lhs);
5034 return success();
5035 }
5036
5037 if (parseToken(FIRToken::less_equal, "expected '<=' in statement"))
5038 return failure();
5039
5040 if (removedFeature({3, 0, 0}, "'<=' connections", loc))
5041 return failure();
5042
5043 Value rhs;
5044 if (parseExp(rhs, "unexpected token in statement") || parseOptionalInfo())
5045 return failure();
5046
5047 locationProcessor.setLoc(loc);
5048
5049 auto lhsType = type_dyn_cast<FIRRTLBaseType>(lhs.getType());
5050 auto rhsType = type_dyn_cast<FIRRTLBaseType>(rhs.getType());
5051 if (!lhsType || !rhsType)
5052 return mlir::emitError(locationProcessor.getLoc(*this, loc),
5053 "cannot connect reference or property types");
5054 // TODO: Once support lands for agg-of-ref, add test for this check!
5055 if (lhsType.containsReference() || rhsType.containsReference())
5056 return mlir::emitError(locationProcessor.getLoc(*this, loc),
5057 "cannot connect types containing references");
5058
5059 if (!areTypesEquivalent(lhsType, rhsType))
5060 return mlir::emitError(locationProcessor.getLoc(*this, loc),
5061 "cannot connect non-equivalent type ")
5062 << rhsType << " to " << lhsType;
5064 builder, lhs, rhs, [&] { return locationProcessor.getLoc(*this, loc); },
5065 getConstants().options.warnOnTruncation);
5066 return success();
5067}
5068
5069//===-------------------------------
5070// FIRStmtParser Declaration Parsing
5071
5072/// instance ::= 'inst' id 'of' id info?
5073ParseResult FIRStmtParser::parseInstance() {
5074 auto startTok = consumeToken(FIRToken::kw_inst);
5075
5076 // If this was actually the start of a connect or something else handle
5077 // that.
5078 if (auto isExpr = parseExpWithLeadingKeyword(startTok))
5079 return *isExpr;
5080
5081 StringRef id;
5082 StringRef moduleName;
5083 if (parseId(id, "expected instance name") ||
5084 parseToken(FIRToken::kw_of, "expected 'of' in instance") ||
5085 parseId(moduleName, "expected module name") || parseOptionalInfo())
5086 return failure();
5087
5088 locationProcessor.setLoc(startTok.getLoc());
5089
5090 // Look up the module that is being referenced.
5091 auto referencedModule = getReferencedModule(startTok.getLoc(), moduleName);
5092 if (!referencedModule)
5093 return failure();
5094
5095 SmallVector<PortInfo> modulePorts = referencedModule.getPorts();
5096
5097 auto annotations = getConstants().emptyArrayAttr;
5098 SmallVector<Attribute, 4> portAnnotations(modulePorts.size(), annotations);
5099
5100 hw::InnerSymAttr sym = {};
5101 auto result = InstanceOp::create(
5102 builder, referencedModule, id, NameKindEnum::InterestingName,
5103 annotations.getValue(), portAnnotations, false, false, sym);
5104
5105 // Since we are implicitly unbundling the instance results, we need to keep
5106 // track of the mapping from bundle fields to results in the unbundledValues
5107 // data structure. Build our entry now.
5108 UnbundledValueEntry unbundledValueEntry;
5109 unbundledValueEntry.reserve(modulePorts.size());
5110 for (size_t i = 0, e = modulePorts.size(); i != e; ++i)
5111 unbundledValueEntry.push_back({modulePorts[i].name, result.getResult(i)});
5112
5113 // Add it to unbundledValues and add an entry to the symbol table to remember
5114 // it.
5115 moduleContext.unbundledValues.push_back(std::move(unbundledValueEntry));
5116 auto entryId = UnbundledID(moduleContext.unbundledValues.size());
5117 return moduleContext.addSymbolEntry(id, entryId, startTok.getLoc());
5118}
5119
5120/// instance_choice ::=
5121/// 'inst_choice' id 'of' id id info? newline indent ( id "=>" id )+ dedent
5122ParseResult FIRStmtParser::parseInstanceChoice() {
5123 auto startTok = consumeToken(FIRToken::kw_instchoice);
5124 SMLoc loc = startTok.getLoc();
5125
5126 // If this was actually the start of a connect or something else handle that.
5127 if (auto isExpr = parseExpWithLeadingKeyword(startTok))
5128 return *isExpr;
5129
5130 if (requireFeature(missingSpecFIRVersion, "option groups/instance choices"))
5131 return failure();
5132
5133 StringRef id;
5134 StringRef defaultModuleName;
5135 StringRef optionGroupName;
5136 if (parseId(id, "expected instance name") ||
5137 parseToken(FIRToken::kw_of, "expected 'of' in instance") ||
5138 parseId(defaultModuleName, "expected module name") ||
5139 parseToken(FIRToken::comma, "expected ','") ||
5140 parseId(optionGroupName, "expected option group name") ||
5141 parseToken(FIRToken::colon, "expected ':' after instchoice") ||
5142 parseOptionalInfo())
5143 return failure();
5144
5145 locationProcessor.setLoc(startTok.getLoc());
5146
5147 // Look up the default module referenced by the instance choice.
5148 // The port lists of all the other referenced modules must match this one.
5149 auto defaultModule = getReferencedModule(loc, defaultModuleName);
5150 if (!defaultModule)
5151 return failure();
5152
5153 SmallVector<PortInfo> modulePorts = defaultModule.getPorts();
5154
5155 // Find the option group.
5156 auto optionGroup = circuitSymTbl.lookup<OptionOp>(optionGroupName);
5157 if (!optionGroup)
5158 return emitError(loc,
5159 "use of undefined option group '" + optionGroupName + "'");
5160
5161 auto baseIndent = getIndentation();
5162 SmallVector<std::pair<OptionCaseOp, FModuleLike>> caseModules;
5163 while (getIndentation() == baseIndent) {
5164 StringRef caseId;
5165 StringRef caseModuleName;
5166 if (parseId(caseId, "expected a case identifier") ||
5167 parseToken(FIRToken::equal_greater,
5168 "expected '=> in instance choice definition") ||
5169 parseId(caseModuleName, "expected module name"))
5170 return failure();
5171
5172 auto caseModule = getReferencedModule(loc, caseModuleName);
5173 if (!caseModule)
5174 return failure();
5175
5176 for (const auto &[defaultPort, casePort] :
5177 llvm::zip(modulePorts, caseModule.getPorts())) {
5178 if (defaultPort.name != casePort.name)
5179 return emitError(loc, "instance case module port '")
5180 << casePort.name.getValue()
5181 << "' does not match the default module port '"
5182 << defaultPort.name.getValue() << "'";
5183 if (defaultPort.type != casePort.type)
5184 return emitError(loc, "instance case port '")
5185 << casePort.name.getValue()
5186 << "' type does not match the default module port";
5187 }
5188
5189 auto optionCase =
5190 dyn_cast_or_null<OptionCaseOp>(optionGroup.lookupSymbol(caseId));
5191 if (!optionCase)
5192 return emitError(loc, "use of undefined option case '" + caseId + "'");
5193 caseModules.emplace_back(optionCase, caseModule);
5194 }
5195
5196 auto annotations = getConstants().emptyArrayAttr;
5197 SmallVector<Attribute, 4> portAnnotations(modulePorts.size(), annotations);
5198
5199 // Create an instance choice op.
5200 StringAttr sym;
5201 auto result = InstanceChoiceOp::create(
5202 builder, defaultModule, caseModules, id, NameKindEnum::InterestingName,
5203 annotations.getValue(), portAnnotations, sym);
5204
5205 // Un-bundle the ports, identically to the regular instance operation.
5206 UnbundledValueEntry unbundledValueEntry;
5207 unbundledValueEntry.reserve(modulePorts.size());
5208 for (size_t i = 0, e = modulePorts.size(); i != e; ++i)
5209 unbundledValueEntry.push_back({modulePorts[i].name, result.getResult(i)});
5210
5211 moduleContext.unbundledValues.push_back(std::move(unbundledValueEntry));
5212 auto entryId = UnbundledID(moduleContext.unbundledValues.size());
5213 return moduleContext.addSymbolEntry(id, entryId, startTok.getLoc());
5214}
5215
5216FModuleLike FIRStmtParser::getReferencedModule(SMLoc loc,
5217 StringRef moduleName) {
5218 auto referencedModule = circuitSymTbl.lookup<FModuleLike>(moduleName);
5219 if (!referencedModule) {
5220 emitError(loc,
5221 "use of undefined module name '" + moduleName + "' in instance");
5222 return {};
5223 }
5224 if (isa<ClassOp /* ClassLike */>(referencedModule)) {
5225 emitError(loc, "cannot create instance of class '" + moduleName +
5226 "', did you mean object?");
5227 return {};
5228 }
5229 return referencedModule;
5230}
5231
5232/// object ::= 'object' id 'of' id info?
5233ParseResult FIRStmtParser::parseObject() {
5234 auto startTok = consumeToken(FIRToken::kw_object);
5235
5236 // If this was actually the start of a connect or something else handle
5237 // that.
5238 if (auto isExpr = parseExpWithLeadingKeyword(startTok))
5239 return *isExpr;
5240
5241 if (requireFeature({6, 0, 0}, "object statements"))
5242 return failure();
5243
5244 StringRef id;
5245 StringRef className;
5246 if (parseId(id, "expected object name") ||
5247 parseToken(FIRToken::kw_of, "expected 'of' in object") ||
5248 parseId(className, "expected class name") || parseOptionalInfo())
5249 return failure();
5250
5251 locationProcessor.setLoc(startTok.getLoc());
5252
5253 // Look up the class that is being referenced.
5254 const auto &classMap = getConstants().classMap;
5255 auto lookup = classMap.find(className);
5256 if (lookup == classMap.end())
5257 return emitError(startTok.getLoc(), "use of undefined class name '" +
5258 className + "' in object");
5259 auto referencedClass = lookup->getSecond();
5260 auto result = ObjectOp::create(builder, referencedClass, id);
5261 return moduleContext.addSymbolEntry(id, result, startTok.getLoc());
5262}
5263
5264/// cmem ::= 'cmem' id ':' type info?
5265ParseResult FIRStmtParser::parseCombMem() {
5266 // TODO(firrtl spec) cmem is completely undocumented.
5267 auto startTok = consumeToken(FIRToken::kw_cmem);
5268
5269 // If this was actually the start of a connect or something else handle
5270 // that.
5271 if (auto isExpr = parseExpWithLeadingKeyword(startTok))
5272 return *isExpr;
5273
5274 StringRef id;
5275 FIRRTLType type;
5276 if (parseId(id, "expected cmem name") ||
5277 parseToken(FIRToken::colon, "expected ':' in cmem") ||
5278 parseType(type, "expected cmem type") || parseOptionalInfo())
5279 return failure();
5280
5281 locationProcessor.setLoc(startTok.getLoc());
5282
5283 // Transform the parsed vector type into a memory type.
5284 auto vectorType = type_dyn_cast<FVectorType>(type);
5285 if (!vectorType)
5286 return emitError("cmem requires vector type");
5287
5288 auto annotations = getConstants().emptyArrayAttr;
5289 StringAttr sym = {};
5290 auto result = CombMemOp::create(
5291 builder, vectorType.getElementType(), vectorType.getNumElements(), id,
5292 NameKindEnum::InterestingName, annotations, sym);
5293 return moduleContext.addSymbolEntry(id, result, startTok.getLoc());
5294}
5295
5296/// smem ::= 'smem' id ':' type ruw? info?
5297ParseResult FIRStmtParser::parseSeqMem() {
5298 // TODO(firrtl spec) smem is completely undocumented.
5299 auto startTok = consumeToken(FIRToken::kw_smem);
5300
5301 // If this was actually the start of a connect or something else handle
5302 // that.
5303 if (auto isExpr = parseExpWithLeadingKeyword(startTok))
5304 return *isExpr;
5305
5306 StringRef id;
5307 FIRRTLType type;
5308 RUWBehavior ruw = RUWBehavior::Undefined;
5309
5310 if (parseId(id, "expected smem name") ||
5311 parseToken(FIRToken::colon, "expected ':' in smem") ||
5312 parseType(type, "expected smem type"))
5313 return failure();
5314
5315 if (consumeIf(FIRToken::comma)) {
5316 if (parseRUW(ruw))
5317 return failure();
5318 }
5319
5320 if (parseOptionalInfo()) {
5321 return failure();
5322 }
5323
5324 locationProcessor.setLoc(startTok.getLoc());
5325
5326 // Transform the parsed vector type into a memory type.
5327 auto vectorType = type_dyn_cast<FVectorType>(type);
5328 if (!vectorType)
5329 return emitError("smem requires vector type");
5330
5331 auto annotations = getConstants().emptyArrayAttr;
5332 StringAttr sym = {};
5333 auto result = SeqMemOp::create(
5334 builder, vectorType.getElementType(), vectorType.getNumElements(), ruw,
5335 id, NameKindEnum::InterestingName, annotations, sym);
5336 return moduleContext.addSymbolEntry(id, result, startTok.getLoc());
5337}
5338
5339/// mem ::= 'mem' id ':' info? INDENT memField* DEDENT
5340/// memField ::= 'data-type' '=>' type NEWLINE
5341/// ::= 'depth' '=>' intLit NEWLINE
5342/// ::= 'read-latency' '=>' intLit NEWLINE
5343/// ::= 'write-latency' '=>' intLit NEWLINE
5344/// ::= 'read-under-write' '=>' ruw NEWLINE
5345/// ::= 'reader' '=>' id+ NEWLINE
5346/// ::= 'writer' '=>' id+ NEWLINE
5347/// ::= 'readwriter' '=>' id+ NEWLINE
5348ParseResult FIRStmtParser::parseMem(unsigned memIndent) {
5349 auto startTok = consumeToken(FIRToken::kw_mem);
5350
5351 // If this was actually the start of a connect or something else handle
5352 // that.
5353 if (auto isExpr = parseExpWithLeadingKeyword(startTok))
5354 return *isExpr;
5355
5356 StringRef id;
5357 if (parseId(id, "expected mem name") ||
5358 parseToken(FIRToken::colon, "expected ':' in mem") || parseOptionalInfo())
5359 return failure();
5360
5361 FIRRTLType type;
5362 int64_t depth = -1, readLatency = -1, writeLatency = -1;
5363 RUWBehavior ruw = RUWBehavior::Undefined;
5364
5365 SmallVector<std::pair<StringAttr, Type>, 4> ports;
5366
5367 // Parse all the memfield records, which are indented more than the mem.
5368 while (1) {
5369 auto nextIndent = getIndentation();
5370 if (!nextIndent || *nextIndent <= memIndent)
5371 break;
5372
5373 auto spelling = getTokenSpelling();
5374 if (parseToken(FIRToken::identifier, "unexpected token in 'mem'") ||
5375 parseToken(FIRToken::equal_greater, "expected '=>' in 'mem'"))
5376 return failure();
5377
5378 if (spelling == "data-type") {
5379 if (type)
5380 return emitError("'mem' type specified multiple times"), failure();
5381
5382 if (parseType(type, "expected type in data-type declaration"))
5383 return failure();
5384 continue;
5385 }
5386 if (spelling == "depth") {
5387 if (parseIntLit(depth, "expected integer in depth specification"))
5388 return failure();
5389 continue;
5390 }
5391 if (spelling == "read-latency") {
5392 if (parseIntLit(readLatency, "expected integer latency"))
5393 return failure();
5394 continue;
5395 }
5396 if (spelling == "write-latency") {
5397 if (parseIntLit(writeLatency, "expected integer latency"))
5398 return failure();
5399 continue;
5400 }
5401 if (spelling == "read-under-write") {
5402 if (getToken().isNot(FIRToken::kw_old, FIRToken::kw_new,
5403 FIRToken::kw_undefined))
5404 return emitError("expected specifier"), failure();
5405
5406 if (parseOptionalRUW(ruw))
5407 return failure();
5408 continue;
5409 }
5410
5411 MemOp::PortKind portKind;
5412 if (spelling == "reader")
5413 portKind = MemOp::PortKind::Read;
5414 else if (spelling == "writer")
5415 portKind = MemOp::PortKind::Write;
5416 else if (spelling == "readwriter")
5417 portKind = MemOp::PortKind::ReadWrite;
5418 else
5419 return emitError("unexpected field in 'mem' declaration"), failure();
5420
5421 StringRef portName;
5422 if (parseId(portName, "expected port name"))
5423 return failure();
5424 auto baseType = type_dyn_cast<FIRRTLBaseType>(type);
5425 if (!baseType)
5426 return emitError("unexpected type, must be base type");
5427 ports.push_back({builder.getStringAttr(portName),
5428 MemOp::getTypeForPort(depth, baseType, portKind)});
5429
5430 while (!getIndentation().has_value()) {
5431 if (parseId(portName, "expected port name"))
5432 return failure();
5433 ports.push_back({builder.getStringAttr(portName),
5434 MemOp::getTypeForPort(depth, baseType, portKind)});
5435 }
5436 }
5437
5438 // The FIRRTL dialect requires mems to have at least one port. Since portless
5439 // mems can never be referenced, it is always safe to drop them.
5440 if (ports.empty())
5441 return success();
5442
5443 // Canonicalize the ports into alphabetical order.
5444 // TODO: Move this into MemOp construction/canonicalization.
5445 llvm::array_pod_sort(ports.begin(), ports.end(),
5446 [](const std::pair<StringAttr, Type> *lhs,
5447 const std::pair<StringAttr, Type> *rhs) -> int {
5448 return lhs->first.getValue().compare(
5449 rhs->first.getValue());
5450 });
5451
5452 auto annotations = getConstants().emptyArrayAttr;
5453 SmallVector<Attribute, 4> resultNames;
5454 SmallVector<Type, 4> resultTypes;
5455 SmallVector<Attribute, 4> resultAnnotations;
5456 for (auto p : ports) {
5457 resultNames.push_back(p.first);
5458 resultTypes.push_back(p.second);
5459 resultAnnotations.push_back(annotations);
5460 }
5461
5462 locationProcessor.setLoc(startTok.getLoc());
5463
5464 auto result = MemOp::create(
5465 builder, resultTypes, readLatency, writeLatency, depth, ruw,
5466 builder.getArrayAttr(resultNames), id, NameKindEnum::InterestingName,
5467 annotations, builder.getArrayAttr(resultAnnotations), hw::InnerSymAttr(),
5468 MemoryInitAttr(), StringAttr());
5469
5470 UnbundledValueEntry unbundledValueEntry;
5471 unbundledValueEntry.reserve(result.getNumResults());
5472 for (size_t i = 0, e = result.getNumResults(); i != e; ++i)
5473 unbundledValueEntry.push_back({resultNames[i], result.getResult(i)});
5474
5475 moduleContext.unbundledValues.push_back(std::move(unbundledValueEntry));
5476 auto entryID = UnbundledID(moduleContext.unbundledValues.size());
5477 return moduleContext.addSymbolEntry(id, entryID, startTok.getLoc());
5478}
5479
5480/// node ::= 'node' id '=' exp info?
5481ParseResult FIRStmtParser::parseNode() {
5482 auto startTok = consumeToken(FIRToken::kw_node);
5483
5484 // If this was actually the start of a connect or something else handle
5485 // that.
5486 if (auto isExpr = parseExpWithLeadingKeyword(startTok))
5487 return *isExpr;
5488
5489 StringRef id;
5490 Value initializer;
5491 if (parseId(id, "expected node name") ||
5492 parseToken(FIRToken::equal, "expected '=' in node") ||
5493 parseExp(initializer, "expected expression for node") ||
5494 parseOptionalInfo())
5495 return failure();
5496
5497 locationProcessor.setLoc(startTok.getLoc());
5498
5499 // Error out in the following conditions:
5500 //
5501 // 1. Node type is Analog (at the top level)
5502 // 2. Node type is not passive under an optional outer flip
5503 // (analog field is okay)
5504 //
5505 // Note: (1) is more restictive than normal NodeOp verification, but
5506 // this is added to align with the SFC. (2) is less restrictive than
5507 // the SFC to accomodate for situations where the node is something
5508 // weird like a module output or an instance input.
5509 auto initializerType = type_cast<FIRRTLType>(initializer.getType());
5510 auto initializerBaseType =
5511 type_dyn_cast<FIRRTLBaseType>(initializer.getType());
5512 if (type_isa<AnalogType>(initializerType) ||
5513 !(initializerBaseType && initializerBaseType.isPassive())) {
5514 emitError(startTok.getLoc())
5515 << "Node cannot be analog and must be passive or passive under a flip "
5516 << initializer.getType();
5517 return failure();
5518 }
5519
5520 auto annotations = getConstants().emptyArrayAttr;
5521 StringAttr sym = {};
5522
5523 auto result = NodeOp::create(builder, initializer, id,
5524 NameKindEnum::InterestingName, annotations, sym);
5525 return moduleContext.addSymbolEntry(id, result.getResult(),
5526 startTok.getLoc());
5527}
5528
5529/// wire ::= 'wire' id ':' type ('domains' '[' domain_list ']')? info?
5530ParseResult FIRStmtParser::parseWire() {
5531 auto startTok = consumeToken(FIRToken::kw_wire);
5532
5533 // If this was actually the start of a connect or something else handle
5534 // that.
5535 if (auto isExpr = parseExpWithLeadingKeyword(startTok))
5536 return *isExpr;
5537
5538 StringRef id;
5539 FIRRTLType type;
5540 if (parseId(id, "expected wire name") ||
5541 parseToken(FIRToken::colon, "expected ':' in wire") ||
5542 parseType(type, "expected wire type"))
5543 return failure();
5544
5545 // Parse optional domain associations
5546 SmallVector<Value> domains;
5547 if (consumeIf(FIRToken::kw_domains)) {
5548 if (requireFeature(missingSpecFIRVersion, "domains", startTok.getLoc()))
5549 return failure();
5550
5551 if (parseToken(FIRToken::l_square, "expected '[' after 'domains'"))
5552 return failure();
5553
5554 if (parseListUntil(FIRToken::r_square, [&]() -> ParseResult {
5555 StringRef domainName;
5556 auto domainLoc = getToken().getLoc();
5557 if (parseId(domainName, "expected domain name"))
5558 return failure();
5559
5560 // Look up the domain value in the module context
5561 SymbolValueEntry lookup;
5562 if (moduleContext.lookupSymbolEntry(lookup, domainName, domainLoc))
5563 return failure();
5564
5565 // Resolve the symbol table entry to a Value
5566 Value domainValue;
5567 if (moduleContext.resolveSymbolEntry(domainValue, lookup, domainLoc))
5568 return failure();
5569
5570 if (!isa<DomainType>(domainValue.getType()))
5571 return emitError(domainLoc)
5572 << "'" << domainName << "' is not a domain";
5573
5574 domains.push_back(domainValue);
5575 return success();
5576 }))
5577 return failure();
5578 }
5579
5580 if (parseOptionalInfo())
5581 return failure();
5582
5583 locationProcessor.setLoc(startTok.getLoc());
5584
5585 auto annotations = getConstants().emptyArrayAttr;
5586 StringAttr sym = {};
5587
5588 // Names of only-nonHW should be droppable.
5589 auto namekind = isa<PropertyType, RefType>(type)
5590 ? NameKindEnum::DroppableName
5591 : NameKindEnum::InterestingName;
5592
5593 auto result = WireOp::create(builder, type, id, namekind, annotations, sym,
5594 /*forceable=*/false, domains);
5595 return moduleContext.addSymbolEntry(id, result.getResult(),
5596 startTok.getLoc());
5597}
5598
5599/// register ::= 'reg' id ':' type exp ('with' ':' reset_block)? info?
5600///
5601/// reset_block ::= INDENT simple_reset info? NEWLINE DEDENT
5602/// ::= '(' simple_reset ')'
5603///
5604/// simple_reset ::= simple_reset0
5605/// ::= '(' simple_reset0 ')'
5606///
5607/// simple_reset0: 'reset' '=>' '(' exp exp ')'
5608///
5609ParseResult FIRStmtParser::parseRegister(unsigned regIndent) {
5610 auto startTok = consumeToken(FIRToken::kw_reg);
5611
5612 // If this was actually the start of a connect or something else handle
5613 // that.
5614 if (auto isExpr = parseExpWithLeadingKeyword(startTok))
5615 return *isExpr;
5616
5617 StringRef id;
5618 FIRRTLType type;
5619 Value clock;
5620
5621 // TODO(firrtl spec): info? should come after the clock expression before
5622 // the 'with'.
5623 if (parseId(id, "expected reg name") ||
5624 parseToken(FIRToken::colon, "expected ':' in reg") ||
5625 parseType(type, "expected reg type") ||
5626 parseToken(FIRToken::comma, "expected ','") ||
5627 parseExp(clock, "expected expression for register clock"))
5628 return failure();
5629
5630 if (!type_isa<FIRRTLBaseType>(type))
5631 return emitError(startTok.getLoc(), "register must have base type");
5632
5633 // Parse the 'with' specifier if present.
5634 Value resetSignal, resetValue;
5635 if (consumeIf(FIRToken::kw_with)) {
5636 if (removedFeature({3, 0, 0}, "'reg with' registers"))
5637 return failure();
5638
5639 if (parseToken(FIRToken::colon, "expected ':' in reg"))
5640 return failure();
5641
5642 // TODO(firrtl spec): Simplify the grammar for register reset logic.
5643 // Why allow multiple ambiguous parentheses? Why rely on indentation at
5644 // all?
5645
5646 // This implements what the examples have in practice.
5647 bool hasExtraLParen = consumeIf(FIRToken::l_paren);
5648
5649 auto indent = getIndentation();
5650 if (!indent || *indent <= regIndent)
5651 if (!hasExtraLParen)
5652 return emitError("expected indented reset specifier in reg"), failure();
5653
5654 if (parseToken(FIRToken::kw_reset, "expected 'reset' in reg") ||
5655 parseToken(FIRToken::equal_greater, "expected => in reset specifier") ||
5656 parseToken(FIRToken::l_paren, "expected '(' in reset specifier") ||
5657 parseExp(resetSignal, "expected expression for reset signal") ||
5658 parseToken(FIRToken::comma, "expected ','"))
5659 return failure();
5660
5661 // The Scala implementation of FIRRTL represents registers without resets
5662 // as a self referential register... and the pretty printer doesn't print
5663 // the right form. Recognize that this is happening and treat it as a
5664 // register without a reset for compatibility.
5665 // TODO(firrtl scala impl): pretty print registers without resets right.
5666 if (getTokenSpelling() == id) {
5667 consumeToken();
5668 if (parseToken(FIRToken::r_paren, "expected ')' in reset specifier"))
5669 return failure();
5670 resetSignal = Value();
5671 } else {
5672 if (parseExp(resetValue, "expected expression for reset value") ||
5673 parseToken(FIRToken::r_paren, "expected ')' in reset specifier"))
5674 return failure();
5675 }
5676
5677 if (hasExtraLParen &&
5678 parseToken(FIRToken::r_paren, "expected ')' in reset specifier"))
5679 return failure();
5680 }
5681
5682 // Finally, handle the last info if present, providing location info for the
5683 // clock expression.
5684 if (parseOptionalInfo())
5685 return failure();
5686
5687 locationProcessor.setLoc(startTok.getLoc());
5688
5689 ArrayAttr annotations = getConstants().emptyArrayAttr;
5690 Value result;
5691 StringAttr sym = {};
5692 if (resetSignal)
5693 result =
5694 RegResetOp::create(builder, type, clock, resetSignal, resetValue, id,
5695 NameKindEnum::InterestingName, annotations, sym)
5696 .getResult();
5697 else
5698 result = RegOp::create(builder, type, clock, id,
5699 NameKindEnum::InterestingName, annotations, sym)
5700 .getResult();
5701 return moduleContext.addSymbolEntry(id, result, startTok.getLoc());
5702}
5703
5704/// registerWithReset ::= 'regreset' id ':' type exp exp exp
5705///
5706/// This syntax is only supported in FIRRTL versions >= 3.0.0. Because this
5707/// syntax is only valid for >= 3.0.0, there is no need to check if the leading
5708/// "regreset" is part of an expression with a leading keyword.
5709ParseResult FIRStmtParser::parseRegisterWithReset() {
5710 auto startTok = consumeToken(FIRToken::kw_regreset);
5711
5712 StringRef id;
5713 FIRRTLType type;
5714 Value clock, resetSignal, resetValue;
5715
5716 if (parseId(id, "expected reg name") ||
5717 parseToken(FIRToken::colon, "expected ':' in reg") ||
5718 parseType(type, "expected reg type") ||
5719 parseToken(FIRToken::comma, "expected ','") ||
5720 parseExp(clock, "expected expression for register clock") ||
5721 parseToken(FIRToken::comma, "expected ','") ||
5722 parseExp(resetSignal, "expected expression for register reset") ||
5723 parseToken(FIRToken::comma, "expected ','") ||
5724 parseExp(resetValue, "expected expression for register reset value") ||
5725 parseOptionalInfo())
5726 return failure();
5727
5728 if (!type_isa<FIRRTLBaseType>(type))
5729 return emitError(startTok.getLoc(), "register must have base type");
5730
5731 locationProcessor.setLoc(startTok.getLoc());
5732
5733 auto result =
5734 RegResetOp::create(builder, type, clock, resetSignal, resetValue, id,
5735 NameKindEnum::InterestingName,
5736 getConstants().emptyArrayAttr, StringAttr{})
5737 .getResult();
5738
5739 return moduleContext.addSymbolEntry(id, result, startTok.getLoc());
5740}
5741
5742/// contract ::= 'contract' (id,+ '=' exp,+) ':' info? contract_body
5743/// contract_body ::= simple_stmt | INDENT simple_stmt+ DEDENT
5744ParseResult FIRStmtParser::parseContract(unsigned blockIndent) {
5745 if (requireFeature(missingSpecFIRVersion, "contracts"))
5746 return failure();
5747
5748 auto startTok = consumeToken(FIRToken::kw_contract);
5749
5750 // Parse the contract results and expressions.
5751 SmallVector<StringRef> ids;
5752 SmallVector<SMLoc> locs;
5753 SmallVector<Value> values;
5754 SmallVector<Type> types;
5755 if (!consumeIf(FIRToken::colon)) {
5756 auto parseContractId = [&] {
5757 StringRef id;
5758 locs.push_back(getToken().getLoc());
5759 if (parseId(id, "expected contract result name"))
5760 return failure();
5761 ids.push_back(id);
5762 return success();
5763 };
5764 auto parseContractValue = [&] {
5765 Value value;
5766 if (parseExp(value, "expected expression for contract result"))
5767 return failure();
5768 values.push_back(value);
5769 types.push_back(value.getType());
5770 return success();
5771 };
5772 if (parseListUntil(FIRToken::equal, parseContractId) ||
5773 parseListUntil(FIRToken::colon, parseContractValue))
5774 return failure();
5775 }
5776 if (parseOptionalInfo())
5777 return failure();
5778
5779 // Each result must have a corresponding expression assigned.
5780 if (ids.size() != values.size())
5781 return emitError(startTok.getLoc())
5782 << "contract requires same number of results and expressions; got "
5783 << ids.size() << " results and " << values.size()
5784 << " expressions instead";
5785
5786 locationProcessor.setLoc(startTok.getLoc());
5787
5788 // Add block arguments for each result and declare their names in a subscope
5789 // for the contract body.
5790 auto contract = ContractOp::create(builder, types, values);
5791 auto &block = contract.getBody().emplaceBlock();
5792
5793 // Parse the contract body.
5794 {
5795 FIRModuleContext::ContextScope scope(moduleContext, &block);
5796 for (auto [id, loc, type] : llvm::zip(ids, locs, types)) {
5797 auto arg = block.addArgument(type, LocWithInfo(loc, this).getLoc());
5798 if (failed(moduleContext.addSymbolEntry(id, arg, loc)))
5799 return failure();
5800 }
5801 if (getIndentation() > blockIndent)
5802 if (parseSubBlock(block, blockIndent, SymbolRefAttr{}))
5803 return failure();
5804 }
5805
5806 // Declare the results.
5807 for (auto [id, loc, value, result] :
5808 llvm::zip(ids, locs, values, contract.getResults())) {
5809 // Remove previous symbol to avoid duplicates
5810 moduleContext.removeSymbolEntry(id);
5811 if (failed(moduleContext.addSymbolEntry(id, result, loc)))
5812 return failure();
5813 }
5814 return success();
5815}
5816
5817//===----------------------------------------------------------------------===//
5818// FIRCircuitParser
5819//===----------------------------------------------------------------------===//
5820
5821namespace {
5822/// This class implements the outer level of the parser, including things
5823/// like circuit and module.
5824struct FIRCircuitParser : public FIRParser {
5825 explicit FIRCircuitParser(SharedParserConstants &state, FIRLexer &lexer,
5826 ModuleOp mlirModule, FIRVersion version)
5827 : FIRParser(state, lexer, version), mlirModule(mlirModule) {}
5828
5829 ParseResult
5830 parseCircuit(SmallVectorImpl<const llvm::MemoryBuffer *> &annotationsBuf,
5831 mlir::TimingScope &ts);
5832
5833private:
5834 /// Extract Annotations from a JSON-encoded Annotation array string and add
5835 /// them to a vector of attributes.
5836 ParseResult importAnnotationsRaw(SMLoc loc, StringRef annotationsStr,
5837 SmallVectorImpl<Attribute> &attrs);
5838
5839 ParseResult parseToplevelDefinition(CircuitOp circuit, unsigned indent);
5840
5841 ParseResult parseClass(CircuitOp circuit, unsigned indent);
5842 ParseResult parseDomain(CircuitOp circuit, unsigned indent);
5843 ParseResult parseExtClass(CircuitOp circuit, unsigned indent);
5844 ParseResult parseExtModule(CircuitOp circuit, unsigned indent);
5845 ParseResult parseIntModule(CircuitOp circuit, unsigned indent);
5846 ParseResult parseModule(CircuitOp circuit, bool isPublic, unsigned indent);
5847 ParseResult parseFormal(CircuitOp circuit, unsigned indent);
5848 ParseResult parseSimulation(CircuitOp circuit, unsigned indent);
5849 template <class Op>
5850 ParseResult parseFormalLike(CircuitOp circuit, unsigned indent);
5851
5852 ParseResult parseLayerName(SymbolRefAttr &result);
5853 ParseResult parseLayerList(SmallVectorImpl<Attribute> &result);
5854 ParseResult parseEnableLayerSpec(SmallVectorImpl<Attribute> &result);
5855 ParseResult parseKnownLayerSpec(SmallVectorImpl<Attribute> &result);
5856 ParseResult parseRequiresSpec(SmallVectorImpl<Attribute> &result);
5857 ParseResult parseModuleLayerSpec(ArrayAttr &enabledLayers);
5858 ParseResult parseExtModuleAttributesSpec(ArrayAttr &enabledLayers,
5859 ArrayAttr &knownLayers,
5860 ArrayAttr &externalRequirements);
5861
5862 ParseResult parsePortList(SmallVectorImpl<PortInfo> &resultPorts,
5863 SmallVectorImpl<SMLoc> &resultPortLocs,
5864 unsigned indent);
5865 ParseResult parseParameterList(ArrayAttr &resultParameters);
5866
5867 ParseResult skipToModuleEnd(unsigned indent);
5868
5869 ParseResult parseTypeDecl();
5870
5871 ParseResult parseOptionDecl(CircuitOp circuit);
5872
5873 ParseResult parseLayer(CircuitOp circuit);
5874
5875 ParseResult resolveDomains(
5876 const SmallVectorImpl<std::pair<Attribute, llvm::SMLoc>> &domainsByName,
5877 const DenseMap<Attribute, size_t> &nameToIndex,
5878 SmallVectorImpl<Attribute> &domainsByIndex);
5879
5880 ParseResult
5881 parseDomains(SmallVectorImpl<std::pair<Attribute, llvm::SMLoc>> &domains,
5882 const DenseMap<Attribute, size_t> &nameToIndex);
5883
5884 struct DeferredModuleToParse {
5885 FModuleLike moduleOp;
5886 SmallVector<SMLoc> portLocs;
5887 FIRLexerCursor lexerCursor;
5888 unsigned indent;
5889 };
5890
5891 ParseResult parseModuleBody(const SymbolTable &circuitSymTbl,
5892 DeferredModuleToParse &deferredModule,
5893 InnerSymFixups &fixups);
5894
5895 SmallVector<DeferredModuleToParse, 0> deferredModules;
5896
5897 SmallVector<InnerSymFixups, 0> moduleFixups;
5898
5899 hw::InnerSymbolNamespaceCollection innerSymbolNamespaces;
5900
5901 ModuleOp mlirModule;
5902};
5903
5904} // end anonymous namespace
5905ParseResult
5906FIRCircuitParser::importAnnotationsRaw(SMLoc loc, StringRef annotationsStr,
5907 SmallVectorImpl<Attribute> &attrs) {
5908
5909 auto annotations = json::parse(annotationsStr);
5910 if (auto err = annotations.takeError()) {
5911 handleAllErrors(std::move(err), [&](const json::ParseError &a) {
5912 auto diag = emitError(loc, "Failed to parse JSON Annotations");
5913 diag.attachNote() << a.message();
5914 });
5915 return failure();
5916 }
5917
5918 json::Path::Root root;
5919 llvm::StringMap<ArrayAttr> thisAnnotationMap;
5920 if (!importAnnotationsFromJSONRaw(annotations.get(), attrs, root,
5921 getContext())) {
5922 auto diag = emitError(loc, "Invalid/unsupported annotation format");
5923 std::string jsonErrorMessage =
5924 "See inline comments for problem area in JSON:\n";
5925 llvm::raw_string_ostream s(jsonErrorMessage);
5926 root.printErrorContext(annotations.get(), s);
5927 diag.attachNote() << jsonErrorMessage;
5928 return failure();
5929 }
5930
5931 return success();
5932}
5933
5934ParseResult FIRCircuitParser::parseLayerName(SymbolRefAttr &result) {
5935 auto *context = getContext();
5936 SmallVector<StringRef> strings;
5937 do {
5938 StringRef name;
5939 if (parseId(name, "expected layer name"))
5940 return failure();
5941 strings.push_back(name);
5942 } while (consumeIf(FIRToken::period));
5943
5944 SmallVector<FlatSymbolRefAttr> nested;
5945 nested.reserve(strings.size() - 1);
5946 for (unsigned i = 1, e = strings.size(); i < e; ++i)
5947 nested.push_back(FlatSymbolRefAttr::get(context, strings[i]));
5948
5949 result = SymbolRefAttr::get(context, strings[0], nested);
5950 return success();
5951}
5952
5953ParseResult FIRCircuitParser::parseModuleLayerSpec(ArrayAttr &enabledLayers) {
5954 SmallVector<Attribute> enabledLayersBuffer;
5955 while (true) {
5956 auto tokenKind = getToken().getKind();
5957 // Parse an enablelayer spec.
5958 if (tokenKind == FIRToken::kw_enablelayer) {
5959 if (parseEnableLayerSpec(enabledLayersBuffer))
5960 return failure();
5961 continue;
5962 }
5963 // Didn't parse a layer spec.
5964 break;
5965 }
5966
5967 if (enabledLayersBuffer.size() != 0)
5968 if (requireFeature({4, 0, 0}, "modules with layers enabled"))
5969 return failure();
5970
5971 enabledLayers = ArrayAttr::get(getContext(), enabledLayersBuffer);
5972 return success();
5973}
5974
5975ParseResult FIRCircuitParser::parseExtModuleAttributesSpec(
5976 ArrayAttr &enabledLayers, ArrayAttr &knownLayers,
5977 ArrayAttr &externalRequirements) {
5978 SmallVector<Attribute> enabledLayersBuffer;
5979 SmallVector<Attribute> knownLayersBuffer;
5980 SmallVector<Attribute> requirementsBuffer;
5981 while (true) {
5982 auto tokenKind = getToken().getKind();
5983 // Parse an enablelayer spec.
5984 if (tokenKind == FIRToken::kw_enablelayer) {
5985 if (parseEnableLayerSpec(enabledLayersBuffer))
5986 return failure();
5987 continue;
5988 }
5989 // Parse a knownlayer spec.
5990 if (tokenKind == FIRToken::kw_knownlayer) {
5991 if (parseKnownLayerSpec(knownLayersBuffer))
5992 return failure();
5993 continue;
5994 }
5995 // Parse a requires spec.
5996 if (tokenKind == FIRToken::kw_requires) {
5997 if (parseRequiresSpec(requirementsBuffer))
5998 return failure();
5999 continue;
6000 }
6001 // Didn't parse a layer spec or requires.
6002 break;
6003 }
6004
6005 if (enabledLayersBuffer.size() != 0)
6006 if (requireFeature({4, 0, 0}, "extmodules with layers enabled"))
6007 return failure();
6008
6009 if (knownLayersBuffer.size() != 0)
6010 if (requireFeature({6, 0, 0}, "extmodules with known layers"))
6011 return failure();
6012
6013 enabledLayers = ArrayAttr::get(getContext(), enabledLayersBuffer);
6014 knownLayers = ArrayAttr::get(getContext(), knownLayersBuffer);
6015 externalRequirements = ArrayAttr::get(getContext(), requirementsBuffer);
6016 return success();
6017}
6018
6019ParseResult
6020FIRCircuitParser::parseLayerList(SmallVectorImpl<Attribute> &result) {
6021 do {
6022 SymbolRefAttr layer;
6023 if (parseLayerName(layer))
6024 return failure();
6025 result.push_back(layer);
6026 } while (consumeIf(FIRToken::comma));
6027 return success();
6028}
6029
6030ParseResult
6031FIRCircuitParser::parseEnableLayerSpec(SmallVectorImpl<Attribute> &result) {
6032 consumeToken(FIRToken::kw_enablelayer);
6033 return parseLayerList(result);
6034}
6035
6036ParseResult
6037FIRCircuitParser::parseKnownLayerSpec(SmallVectorImpl<Attribute> &result) {
6038 consumeToken(FIRToken::kw_knownlayer);
6039 return parseLayerList(result);
6040}
6041
6042ParseResult
6043FIRCircuitParser::parseRequiresSpec(SmallVectorImpl<Attribute> &result) {
6044 consumeToken(FIRToken::kw_requires);
6045 do {
6046 StringRef requireStr;
6047 if (parseGetSpelling(requireStr) ||
6048 parseToken(FIRToken::string, "expected string after 'requires'"))
6049 return failure();
6050 // Remove the surrounding quotes from the string.
6051 result.push_back(
6052 StringAttr::get(getContext(), requireStr.drop_front().drop_back()));
6053 } while (consumeIf(FIRToken::comma));
6054 return success();
6055}
6056
6057/// portlist ::= port*
6058/// port ::= dir id ':' type info? NEWLINE
6059/// dir ::= 'input' | 'output'
6060ParseResult
6061FIRCircuitParser::parsePortList(SmallVectorImpl<PortInfo> &resultPorts,
6062 SmallVectorImpl<SMLoc> &resultPortLocs,
6063 unsigned indent) {
6064 // Stores of information about domains as they are parsed:
6065 // 1. Mapping of domain name to port index
6066 // 2. Mapping of port index to domain associations, using domain _names_.
6067 // The locations are recorded to generate good error messages.
6068 DenseMap<Attribute, size_t> nameToIndex;
6069 DenseMap<size_t, SmallVector<std::pair<Attribute, SMLoc>>> domainNames;
6070
6071 // Parse any ports. Populate domain information.
6072 while (getToken().isAny(FIRToken::kw_input, FIRToken::kw_output) &&
6073 // Must be nested under the module.
6074 getIndentation() > indent) {
6075
6076 // We need one token lookahead to resolve the ambiguity between:
6077 // output foo ; port
6078 // output <= input ; identifier expression
6079 // output.thing <= input ; identifier expression
6080 auto backtrackState = getLexer().getCursor();
6081
6082 bool isOutput = getToken().is(FIRToken::kw_output);
6083 consumeToken();
6084
6085 // If we have something that isn't a keyword then this must be an
6086 // identifier, not an input/output marker.
6087 if (!getToken().isAny(FIRToken::identifier, FIRToken::literal_identifier) &&
6088 !getToken().isKeyword()) {
6089 backtrackState.restore(getLexer());
6090 break;
6091 }
6092
6093 StringAttr name;
6094 FIRRTLType type;
6095 LocWithInfo info(getToken().getLoc(), this);
6096 if (parseId(name, "expected port name") ||
6097 parseToken(FIRToken::colon, "expected ':' in port definition") ||
6098 parseType(type, "expected a type in port declaration"))
6099 return failure();
6100 Attribute domainInfoElement = {};
6101 size_t portIdx = resultPorts.size();
6102 if (auto domainType = dyn_cast<DomainType>(type)) {
6103 // Domain information is now stored in the type itself.
6104 // Domain type ports have no associations.
6105 domainInfoElement = ArrayAttr::get(getContext(), {});
6106 } else {
6107 if (getToken().is(FIRToken::kw_domains))
6108 if (parseDomains(domainNames[portIdx], nameToIndex))
6109 return failure();
6110 }
6111
6112 if (info.parseOptionalInfo())
6113 return failure();
6114
6115 StringAttr innerSym = {};
6116 resultPorts.push_back(PortInfo{name,
6117 type,
6118 direction::get(isOutput),
6119 innerSym,
6120 info.getLoc(),
6121 {},
6122 domainInfoElement});
6123 resultPortLocs.push_back(info.getFIRLoc());
6124 nameToIndex.insert({name, portIdx});
6125 }
6126
6127 // Apply domain assocations to ports.
6128 for (size_t portIdx = 0, e = resultPorts.size(); portIdx != e; ++portIdx) {
6129 auto &port = resultPorts[portIdx];
6130 Attribute &attr = port.domains;
6131 if (attr)
6132 continue;
6133
6134 SmallVector<Attribute> domainInfo;
6135 if (failed(resolveDomains(domainNames[portIdx], nameToIndex, domainInfo)))
6136 return failure();
6137 attr = ArrayAttr::get(getContext(), domainInfo);
6138 }
6139
6140 // Check for port name collisions.
6141 SmallDenseMap<Attribute, SMLoc> portIds;
6142 for (auto portAndLoc : llvm::zip(resultPorts, resultPortLocs)) {
6143 PortInfo &port = std::get<0>(portAndLoc);
6144 auto &entry = portIds[port.name];
6145 if (!entry.isValid()) {
6146 entry = std::get<1>(portAndLoc);
6147 continue;
6148 }
6149
6150 emitError(std::get<1>(portAndLoc),
6151 "redefinition of name '" + port.getName() + "'")
6152 .attachNote(translateLocation(entry))
6153 << "previous definition here";
6154 return failure();
6155 }
6156
6157 return success();
6158}
6159
6160/// We're going to defer parsing this module, so just skip tokens until we
6161/// get to the next module or the end of the file.
6162ParseResult FIRCircuitParser::skipToModuleEnd(unsigned indent) {
6163 while (true) {
6164 switch (getToken().getKind()) {
6165
6166 // End of file or invalid token will be handled by outer level.
6167 case FIRToken::eof:
6168 case FIRToken::error:
6169 return success();
6170
6171 // If we got to the next top-level declaration, then we're done.
6172 case FIRToken::kw_class:
6173 case FIRToken::kw_domain:
6174 case FIRToken::kw_declgroup:
6175 case FIRToken::kw_extclass:
6176 case FIRToken::kw_extmodule:
6177 case FIRToken::kw_intmodule:
6178 case FIRToken::kw_formal:
6179 case FIRToken::kw_module:
6180 case FIRToken::kw_public:
6181 case FIRToken::kw_layer:
6182 case FIRToken::kw_option:
6183 case FIRToken::kw_simulation:
6184 case FIRToken::kw_type:
6185 // All module declarations should have the same indentation
6186 // level. Use this fact to differentiate between module
6187 // declarations and usages of "module" as identifiers.
6188 if (getIndentation() == indent)
6189 return success();
6190 [[fallthrough]];
6191 default:
6192 consumeToken();
6193 break;
6194 }
6195 }
6196}
6197
6198/// parameter-list ::= parameter*
6199/// parameter ::= 'parameter' param NEWLINE
6200ParseResult FIRCircuitParser::parseParameterList(ArrayAttr &resultParameters) {
6201 SmallVector<Attribute, 8> parameters;
6202 SmallPtrSet<StringAttr, 8> seen;
6203 while (consumeIf(FIRToken::kw_parameter)) {
6204 StringAttr name;
6205 Attribute value;
6206 SMLoc loc;
6207 if (parseParameter(name, value, loc))
6208 return failure();
6209 auto typedValue = dyn_cast<TypedAttr>(value);
6210 if (!typedValue)
6211 return emitError(loc)
6212 << "invalid value for parameter '" << name.getValue() << "'";
6213 if (!seen.insert(name).second)
6214 return emitError(loc,
6215 "redefinition of parameter '" + name.getValue() + "'");
6216 parameters.push_back(ParamDeclAttr::get(name, typedValue));
6217 }
6218 resultParameters = ArrayAttr::get(getContext(), parameters);
6219 return success();
6220}
6221
6222/// class ::= 'class' id ':' info? INDENT portlist simple_stmt_block DEDENT
6223ParseResult FIRCircuitParser::parseClass(CircuitOp circuit, unsigned indent) {
6224 StringAttr name;
6225 SmallVector<PortInfo, 8> portList;
6226 SmallVector<SMLoc> portLocs;
6227 LocWithInfo info(getToken().getLoc(), this);
6228
6229 if (requireFeature({6, 0, 0}, "classes"))
6230 return failure();
6231
6232 consumeToken(FIRToken::kw_class);
6233 if (parseId(name, "expected class name") ||
6234 parseToken(FIRToken::colon, "expected ':' in class definition") ||
6235 info.parseOptionalInfo() || parsePortList(portList, portLocs, indent))
6236 return failure();
6237
6238 if (name == circuit.getName())
6239 return mlir::emitError(info.getLoc(),
6240 "class cannot be the top of a circuit");
6241
6242 for (auto &portInfo : portList)
6243 if (!isa<PropertyType>(portInfo.type))
6244 return mlir::emitError(portInfo.loc,
6245 "ports on classes must be properties");
6246
6247 // build it
6248 auto builder = circuit.getBodyBuilder();
6249 auto classOp = ClassOp::create(builder, info.getLoc(), name, portList);
6250 classOp.setPrivate();
6251 deferredModules.emplace_back(
6252 DeferredModuleToParse{classOp, portLocs, getLexer().getCursor(), indent});
6253
6254 // Stash the class name -> op in the constants, so we can resolve Inst types.
6255 getConstants().classMap[name.getValue()] = classOp;
6256 return skipToModuleEnd(indent);
6257}
6258
6259/// domain ::= 'domain' id ':' info? (INDENT domain-field+ DEDENT)?
6260/// domain-field ::= id ':' property-type info? NEWLINE
6261ParseResult FIRCircuitParser::parseDomain(CircuitOp circuit, unsigned indent) {
6262 LocWithInfo info(getToken().getLoc(), this);
6263 consumeToken(FIRToken::kw_domain);
6264
6265 StringAttr name;
6266 if (parseId(name, "domain name") ||
6267 parseToken(FIRToken::colon, "expected ':' after domain definition") ||
6268 info.parseOptionalInfo())
6269 return failure();
6270
6271 SmallVector<Attribute> fields;
6272 SmallPtrSet<StringAttr, 4> nameSet;
6273 while (true) {
6274 auto nextIndent = getIndentation();
6275 if (!nextIndent || *nextIndent <= indent)
6276 break;
6277
6278 auto loc = getToken().getLoc();
6279 StringAttr fieldName;
6280 PropertyType type;
6281 LocationAttr fieldLoc; // ignore field locators
6282 if (parseId(fieldName, "field name") ||
6283 parseToken(FIRToken::colon, "expected ':' after field name") ||
6284 parsePropertyType(type, "field type") ||
6285 parseOptionalInfoLocator(fieldLoc))
6286 return failure();
6287
6288 // Verify that the names of each field are unique.
6289 if (!nameSet.insert(fieldName).second)
6290 return emitError(loc, "duplicate field name in domain: " +
6291 fieldName.getValue());
6292
6293 fields.push_back(
6294 DomainFieldAttr::get(circuit.getContext(), fieldName, type));
6295 }
6296
6297 auto builder = circuit.getBodyBuilder();
6298 auto domainOp =
6299 DomainOp::create(builder, info.getLoc(), name, /*sym_visibility=*/{},
6300 builder.getArrayAttr(fields));
6301
6302 // Stash the domain name -> op in the constants, so we can resolve Domain
6303 // types.
6304 getConstants().domainMap[name.getValue()] = domainOp;
6305
6306 return success();
6307}
6308
6309/// extclass ::= 'extclass' id ':' info? INDENT portlist DEDENT
6310ParseResult FIRCircuitParser::parseExtClass(CircuitOp circuit,
6311 unsigned indent) {
6312 StringAttr name;
6313 SmallVector<PortInfo, 8> portList;
6314 SmallVector<SMLoc> portLocs;
6315 LocWithInfo info(getToken().getLoc(), this);
6316
6317 if (requireFeature({6, 0, 0}, "classes"))
6318 return failure();
6319
6320 consumeToken(FIRToken::kw_extclass);
6321 if (parseId(name, "expected extclass name") ||
6322 parseToken(FIRToken::colon, "expected ':' in extclass definition") ||
6323 info.parseOptionalInfo() || parsePortList(portList, portLocs, indent))
6324 return failure();
6325
6326 if (name == circuit.getName())
6327 return mlir::emitError(info.getLoc(),
6328 "extclass cannot be the top of a circuit");
6329
6330 for (auto &portInfo : portList)
6331 if (!isa<PropertyType>(portInfo.type))
6332 return mlir::emitError(portInfo.loc,
6333 "ports on extclasses must be properties");
6334
6335 // Build it
6336 auto builder = circuit.getBodyBuilder();
6337 auto extClassOp = ExtClassOp::create(builder, info.getLoc(), name, portList);
6338
6339 // Stash the class name -> op in the constants, so we can resolve Inst types.
6340 getConstants().classMap[name.getValue()] = extClassOp;
6341 return skipToModuleEnd(indent);
6342}
6343
6344/// extmodule ::=
6345/// 'extmodule' id requires? ':' info?
6346/// INDENT portlist defname? parameter-list DEDENT
6347/// defname ::= 'defname' '=' id NEWLINE
6348/// requires ::= 'requires' string (',' string)*
6349ParseResult FIRCircuitParser::parseExtModule(CircuitOp circuit,
6350 unsigned indent) {
6351 StringAttr name;
6352 ArrayAttr enabledLayers;
6353 ArrayAttr knownLayers;
6354 ArrayAttr externalRequirements;
6355 SmallVector<PortInfo, 8> portList;
6356 SmallVector<SMLoc> portLocs;
6357 LocWithInfo info(getToken().getLoc(), this);
6358 consumeToken(FIRToken::kw_extmodule);
6359 if (parseId(name, "expected extmodule name") ||
6360 parseExtModuleAttributesSpec(enabledLayers, knownLayers,
6361 externalRequirements) ||
6362 parseToken(FIRToken::colon, "expected ':' in extmodule definition") ||
6363 info.parseOptionalInfo() || parsePortList(portList, portLocs, indent))
6364 return failure();
6365
6366 StringRef defName;
6367 if (consumeIf(FIRToken::kw_defname)) {
6368 if (parseToken(FIRToken::equal, "expected '=' in defname") ||
6369 parseId(defName, "expected defname name"))
6370 return failure();
6371 }
6372
6373 ArrayAttr parameters;
6374 if (parseParameterList(parameters))
6375 return failure();
6376
6377 if (version >= FIRVersion({4, 0, 0})) {
6378 for (auto [pi, loc] : llvm::zip_equal(portList, portLocs)) {
6379 if (auto ftype = type_dyn_cast<FIRRTLType>(pi.type)) {
6380 if (ftype.hasUninferredWidth())
6381 return emitError(loc, "extmodule port must have known width");
6382 }
6383 }
6384 }
6385
6386 auto builder = circuit.getBodyBuilder();
6387 auto isMainModule = (name == circuit.getName());
6388 auto convention =
6389 (isMainModule && getConstants().options.scalarizePublicModules) ||
6390 getConstants().options.scalarizeExtModules
6391 ? Convention::Scalarized
6392 : Convention::Internal;
6393 auto conventionAttr = ConventionAttr::get(getContext(), convention);
6394 auto annotations = ArrayAttr::get(getContext(), {});
6395 auto extModuleOp = FExtModuleOp::create(
6396 builder, info.getLoc(), name, conventionAttr, portList, knownLayers,
6397 defName, annotations, parameters, enabledLayers, externalRequirements);
6398 auto visibility = isMainModule ? SymbolTable::Visibility::Public
6399 : SymbolTable::Visibility::Private;
6400 SymbolTable::setSymbolVisibility(extModuleOp, visibility);
6401 return success();
6402}
6403
6404/// intmodule ::=
6405/// 'intmodule' id ':' info?
6406/// INDENT portlist intname parameter-list ref-list DEDENT
6407/// intname ::= 'intrinsic' '=' id NEWLINE
6408ParseResult FIRCircuitParser::parseIntModule(CircuitOp circuit,
6409 unsigned indent) {
6410 StringAttr name;
6411 StringRef intName;
6412 ArrayAttr enabledLayers;
6413 SmallVector<PortInfo, 8> portList;
6414 SmallVector<SMLoc> portLocs;
6415 LocWithInfo info(getToken().getLoc(), this);
6416 consumeToken(FIRToken::kw_intmodule);
6417 if (parseId(name, "expected intmodule name") ||
6418 parseModuleLayerSpec(enabledLayers) ||
6419 parseToken(FIRToken::colon, "expected ':' in intmodule definition") ||
6420 info.parseOptionalInfo() || parsePortList(portList, portLocs, indent) ||
6421 parseToken(FIRToken::kw_intrinsic, "expected 'intrinsic'") ||
6422 parseToken(FIRToken::equal, "expected '=' in intrinsic") ||
6423 parseId(intName, "expected intrinsic name"))
6424 return failure();
6425
6426 ArrayAttr parameters;
6427 if (parseParameterList(parameters))
6428 return failure();
6429
6430 ArrayAttr annotations = getConstants().emptyArrayAttr;
6431 auto builder = circuit.getBodyBuilder();
6432 FIntModuleOp::create(builder, info.getLoc(), name, portList, intName,
6433 annotations, parameters, enabledLayers)
6434 .setPrivate();
6435 return success();
6436}
6437
6438/// module ::= 'module' id ':' info? INDENT portlist simple_stmt_block DEDENT
6439ParseResult FIRCircuitParser::parseModule(CircuitOp circuit, bool isPublic,
6440 unsigned indent) {
6441 StringAttr name;
6442 SmallVector<PortInfo, 8> portList;
6443 SmallVector<SMLoc> portLocs;
6444 ArrayAttr enabledLayers;
6445 auto modLoc = getToken().getLoc();
6446 LocWithInfo info(modLoc, this);
6447 consumeToken(FIRToken::kw_module);
6448 if (parseId(name, "expected module name") ||
6449 parseModuleLayerSpec(enabledLayers) ||
6450 parseToken(FIRToken::colon, "expected ':' in module definition") ||
6451 info.parseOptionalInfo() || parsePortList(portList, portLocs, indent))
6452 return failure();
6453
6454 // The main module is implicitly public.
6455 if (name == circuit.getName()) {
6456 if (!isPublic && removedFeature({4, 0, 0}, "private main modules", modLoc))
6457 return failure();
6458 isPublic = true;
6459 }
6460
6461 if (isPublic && version >= FIRVersion({4, 0, 0})) {
6462 for (auto [pi, loc] : llvm::zip_equal(portList, portLocs)) {
6463 if (auto ftype = type_dyn_cast<FIRRTLType>(pi.type)) {
6464 if (ftype.hasUninferredWidth())
6465 return emitError(loc, "public module port must have known width");
6466 if (ftype.hasUninferredReset())
6467 return emitError(loc,
6468 "public module port must have concrete reset type");
6469 }
6470 }
6471 }
6472
6473 ArrayAttr annotations = getConstants().emptyArrayAttr;
6474 auto convention = Convention::Internal;
6475 if (isPublic && getConstants().options.scalarizePublicModules)
6476 convention = Convention::Scalarized;
6477 if (!isPublic && getConstants().options.scalarizeInternalModules)
6478 convention = Convention::Scalarized;
6479 auto conventionAttr = ConventionAttr::get(getContext(), convention);
6480 auto builder = circuit.getBodyBuilder();
6481 auto moduleOp =
6482 FModuleOp::create(builder, info.getLoc(), name, conventionAttr, portList,
6483 annotations, enabledLayers);
6484
6485 auto visibility = isPublic ? SymbolTable::Visibility::Public
6486 : SymbolTable::Visibility::Private;
6487 SymbolTable::setSymbolVisibility(moduleOp, visibility);
6488
6489 // Parse the body of this module after all prototypes have been parsed. This
6490 // allows us to handle forward references correctly.
6491 deferredModules.emplace_back(DeferredModuleToParse{
6492 moduleOp, portLocs, getLexer().getCursor(), indent});
6493
6494 if (skipToModuleEnd(indent))
6495 return failure();
6496 return success();
6497}
6498
6499/// formal ::= 'formal' formal-like
6500ParseResult FIRCircuitParser::parseFormal(CircuitOp circuit, unsigned indent) {
6501 consumeToken(FIRToken::kw_formal);
6502 return parseFormalLike<FormalOp>(circuit, indent);
6503}
6504
6505/// simulation ::= 'simulation' formal-like
6506ParseResult FIRCircuitParser::parseSimulation(CircuitOp circuit,
6507 unsigned indent) {
6508 consumeToken(FIRToken::kw_simulation);
6509 return parseFormalLike<SimulationOp>(circuit, indent);
6510}
6511
6512/// formal-like ::= formal-like-old | formal-like-new
6513/// formal-like-old ::= id 'of' id ',' 'bound' '=' int info?
6514/// formal-like-new ::= id 'of' id ':' info? INDENT (param NEWLINE)* DEDENT
6515template <class Op>
6516ParseResult FIRCircuitParser::parseFormalLike(CircuitOp circuit,
6517 unsigned indent) {
6518 StringRef id, moduleName;
6519 int64_t bound = 0;
6520 LocWithInfo info(getToken().getLoc(), this);
6521 auto builder = circuit.getBodyBuilder();
6522
6523 // Parse the name and target module of the test.
6524 if (parseId(id, "expected test name") ||
6525 parseToken(FIRToken::kw_of, "expected 'of' in test") ||
6526 parseId(moduleName, "expected module name"))
6527 return failure();
6528
6529 // TODO: Remove the old `, bound = N` variant in favor of the new parameters.
6530 NamedAttrList params;
6531 if (consumeIf(FIRToken::comma)) {
6532 // Parse the old style declaration with a `, bound = N` suffix.
6533 if (getToken().isNot(FIRToken::identifier) || getTokenSpelling() != "bound")
6534 return emitError("expected 'bound' after ','");
6535 consumeToken();
6536 if (parseToken(FIRToken::equal, "expected '=' after 'bound'") ||
6537 parseIntLit(bound, "expected integer bound after '='"))
6538 return failure();
6539 if (bound <= 0)
6540 return emitError("bound must be a positive integer");
6541 if (info.parseOptionalInfo())
6542 return failure();
6543 params.set("bound", builder.getIntegerAttr(builder.getI32Type(), bound));
6544 } else {
6545 // Parse the new style declaration with a `:` and parameter list.
6546 if (parseToken(FIRToken::colon, "expected ':' in test") ||
6547 info.parseOptionalInfo())
6548 return failure();
6549 while (getIndentation() > indent) {
6550 StringAttr paramName;
6551 Attribute paramValue;
6552 SMLoc paramLoc;
6553 if (parseParameter(paramName, paramValue, paramLoc,
6554 /*allowAggregates=*/true))
6555 return failure();
6556 if (params.set(paramName, paramValue))
6557 return emitError(paramLoc, "redefinition of parameter '" +
6558 paramName.getValue() + "'");
6559 }
6560 }
6561
6562 Op::create(builder, info.getLoc(), id, /*sym_visibility=*/{}, moduleName,
6563 params.getDictionary(getContext()));
6564 return success();
6565}
6566
6567ParseResult FIRCircuitParser::parseToplevelDefinition(CircuitOp circuit,
6568 unsigned indent) {
6569 switch (getToken().getKind()) {
6570 case FIRToken::kw_class:
6571 return parseClass(circuit, indent);
6572 case FIRToken::kw_declgroup:
6573 if (requireFeature({3, 2, 0}, "optional groups") ||
6574 removedFeature({3, 3, 0}, "optional groups"))
6575 return failure();
6576 return parseLayer(circuit);
6577 case FIRToken::kw_domain:
6578 if (requireFeature(missingSpecFIRVersion, "domains"))
6579 return failure();
6580 return parseDomain(circuit, indent);
6581 case FIRToken::kw_extclass:
6582 return parseExtClass(circuit, indent);
6583 case FIRToken::kw_extmodule:
6584 return parseExtModule(circuit, indent);
6585 case FIRToken::kw_formal:
6586 if (requireFeature({4, 0, 0}, "formal tests"))
6587 return failure();
6588 return parseFormal(circuit, indent);
6589 case FIRToken::kw_intmodule:
6590 if (requireFeature({1, 2, 0}, "intrinsic modules") ||
6591 removedFeature({4, 0, 0}, "intrinsic modules"))
6592 return failure();
6593 return parseIntModule(circuit, indent);
6594 case FIRToken::kw_layer:
6595 if (requireFeature({3, 3, 0}, "layers"))
6596 return failure();
6597 return parseLayer(circuit);
6598 case FIRToken::kw_module:
6599 return parseModule(circuit, /*isPublic=*/false, indent);
6600 case FIRToken::kw_public:
6601 if (requireFeature({3, 3, 0}, "public modules"))
6602 return failure();
6603 consumeToken();
6604 if (getToken().getKind() == FIRToken::kw_module)
6605 return parseModule(circuit, /*isPublic=*/true, indent);
6606 return emitError(getToken().getLoc(), "only modules may be public");
6607 case FIRToken::kw_simulation:
6608 if (requireFeature(nextFIRVersion, "simulation tests"))
6609 return failure();
6610 return parseSimulation(circuit, indent);
6611 case FIRToken::kw_type:
6612 return parseTypeDecl();
6613 case FIRToken::kw_option:
6614 if (requireFeature(missingSpecFIRVersion, "option groups/instance choices"))
6615 return failure();
6616 return parseOptionDecl(circuit);
6617 default:
6618 return emitError(getToken().getLoc(), "unknown toplevel definition");
6619 }
6620}
6621
6622// Parse a type declaration.
6623ParseResult FIRCircuitParser::parseTypeDecl() {
6624 StringRef id;
6625 FIRRTLType type;
6626 consumeToken();
6627 auto loc = getToken().getLoc();
6628
6629 if (getToken().isKeyword())
6630 return emitError(loc) << "cannot use keyword '" << getToken().getSpelling()
6631 << "' for type alias name";
6632
6633 if (parseId(id, "expected type name") ||
6634 parseToken(FIRToken::equal, "expected '=' in type decl") ||
6635 parseType(type, "expected a type"))
6636 return failure();
6637 auto name = StringAttr::get(type.getContext(), id);
6638 // Create type alias only for base types. Otherwise just pass through the
6639 // type.
6640 if (auto base = type_dyn_cast<FIRRTLBaseType>(type))
6641 type = BaseTypeAliasType::get(name, base);
6642 else
6643 emitWarning(loc)
6644 << "type alias for non-base type " << type
6645 << " is currently not supported. Type alias is stripped immediately";
6646
6647 if (!getConstants().aliasMap.insert({id, type}).second)
6648 return emitError(loc) << "type alias `" << name.getValue()
6649 << "` is already defined";
6650 return success();
6651}
6652
6653// Parse an option group declaration.
6654ParseResult FIRCircuitParser::parseOptionDecl(CircuitOp circuit) {
6655 StringRef id;
6656 LocWithInfo info(getToken().getLoc(), this);
6657 consumeToken();
6658
6659 if (parseId(id, "expected an option group name") ||
6660 parseToken(FIRToken::colon,
6661 "expected ':' after option group definition") ||
6662 info.parseOptionalInfo())
6663 return failure();
6664
6665 auto builder = OpBuilder::atBlockEnd(circuit.getBodyBlock());
6666 auto optionOp =
6667 OptionOp::create(builder, info.getLoc(), id, /*sym_visibility=*/{});
6668 auto *block = new Block;
6669 optionOp.getBody().push_back(block);
6670 builder.setInsertionPointToEnd(block);
6671
6672 auto baseIndent = getIndentation();
6673 StringSet<> cases;
6674 while (getIndentation() == baseIndent) {
6675 StringRef id;
6676 LocWithInfo caseInfo(getToken().getLoc(), this);
6677 if (parseId(id, "expected an option case ID") ||
6678 caseInfo.parseOptionalInfo())
6679 return failure();
6680
6681 if (!cases.insert(id).second)
6682 return emitError(caseInfo.getFIRLoc())
6683 << "duplicate option case definition '" << id << "'";
6684
6685 OptionCaseOp::create(builder, caseInfo.getLoc(), id);
6686 }
6687
6688 return success();
6689}
6690
6691// Parse a layer definition.
6692ParseResult FIRCircuitParser::parseLayer(CircuitOp circuit) {
6693 auto baseIndent = getIndentation();
6694
6695 // A stack of all layers that are possibly parents of the current layer.
6696 SmallVector<std::pair<std::optional<unsigned>, LayerOp>> layerStack;
6697
6698 // Parse a single layer and add it to the layerStack.
6699 auto parseOne = [&](Block *block) -> ParseResult {
6700 auto indent = getIndentation();
6701 StringRef id, convention;
6702 LocWithInfo info(getToken().getLoc(), this);
6703 consumeToken();
6704 if (parseId(id, "expected layer name") ||
6705 parseToken(FIRToken::comma, "expected ','") ||
6706 parseGetSpelling(convention))
6707 return failure();
6708
6709 auto layerConvention = symbolizeLayerConvention(convention);
6710 if (!layerConvention) {
6711 emitError() << "unknown convention '" << convention
6712 << "' (did you misspell it?)";
6713 return failure();
6714 }
6715 if (layerConvention == LayerConvention::Inline &&
6716 requireFeature({4, 1, 0}, "inline layers"))
6717 return failure();
6718 consumeToken();
6719
6720 hw::OutputFileAttr outputDir;
6721 if (consumeIf(FIRToken::comma)) {
6722 if (getToken().getKind() == FIRToken::string) {
6723 auto text = getToken().getStringValue();
6724 if (text.empty())
6725 return emitError() << "output directory must not be blank";
6726 outputDir = hw::OutputFileAttr::getAsDirectory(getContext(), text);
6727 consumeToken(FIRToken::string);
6728 }
6729 }
6730
6731 if (parseToken(FIRToken::colon, "expected ':' after layer definition") ||
6732 info.parseOptionalInfo())
6733 return failure();
6734 auto builder = OpBuilder::atBlockEnd(block);
6735 // Create the layer definition and give it an empty block.
6736 auto layerOp = LayerOp::create(builder, info.getLoc(), id,
6737 /*sym_visibility=*/{}, *layerConvention);
6738 layerOp->getRegion(0).push_back(new Block());
6739 if (outputDir)
6740 layerOp->setAttr("output_file", outputDir);
6741 layerStack.push_back({indent, layerOp});
6742 return success();
6743 };
6744
6745 if (parseOne(circuit.getBodyBlock()))
6746 return failure();
6747
6748 // Parse any nested layers.
6749 while (getIndentation() > baseIndent) {
6750 switch (getToken().getKind()) {
6751 case FIRToken::kw_declgroup:
6752 case FIRToken::kw_layer: {
6753 // Pop nested layers off the stack until we find out what layer to insert
6754 // this into.
6755 while (layerStack.back().first >= getIndentation())
6756 layerStack.pop_back();
6757 auto parentLayer = layerStack.back().second;
6758 if (parseOne(&parentLayer.getBody().front()))
6759 return failure();
6760 break;
6761 }
6762 default:
6763 return emitError("expected 'layer'"), failure();
6764 }
6765 }
6766
6767 return success();
6768}
6769
6770ParseResult FIRCircuitParser::resolveDomains(
6771 const SmallVectorImpl<std::pair<Attribute, llvm::SMLoc>> &domainsByName,
6772 const DenseMap<Attribute, size_t> &nameToIndex,
6773 SmallVectorImpl<Attribute> &domainsByIndex) {
6774
6775 for (auto [attr, loc] : domainsByName) {
6776 auto domain = cast<StringAttr>(attr);
6777 auto indexItr = nameToIndex.find(domain);
6778 if (indexItr == nameToIndex.end()) {
6779 emitError(loc) << "unknown domain name '" << domain.getValue() << "'";
6780 return failure();
6781 }
6782 domainsByIndex.push_back(IntegerAttr::get(
6783 IntegerType::get(getContext(), 32, IntegerType::Unsigned),
6784 indexItr->second));
6785 }
6786
6787 return success();
6788}
6789
6790ParseResult FIRCircuitParser::parseDomains(
6791 SmallVectorImpl<std::pair<Attribute, llvm::SMLoc>> &domains,
6792 const DenseMap<Attribute, size_t> &nameToIndex) {
6793 if (requireFeature(missingSpecFIRVersion, "domains"))
6794 return failure();
6795 if (parseToken(FIRToken::kw_domains, "expected 'domains'") ||
6796 parseToken(FIRToken::l_square, "expected '['"))
6797 return failure();
6798
6799 if (parseListUntil(FIRToken::r_square, [&]() -> ParseResult {
6800 StringAttr domain;
6801 auto domainLoc = getToken().getLoc();
6802 if (parseId(domain, "expected domain name"))
6803 return failure();
6804 domains.push_back({domain, domainLoc});
6805 return success();
6806 }))
6807 return failure();
6808
6809 return success();
6810}
6811
6812// Parse the body of this module.
6813ParseResult
6814FIRCircuitParser::parseModuleBody(const SymbolTable &circuitSymTbl,
6815 DeferredModuleToParse &deferredModule,
6816 InnerSymFixups &fixups) {
6817 FModuleLike moduleOp = deferredModule.moduleOp;
6818 auto &body = moduleOp->getRegion(0).front();
6819 auto &portLocs = deferredModule.portLocs;
6820
6821 // We parse the body of this module with its own lexer, enabling parallel
6822 // parsing with the rest of the other module bodies.
6823 FIRLexer moduleBodyLexer(getLexer().getSourceMgr(), getContext());
6824
6825 // Reset the parser/lexer state back to right after the port list.
6826 deferredModule.lexerCursor.restore(moduleBodyLexer);
6827
6828 FIRModuleContext moduleContext(&body, getConstants(), moduleBodyLexer,
6829 version);
6830
6831 // Install all of the ports into the symbol table, associated with their
6832 // block arguments.
6833 auto portList = moduleOp.getPorts();
6834 auto portArgs = body.getArguments();
6835 for (auto tuple : llvm::zip(portList, portLocs, portArgs)) {
6836 PortInfo &port = std::get<0>(tuple);
6837 llvm::SMLoc loc = std::get<1>(tuple);
6838 BlockArgument portArg = std::get<2>(tuple);
6839 assert(!port.sym);
6840 if (moduleContext.addSymbolEntry(port.getName(), portArg, loc))
6841 return failure();
6842 }
6843
6844 FIRStmtParser stmtParser(body, moduleContext, fixups, circuitSymTbl, version);
6845
6846 // Parse the moduleBlock.
6847 auto result = stmtParser.parseSimpleStmtBlock(deferredModule.indent);
6848 if (failed(result))
6849 return result;
6850
6851 return success();
6852}
6853
6854/// file ::= circuit
6855/// versionHeader ::= 'FIRRTL' 'version' versionLit NEWLINE
6856/// circuit ::= versionHeader? 'circuit' id ':' info? INDENT module* DEDENT EOF
6857///
6858/// If non-null, annotationsBuf is a memory buffer containing JSON annotations.
6859///
6860ParseResult FIRCircuitParser::parseCircuit(
6861 SmallVectorImpl<const llvm::MemoryBuffer *> &annotationsBufs,
6862 mlir::TimingScope &ts) {
6863
6864 auto indent = getIndentation();
6865 if (parseToken(FIRToken::kw_FIRRTL, "expected 'FIRRTL'"))
6866 return failure();
6867 if (!indent.has_value())
6868 return emitError("'FIRRTL' must be first token on its line");
6869 if (parseToken(FIRToken::kw_version, "expected version after 'FIRRTL'") ||
6870 parseVersionLit("expected version literal"))
6871 return failure();
6872 indent = getIndentation();
6873
6874 if (!indent.has_value())
6875 return emitError("'circuit' must be first token on its line");
6876 unsigned circuitIndent = *indent;
6877
6878 LocWithInfo info(getToken().getLoc(), this);
6879 StringAttr name;
6880 SMLoc inlineAnnotationsLoc;
6881 StringRef inlineAnnotations;
6882
6883 // A file must contain a top level `circuit` definition.
6884 if (parseToken(FIRToken::kw_circuit,
6885 "expected a top-level 'circuit' definition") ||
6886 parseId(name, "expected circuit name") ||
6887 parseToken(FIRToken::colon, "expected ':' in circuit definition") ||
6888 parseOptionalAnnotations(inlineAnnotationsLoc, inlineAnnotations) ||
6889 info.parseOptionalInfo())
6890 return failure();
6891
6892 // Create the top-level circuit op in the MLIR module.
6893 OpBuilder b(mlirModule.getBodyRegion());
6894 auto circuit = CircuitOp::create(b, info.getLoc(), name);
6895
6896 // A timer to get execution time of annotation parsing.
6897 auto parseAnnotationTimer = ts.nest("Parse annotations");
6898
6899 // Deal with any inline annotations, if they exist. These are processed
6900 // first to place any annotations from an annotation file *after* the inline
6901 // annotations. While arbitrary, this makes the annotation file have
6902 // "append" semantics.
6903 SmallVector<Attribute> annos;
6904 if (!inlineAnnotations.empty())
6905 if (importAnnotationsRaw(inlineAnnotationsLoc, inlineAnnotations, annos))
6906 return failure();
6907
6908 // Deal with the annotation file if one was specified
6909 for (auto *annotationsBuf : annotationsBufs)
6910 if (importAnnotationsRaw(info.getFIRLoc(), annotationsBuf->getBuffer(),
6911 annos))
6912 return failure();
6913
6914 parseAnnotationTimer.stop();
6915
6916 // Get annotations that are supposed to be specially handled by the
6917 // LowerAnnotations pass.
6918 if (!annos.empty())
6919 circuit->setAttr(rawAnnotations, b.getArrayAttr(annos));
6920
6921 // A timer to get execution time of module parsing.
6922 auto parseTimer = ts.nest("Parse modules");
6923 deferredModules.reserve(16);
6924
6925 // Parse any contained modules.
6926 while (true) {
6927 switch (getToken().getKind()) {
6928 // If we got to the end of the file, then we're done.
6929 case FIRToken::eof:
6930 goto DoneParsing;
6931
6932 // If we got an error token, then the lexer already emitted an error,
6933 // just stop. We could introduce error recovery if there was demand for
6934 // it.
6935 case FIRToken::error:
6936 return failure();
6937
6938 default:
6939 emitError("unexpected token in circuit");
6940 return failure();
6941
6942 case FIRToken::kw_class:
6943 case FIRToken::kw_declgroup:
6944 case FIRToken::kw_domain:
6945 case FIRToken::kw_extclass:
6946 case FIRToken::kw_extmodule:
6947 case FIRToken::kw_intmodule:
6948 case FIRToken::kw_layer:
6949 case FIRToken::kw_formal:
6950 case FIRToken::kw_module:
6951 case FIRToken::kw_option:
6952 case FIRToken::kw_public:
6953 case FIRToken::kw_simulation:
6954 case FIRToken::kw_type: {
6955 auto indent = getIndentation();
6956 if (!indent.has_value())
6957 return emitError("'module' must be first token on its line"), failure();
6958 unsigned definitionIndent = *indent;
6959
6960 if (definitionIndent <= circuitIndent)
6961 return emitError("module should be indented more"), failure();
6962
6963 if (parseToplevelDefinition(circuit, definitionIndent))
6964 return failure();
6965 break;
6966 }
6967 }
6968 }
6969
6970 // After the outline of the file has been parsed, we can go ahead and parse
6971 // all the bodies. This allows us to resolve forward-referenced modules and
6972 // makes it possible to parse their bodies in parallel.
6973DoneParsing:
6974 // Each of the modules may translate source locations, and doing so touches
6975 // the SourceMgr to build a line number cache. This isn't thread safe, so we
6976 // proactively touch it to make sure that it is always already created.
6977 (void)getLexer().translateLocation(info.getFIRLoc());
6978
6979 // Pre-verify symbol table, so we can construct it next. Ideally, we would do
6980 // this verification through the trait.
6981 { // Memory is tight in parsing.
6982 // Check that all symbols are uniquely named within child regions.
6983 DenseMap<Attribute, Location> nameToOrigLoc;
6984 for (auto &op : *circuit.getBodyBlock()) {
6985 // Check for a symbol name attribute.
6986 auto symbol = dyn_cast<mlir::SymbolOpInterface>(&op);
6987 if (!symbol)
6988 continue;
6989
6990 auto nameAttr = symbol.getNameAttr();
6991
6992 // Try to insert this symbol into the table.
6993 auto it = nameToOrigLoc.try_emplace(nameAttr, op.getLoc());
6994 if (!it.second) {
6995 op.emitError()
6996 .append("redefinition of symbol named '", nameAttr.getValue(), "'")
6997 .attachNote(it.first->second)
6998 .append("see existing symbol definition here");
6999 return failure();
7000 }
7001 }
7002 }
7003
7004 SymbolTable circuitSymTbl(circuit);
7005
7006 moduleFixups.resize(deferredModules.size());
7007
7008 // Stub out inner symbol namespace for each module,
7009 // none should be added so do this now to avoid walking later
7010 // to discover that this is the case.
7011 for (auto &d : deferredModules)
7012 innerSymbolNamespaces.get(d.moduleOp.getOperation());
7013
7014 // Next, parse all the module bodies.
7015 auto anyFailed = mlir::failableParallelForEachN(
7016 getContext(), 0, deferredModules.size(), [&](size_t index) {
7017 if (parseModuleBody(circuitSymTbl, deferredModules[index],
7018 moduleFixups[index]))
7019 return failure();
7020 return success();
7021 });
7022 if (failed(anyFailed))
7023 return failure();
7024
7025 // Walk operations created that have inner symbol references
7026 // that need replacing now that it's safe to create inner symbols everywhere.
7027 for (auto &fixups : moduleFixups) {
7028 if (failed(fixups.resolve(innerSymbolNamespaces)))
7029 return failure();
7030 }
7031
7032 // Helper to transform a layer name specification of the form `A::B::C` into
7033 // a SymbolRefAttr.
7034 auto parseLayerName = [&](StringRef name) -> Attribute {
7035 // Parse the layer name into a SymbolRefAttr.
7036 auto [head, rest] = name.split(".");
7037 SmallVector<FlatSymbolRefAttr> nestedRefs;
7038 while (!rest.empty()) {
7039 StringRef next;
7040 std::tie(next, rest) = rest.split(".");
7041 nestedRefs.push_back(FlatSymbolRefAttr::get(getContext(), next));
7042 }
7043 return SymbolRefAttr::get(getContext(), head, nestedRefs);
7044 };
7045
7046 auto getArrayAttr = [&](ArrayRef<std::string> strArray, auto getAttr) {
7047 SmallVector<Attribute> attrArray;
7048 auto *context = getContext();
7049 for (const auto &str : strArray)
7050 attrArray.push_back(getAttr(str));
7051 if (attrArray.empty())
7052 return ArrayAttr();
7053 return ArrayAttr::get(context, attrArray);
7054 };
7055
7056 if (auto enableLayers =
7057 getArrayAttr(getConstants().options.enableLayers, parseLayerName))
7058 circuit.setEnableLayersAttr(enableLayers);
7059 if (auto disableLayers =
7060 getArrayAttr(getConstants().options.disableLayers, parseLayerName))
7061 circuit.setDisableLayersAttr(disableLayers);
7062
7063 auto getStrAttr = [&](StringRef str) -> Attribute {
7064 return StringAttr::get(getContext(), str);
7065 };
7066
7067 if (auto selectInstChoice =
7068 getArrayAttr(getConstants().options.selectInstanceChoice, getStrAttr))
7069 circuit.setSelectInstChoiceAttr(selectInstChoice);
7070
7071 circuit.setDefaultLayerSpecialization(
7072 getConstants().options.defaultLayerSpecialization);
7073
7074 return success();
7075}
7076
7077//===----------------------------------------------------------------------===//
7078// Driver
7079//===----------------------------------------------------------------------===//
7080
7081// Parse the specified .fir file into the specified MLIR context.
7082mlir::OwningOpRef<mlir::ModuleOp>
7083circt::firrtl::importFIRFile(SourceMgr &sourceMgr, MLIRContext *context,
7084 mlir::TimingScope &ts, FIRParserOptions options) {
7085 const auto *sourceBuf = sourceMgr.getMemoryBuffer(sourceMgr.getMainFileID());
7086 SmallVector<const llvm::MemoryBuffer *> annotationsBufs;
7087 unsigned fileID = 1;
7088 for (unsigned e = options.numAnnotationFiles + 1; fileID < e; ++fileID)
7089 annotationsBufs.push_back(
7090 sourceMgr.getMemoryBuffer(sourceMgr.getMainFileID() + fileID));
7091
7092 context->loadDialect<CHIRRTLDialect>();
7093 context->loadDialect<FIRRTLDialect, hw::HWDialect>();
7094
7095 // This is the result module we are parsing into.
7096 mlir::OwningOpRef<mlir::ModuleOp> module(ModuleOp::create(
7097 FileLineColLoc::get(context, sourceBuf->getBufferIdentifier(),
7098 /*line=*/0,
7099 /*column=*/0)));
7100 SharedParserConstants state(context, options);
7101 FIRLexer lexer(sourceMgr, context);
7102 if (FIRCircuitParser(state, lexer, *module, minimumFIRVersion)
7103 .parseCircuit(annotationsBufs, ts))
7104 return nullptr;
7105
7106 // Make sure the parse module has no other structural problems detected by
7107 // the verifier.
7108 auto circuitVerificationTimer = ts.nest("Verify circuit");
7109 if (failed(verify(*module)))
7110 return {};
7111
7112 return module;
7113}
7114
7116 static mlir::TranslateToMLIRRegistration fromFIR(
7117 "import-firrtl", "import .fir",
7118 [](llvm::SourceMgr &sourceMgr, MLIRContext *context) {
7119 mlir::TimingScope ts;
7120 return importFIRFile(sourceMgr, context, ts);
7121 });
7122}
assert(baseType &&"element must be base type")
MlirType elementType
Definition CHIRRTL.cpp:29
static ParseResult parseParameterList(OpAsmParser &parser, SmallVector< Attribute > &parameters)
Parse an parameter list if present.
static std::unique_ptr< Context > context
static mlir::Operation * resolve(Context &context, mlir::SymbolRefAttr sym)
std::vector< UnbundledValueEntry > UnbundledValuesList
SmallVector< std::pair< Attribute, Value > > UnbundledValueEntry
llvm::PointerUnion< Value, UnbundledID > SymbolValueEntry
llvm::DenseMap< std::pair< Value, unsigned >, Value > SubaccessCache
ModuleSymbolTable::MapEntryTy ModuleSymbolTableEntry
llvm::StringMap< std::pair< SMLoc, SymbolValueEntry >, llvm::BumpPtrAllocator > ModuleSymbolTable
llvm::PointerEmbeddedInt< unsigned, 31 > UnbundledID
static ParseResult parseType(Type &result, StringRef name, AsmParser &parser)
Parse a type defined by this dialect.
static std::vector< mlir::Value > toVector(mlir::ValueRange range)
static Location getLoc(DefSlot slot)
Definition Mem2Reg.cpp:193
false return failure()
Parse an optional keyword or string and set instance into 'result'.
static ParseResult parsePortList(OpAsmParser &p, SmallVectorImpl< module_like_impl::PortParse > &result)
return success()
NamedAttrList attrs
This helper class is used to handle Info records, which specify higher level symbolic source location...
std::optional< Location > infoLoc
This is the location specified by the @ marker if present.
LocWithInfo(SMLoc firLoc, FIRParser *parser)
void setDefaultLoc(Location loc)
If we didn't parse an info locator for the specified value, this sets a default, overriding a fall ba...
FIRParser *const parser
SMLoc firLoc
This is the designated location in the .fir file for use when there is no @ info marker.
ParseResult parseOptionalInfo()
Parse an @info marker if present and update our location.
SMLoc getFIRLoc() const
FieldRef getSubField(unsigned subFieldID) const
Get a reference to a subfield.
Definition FieldRef.h:64
Value getValue() const
Get the Value which created this location.
Definition FieldRef.h:39
This implements a lexer for .fir files.
Definition FIRLexer.h:101
bool isNot(Kind k) const
Definition FIRLexer.h:61
StringRef getSpelling() const
Definition FIRLexer.h:45
bool is(Kind K) const
Definition FIRLexer.h:49
std::string getStringValue() const
Given a token containing a string literal, return its value, including removing the quote characters ...
Definition FIRLexer.cpp:58
llvm::SMLoc getLoc() const
Definition FIRLexer.cpp:33
static IntType get(MLIRContext *context, bool isSigned, int32_t widthOrSentinel=-1, bool isConst=false)
Return an SIntType or UIntType with the specified signedness, width, and constness.
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
Definition CalyxOps.cpp:56
mlir::Type innerType(mlir::Type type)
Definition ESITypes.cpp:423
RefType getForceableResultType(bool forceable, Type type)
Return null or forceable reference result type.
static Direction get(bool isOutput)
Return an output direction if isOutput is true, otherwise return an input direction.
Definition FIRRTLEnums.h:36
BaseTy type_cast(Type type)
Flow swapFlow(Flow flow)
Get a flow's reverse.
void registerFromFIRFileTranslation()
constexpr FIRVersion nextFIRVersion(7, 0, 0)
The next version of FIRRTL that is not yet released.
std::pair< bool, std::optional< mlir::LocationAttr > > maybeStringToLocation(llvm::StringRef spelling, bool skipParsing, mlir::StringAttr &locatorFilenameCache, FileLineColLoc &fileLineColLocCache, MLIRContext *context)
Flow foldFlow(Value val, Flow accumulatedFlow=Flow::Source)
Compute the flow for a Value, val, as determined by the FIRRTL specification.
constexpr const char * rawAnnotations
bool areTypesRefCastable(Type dstType, Type srcType)
Return true if destination ref type can be cast from source ref type, per FIRRTL spec rules they must...
bool areTypesEquivalent(FIRRTLType destType, FIRRTLType srcType, bool destOuterTypeIsConst=false, bool srcOuterTypeIsConst=false, bool requireSameWidths=false)
Returns whether the two types are equivalent.
hw::InnerRefAttr getInnerRefTo(const hw::InnerSymTarget &target, GetNamespaceCallback getNamespace)
Obtain an inner reference to the target (operation or port), adding an inner symbol as necessary.
void emitConnect(OpBuilder &builder, Location loc, Value lhs, Value rhs, bool warnOnTruncation=false)
Emit a connect between two values.
mlir::ParseResult parseFormatString(mlir::OpBuilder &builder, mlir::Location loc, llvm::StringRef formatString, llvm::ArrayRef< mlir::Value > specOperands, mlir::StringAttr &formatStringResult, llvm::SmallVectorImpl< mlir::Value > &operands)
mlir::OwningOpRef< mlir::ModuleOp > importFIRFile(llvm::SourceMgr &sourceMgr, mlir::MLIRContext *context, mlir::TimingScope &ts, FIRParserOptions options={})
BaseTy type_dyn_cast(Type type)
constexpr FIRVersion missingSpecFIRVersion
A marker for parser features that are currently missing from the spec.
Definition FIRParser.h:147
hw::InnerSymTarget getTargetFor(FieldRef ref)
Return the inner sym target for the specified value and fieldID.
bool type_isa(Type type)
constexpr FIRVersion minimumFIRVersion(2, 0, 0)
The current minimum version of FIRRTL that the parser supports.
bool importAnnotationsFromJSONRaw(llvm::json::Value &value, SmallVectorImpl< Attribute > &annotations, llvm::json::Path path, MLIRContext *context)
Deserialize a JSON value into FIRRTL Annotations.
void info(Twine message)
Definition LSPUtils.cpp:20
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
unsigned numAnnotationFiles
The number of annotation files that were specified on the command line.
Definition FIRParser.h:51
InfoLocHandling infoLocatorHandling
Definition FIRParser.h:47
InfoLocHandling
Specify how @info locators should be handled.
Definition FIRParser.h:37
@ IgnoreInfo
If this is set to true, the @info locators are ignored, and the locations are set to the location in ...
Definition FIRParser.h:40
The FIRRTL specification version.
Definition FIRParser.h:89
static std::optional< FIRVersion > fromString(StringRef str)
Parse a version string of the form "major.minor.patch".
Definition FIRParser.h:115