Loading [MathJax]/extensions/tex2jax.js
CIRCT 22.0.0git
All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Pages
SVOps.cpp
Go to the documentation of this file.
1//===- SVOps.cpp - Implement the SV operations ----------------------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implement the SV ops.
10//
11//===----------------------------------------------------------------------===//
12
22#include "mlir/IR/Builders.h"
23#include "mlir/IR/BuiltinTypes.h"
24#include "mlir/IR/Matchers.h"
25#include "mlir/IR/PatternMatch.h"
26#include "mlir/Interfaces/FunctionImplementation.h"
27#include "llvm/ADT/SmallString.h"
28#include "llvm/ADT/StringExtras.h"
29#include "llvm/ADT/TypeSwitch.h"
30
31#include <optional>
32
33using namespace circt;
34using namespace sv;
35using mlir::TypedAttr;
36
37/// Return true if the specified expression is 2-state. This is determined by
38/// looking at the defining op. This can look as far through the dataflow as it
39/// wants, but for now, it is just looking at the single value.
40bool sv::is2StateExpression(Value v) {
41 if (auto *op = v.getDefiningOp()) {
42 if (auto attr = op->getAttrOfType<UnitAttr>("twoState"))
43 return (bool)attr;
44 }
45 // Plain constants are obviously safe
46 return v.getDefiningOp<hw::ConstantOp>();
47}
48
49/// Return true if the specified operation is an expression.
50bool sv::isExpression(Operation *op) {
51 return isa<VerbatimExprOp, VerbatimExprSEOp, GetModportOp,
52 ReadInterfaceSignalOp, ConstantXOp, ConstantZOp, ConstantStrOp,
53 MacroRefExprOp, MacroRefExprSEOp>(op);
54}
55
56LogicalResult sv::verifyInProceduralRegion(Operation *op) {
57 if (op->getParentOp()->hasTrait<sv::ProceduralRegion>())
58 return success();
59 op->emitError() << op->getName() << " should be in a procedural region";
60 return failure();
61}
62
63LogicalResult sv::verifyInNonProceduralRegion(Operation *op) {
64 if (!op->getParentOp()->hasTrait<sv::ProceduralRegion>())
65 return success();
66 op->emitError() << op->getName() << " should be in a non-procedural region";
67 return failure();
68}
69
70/// Returns the operation registered with the given symbol name with the regions
71/// of 'symbolTableOp'. recurse through nested regions which don't contain the
72/// symboltable trait. Returns nullptr if no valid symbol was found.
73static Operation *lookupSymbolInNested(Operation *symbolTableOp,
74 StringRef symbol) {
75 Region &region = symbolTableOp->getRegion(0);
76 if (region.empty())
77 return nullptr;
78
79 // Look for a symbol with the given name.
80 StringAttr symbolNameId = StringAttr::get(symbolTableOp->getContext(),
81 SymbolTable::getSymbolAttrName());
82 for (Block &block : region)
83 for (Operation &nestedOp : block) {
84 auto nameAttr = nestedOp.getAttrOfType<StringAttr>(symbolNameId);
85 if (nameAttr && nameAttr.getValue() == symbol)
86 return &nestedOp;
87 if (!nestedOp.hasTrait<OpTrait::SymbolTable>() &&
88 nestedOp.getNumRegions()) {
89 if (auto *nop = lookupSymbolInNested(&nestedOp, symbol))
90 return nop;
91 }
92 }
93 return nullptr;
94}
95
96/// Verifies symbols referenced by macro identifiers.
97static LogicalResult
98verifyMacroIdentSymbolUses(Operation *op, FlatSymbolRefAttr attr,
99 SymbolTableCollection &symbolTable) {
100 auto *refOp = symbolTable.lookupNearestSymbolFrom(op, attr);
101 if (!refOp)
102 return op->emitError("references an undefined symbol: ") << attr;
103 if (!isa<MacroDeclOp>(refOp))
104 return op->emitError("must reference a macro declaration");
105 return success();
106}
107
108//===----------------------------------------------------------------------===//
109// VerbatimExprOp
110//===----------------------------------------------------------------------===//
111
112/// Get the asm name for sv.verbatim.expr and sv.verbatim.expr.se.
113static void
115 function_ref<void(Value, StringRef)> setNameFn) {
116 // If the string is macro like, then use a pretty name. We only take the
117 // string up to a weird character (like a paren) and currently ignore
118 // parenthesized expressions.
119 auto isOkCharacter = [](char c) { return llvm::isAlnum(c) || c == '_'; };
120 auto name = op->getAttrOfType<StringAttr>("format_string").getValue();
121 // Ignore a leading ` in macro name.
122 if (name.starts_with("`"))
123 name = name.drop_front();
124 name = name.take_while(isOkCharacter);
125 if (!name.empty())
126 setNameFn(op->getResult(0), name);
127}
128
129void VerbatimExprOp::getAsmResultNames(
130 function_ref<void(Value, StringRef)> setNameFn) {
131 getVerbatimExprAsmResultNames(getOperation(), std::move(setNameFn));
132}
133
134void VerbatimExprSEOp::getAsmResultNames(
135 function_ref<void(Value, StringRef)> setNameFn) {
136 getVerbatimExprAsmResultNames(getOperation(), std::move(setNameFn));
137}
138
139//===----------------------------------------------------------------------===//
140// MacroRefExprOp
141//===----------------------------------------------------------------------===//
142
143void MacroRefExprOp::getAsmResultNames(
144 function_ref<void(Value, StringRef)> setNameFn) {
145 setNameFn(getResult(), getMacroName());
146}
147
148void MacroRefExprSEOp::getAsmResultNames(
149 function_ref<void(Value, StringRef)> setNameFn) {
150 setNameFn(getResult(), getMacroName());
151}
152
153static MacroDeclOp getReferencedMacro(const hw::HWSymbolCache *cache,
154 Operation *op,
155 FlatSymbolRefAttr macroName) {
156 if (cache)
157 if (auto *result = cache->getDefinition(macroName.getAttr()))
158 return cast<MacroDeclOp>(result);
159
160 auto topLevelModuleOp = op->getParentOfType<ModuleOp>();
161 return topLevelModuleOp.lookupSymbol<MacroDeclOp>(macroName.getValue());
162}
163
164/// Lookup the module or extmodule for the symbol. This returns null on
165/// invalid IR.
166MacroDeclOp MacroRefExprOp::getReferencedMacro(const hw::HWSymbolCache *cache) {
167 return ::getReferencedMacro(cache, *this, getMacroNameAttr());
168}
169
170MacroDeclOp
171MacroRefExprSEOp::getReferencedMacro(const hw::HWSymbolCache *cache) {
172 return ::getReferencedMacro(cache, *this, getMacroNameAttr());
173}
174
175//===----------------------------------------------------------------------===//
176// MacroErrorOp
177//===----------------------------------------------------------------------===//
178
179std::string MacroErrorOp::getMacroIdentifier() {
180 const auto *prefix = "_ERROR";
181 auto msg = getMessage();
182 if (!msg || msg->empty())
183 return prefix;
184
185 std::string id(prefix);
186 id.push_back('_');
187 for (auto c : *msg) {
188 if (llvm::isAlnum(c))
189 id.push_back(c);
190 else
191 id.push_back('_');
192 }
193 return id;
194}
195
196//===----------------------------------------------------------------------===//
197// MacroDeclOp
198//===----------------------------------------------------------------------===//
199
200MacroDeclOp MacroDefOp::getReferencedMacro(const hw::HWSymbolCache *cache) {
201 return ::getReferencedMacro(cache, *this, getMacroNameAttr());
202}
203
204MacroDeclOp MacroRefOp::getReferencedMacro(const hw::HWSymbolCache *cache) {
205 return ::getReferencedMacro(cache, *this, getMacroNameAttr());
206}
207
208/// Ensure that the symbol being instantiated exists and is a MacroDefOp.
209LogicalResult
210MacroRefExprOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
211 return verifyMacroIdentSymbolUses(*this, getMacroNameAttr(), symbolTable);
212}
213
214/// Ensure that the symbol being instantiated exists and is a MacroDefOp.
215LogicalResult
216MacroRefExprSEOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
217 return verifyMacroIdentSymbolUses(*this, getMacroNameAttr(), symbolTable);
218}
219
220/// Ensure that the symbol being instantiated exists and is a MacroDefOp.
221LogicalResult MacroDefOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
222 return verifyMacroIdentSymbolUses(*this, getMacroNameAttr(), symbolTable);
223}
224
225/// Ensure that the symbol being instantiated exists and is a MacroDefOp.
226LogicalResult MacroRefOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
227 return verifyMacroIdentSymbolUses(*this, getMacroNameAttr(), symbolTable);
228}
229
230//===----------------------------------------------------------------------===//
231// MacroDeclOp
232//===----------------------------------------------------------------------===//
233
234StringRef MacroDeclOp::getMacroIdentifier() {
235 return getVerilogName().value_or(getSymName());
236}
237
238//===----------------------------------------------------------------------===//
239// ConstantXOp / ConstantZOp
240//===----------------------------------------------------------------------===//
241
242void ConstantXOp::getAsmResultNames(
243 function_ref<void(Value, StringRef)> setNameFn) {
244 SmallVector<char, 32> specialNameBuffer;
245 llvm::raw_svector_ostream specialName(specialNameBuffer);
246 specialName << "x_i" << getWidth();
247 setNameFn(getResult(), specialName.str());
248}
249
250LogicalResult ConstantXOp::verify() {
251 // We don't allow zero width constant or unknown width.
252 if (getWidth() <= 0)
253 return emitError("unsupported type");
254 return success();
255}
256
257void ConstantZOp::getAsmResultNames(
258 function_ref<void(Value, StringRef)> setNameFn) {
259 SmallVector<char, 32> specialNameBuffer;
260 llvm::raw_svector_ostream specialName(specialNameBuffer);
261 specialName << "z_i" << getWidth();
262 setNameFn(getResult(), specialName.str());
263}
264
265LogicalResult ConstantZOp::verify() {
266 // We don't allow zero width constant or unknown type.
267 if (getWidth() <= 0)
268 return emitError("unsupported type");
269 return success();
270}
271
272//===----------------------------------------------------------------------===//
273// LocalParamOp
274//===----------------------------------------------------------------------===//
275
276void LocalParamOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
277 // If the localparam has an optional 'name' attribute, use it.
278 auto nameAttr = (*this)->getAttrOfType<StringAttr>("name");
279 if (!nameAttr.getValue().empty())
280 setNameFn(getResult(), nameAttr.getValue());
281}
282
283LogicalResult LocalParamOp::verify() {
284 // Verify that this is a valid parameter value.
285 return hw::checkParameterInContext(
286 getValue(), (*this)->getParentOfType<hw::HWModuleOp>(), *this);
287}
288
289//===----------------------------------------------------------------------===//
290// RegOp
291//===----------------------------------------------------------------------===//
292
293static ParseResult
294parseImplicitInitType(OpAsmParser &p, mlir::Type regType,
295 std::optional<OpAsmParser::UnresolvedOperand> &initValue,
296 mlir::Type &initType) {
297 if (!initValue.has_value())
298 return success();
299
300 hw::InOutType ioType = dyn_cast<hw::InOutType>(regType);
301 if (!ioType)
302 return p.emitError(p.getCurrentLocation(), "expected inout type for reg");
303
304 initType = ioType.getElementType();
305 return success();
306}
307
308static void printImplicitInitType(OpAsmPrinter &p, Operation *op,
309 mlir::Type regType, mlir::Value initValue,
310 mlir::Type initType) {}
311
312void RegOp::build(OpBuilder &builder, OperationState &odsState,
313 Type elementType, StringAttr name, hw::InnerSymAttr innerSym,
314 mlir::Value initValue) {
315 if (!name)
316 name = builder.getStringAttr("");
317 odsState.addAttribute("name", name);
318 if (innerSym)
319 odsState.addAttribute(hw::InnerSymbolTable::getInnerSymbolAttrName(),
320 innerSym);
321 odsState.addTypes(hw::InOutType::get(elementType));
322 if (initValue)
323 odsState.addOperands(initValue);
324}
325
326/// Suggest a name for each result value based on the saved result names
327/// attribute.
328void RegOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
329 // If the wire has an optional 'name' attribute, use it.
330 auto nameAttr = (*this)->getAttrOfType<StringAttr>("name");
331 if (!nameAttr.getValue().empty())
332 setNameFn(getResult(), nameAttr.getValue());
333}
334
335std::optional<size_t> RegOp::getTargetResultIndex() { return 0; }
336
337// If this reg is only written to, delete the reg and all writers.
338LogicalResult RegOp::canonicalize(RegOp op, PatternRewriter &rewriter) {
339 // Block if op has SV attributes.
340 if (hasSVAttributes(op))
341 return failure();
342
343 // If the reg has a symbol, then we can't delete it.
344 if (op.getInnerSymAttr())
345 return failure();
346 // Check that all operations on the wire are sv.assigns. All other wire
347 // operations will have been handled by other canonicalization.
348 for (auto *user : op.getResult().getUsers())
349 if (!isa<AssignOp>(user))
350 return failure();
351
352 // Remove all uses of the wire.
353 for (auto *user : llvm::make_early_inc_range(op.getResult().getUsers()))
354 rewriter.eraseOp(user);
355
356 // Remove the wire.
357 rewriter.eraseOp(op);
358 return success();
359}
360
361//===----------------------------------------------------------------------===//
362// LogicOp
363//===----------------------------------------------------------------------===//
364
365void LogicOp::build(OpBuilder &builder, OperationState &odsState,
366 Type elementType, StringAttr name,
367 hw::InnerSymAttr innerSym) {
368 if (!name)
369 name = builder.getStringAttr("");
370 odsState.addAttribute("name", name);
371 if (innerSym)
372 odsState.addAttribute(hw::InnerSymbolTable::getInnerSymbolAttrName(),
373 innerSym);
374 odsState.addTypes(hw::InOutType::get(elementType));
375}
376
377/// Suggest a name for each result value based on the saved result names
378/// attribute.
379void LogicOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
380 // If the logic has an optional 'name' attribute, use it.
381 auto nameAttr = (*this)->getAttrOfType<StringAttr>("name");
382 if (!nameAttr.getValue().empty())
383 setNameFn(getResult(), nameAttr.getValue());
384}
385
386std::optional<size_t> LogicOp::getTargetResultIndex() { return 0; }
387
388//===----------------------------------------------------------------------===//
389// Control flow like-operations
390//===----------------------------------------------------------------------===//
391
392//===----------------------------------------------------------------------===//
393// IfDefOp
394//===----------------------------------------------------------------------===//
395
396void IfDefOp::build(OpBuilder &builder, OperationState &result, StringRef cond,
397 std::function<void()> thenCtor,
398 std::function<void()> elseCtor) {
399 build(builder, result, builder.getStringAttr(cond), std::move(thenCtor),
400 std::move(elseCtor));
401}
402
403void IfDefOp::build(OpBuilder &builder, OperationState &result, StringAttr cond,
404 std::function<void()> thenCtor,
405 std::function<void()> elseCtor) {
406 build(builder, result, FlatSymbolRefAttr::get(builder.getContext(), cond),
407 std::move(thenCtor), std::move(elseCtor));
408}
409
410void IfDefOp::build(OpBuilder &builder, OperationState &result,
411 FlatSymbolRefAttr cond, std::function<void()> thenCtor,
412 std::function<void()> elseCtor) {
413 build(builder, result, MacroIdentAttr::get(builder.getContext(), cond),
414 std::move(thenCtor), std::move(elseCtor));
415}
416
417void IfDefOp::build(OpBuilder &builder, OperationState &result,
418 MacroIdentAttr cond, std::function<void()> thenCtor,
419 std::function<void()> elseCtor) {
420 OpBuilder::InsertionGuard guard(builder);
421
422 result.addAttribute("cond", cond);
423 builder.createBlock(result.addRegion());
424
425 // Fill in the body of the #ifdef.
426 if (thenCtor)
427 thenCtor();
428
429 Region *elseRegion = result.addRegion();
430 if (elseCtor) {
431 builder.createBlock(elseRegion);
432 elseCtor();
433 }
434}
435
436LogicalResult IfDefOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
437 return verifyMacroIdentSymbolUses(*this, getCond().getIdent(), symbolTable);
438}
439
440// If both thenRegion and elseRegion are empty, erase op.
441template <class Op>
442static LogicalResult canonicalizeIfDefLike(Op op, PatternRewriter &rewriter) {
443 if (!op.getThenBlock()->empty())
444 return failure();
445
446 if (op.hasElse() && !op.getElseBlock()->empty())
447 return failure();
448
449 rewriter.eraseOp(op);
450 return success();
451}
452
453LogicalResult IfDefOp::canonicalize(IfDefOp op, PatternRewriter &rewriter) {
454 return canonicalizeIfDefLike(op, rewriter);
455}
456
457//===----------------------------------------------------------------------===//
458// IfDefProceduralOp
459//===----------------------------------------------------------------------===//
460
461void IfDefProceduralOp::build(OpBuilder &builder, OperationState &result,
462 StringRef cond, std::function<void()> thenCtor,
463 std::function<void()> elseCtor) {
464 build(builder, result, builder.getStringAttr(cond), std::move(thenCtor),
465 std::move(elseCtor));
466}
467
468void IfDefProceduralOp::build(OpBuilder &builder, OperationState &result,
469 StringAttr cond, std::function<void()> thenCtor,
470 std::function<void()> elseCtor) {
471 build(builder, result, FlatSymbolRefAttr::get(builder.getContext(), cond),
472 std::move(thenCtor), std::move(elseCtor));
473}
474
475void IfDefProceduralOp::build(OpBuilder &builder, OperationState &result,
476 FlatSymbolRefAttr cond,
477 std::function<void()> thenCtor,
478 std::function<void()> elseCtor) {
479 build(builder, result, MacroIdentAttr::get(builder.getContext(), cond),
480 std::move(thenCtor), std::move(elseCtor));
481}
482
483void IfDefProceduralOp::build(OpBuilder &builder, OperationState &result,
484 MacroIdentAttr cond,
485 std::function<void()> thenCtor,
486 std::function<void()> elseCtor) {
487 OpBuilder::InsertionGuard guard(builder);
488
489 result.addAttribute("cond", cond);
490 builder.createBlock(result.addRegion());
491
492 // Fill in the body of the #ifdef.
493 if (thenCtor)
494 thenCtor();
495
496 Region *elseRegion = result.addRegion();
497 if (elseCtor) {
498 builder.createBlock(elseRegion);
499 elseCtor();
500 }
501}
502
503LogicalResult IfDefProceduralOp::canonicalize(IfDefProceduralOp op,
504 PatternRewriter &rewriter) {
505 return canonicalizeIfDefLike(op, rewriter);
506}
507
508LogicalResult
509IfDefProceduralOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
510 return verifyMacroIdentSymbolUses(*this, getCond().getIdent(), symbolTable);
511}
512
513//===----------------------------------------------------------------------===//
514// IfOp
515//===----------------------------------------------------------------------===//
516
517void IfOp::build(OpBuilder &builder, OperationState &result, Value cond,
518 std::function<void()> thenCtor,
519 std::function<void()> elseCtor) {
520 OpBuilder::InsertionGuard guard(builder);
521
522 result.addOperands(cond);
523 builder.createBlock(result.addRegion());
524
525 // Fill in the body of the if.
526 if (thenCtor)
527 thenCtor();
528
529 Region *elseRegion = result.addRegion();
530 if (elseCtor) {
531 builder.createBlock(elseRegion);
532 elseCtor();
533 }
534}
535
536/// Replaces the given op with the contents of the given single-block region.
537static void replaceOpWithRegion(PatternRewriter &rewriter, Operation *op,
538 Region &region) {
539 assert(llvm::hasSingleElement(region) && "expected single-region block");
540 Block *fromBlock = &region.front();
541 // Merge it in above the specified operation.
542 op->getBlock()->getOperations().splice(Block::iterator(op),
543 fromBlock->getOperations());
544}
545
546LogicalResult IfOp::canonicalize(IfOp op, PatternRewriter &rewriter) {
547 // Block if op has SV attributes.
548 if (hasSVAttributes(op))
549 return failure();
550
551 if (auto constant = op.getCond().getDefiningOp<hw::ConstantOp>()) {
552
553 if (constant.getValue().isAllOnes())
554 replaceOpWithRegion(rewriter, op, op.getThenRegion());
555 else if (!op.getElseRegion().empty())
556 replaceOpWithRegion(rewriter, op, op.getElseRegion());
557
558 rewriter.eraseOp(op);
559
560 return success();
561 }
562
563 // Erase empty if-else block.
564 if (!op.getThenBlock()->empty() && op.hasElse() &&
565 op.getElseBlock()->empty()) {
566 rewriter.eraseBlock(op.getElseBlock());
567 return success();
568 }
569
570 // Erase empty if's.
571
572 // If there is stuff in the then block, leave this operation alone.
573 if (!op.getThenBlock()->empty())
574 return failure();
575
576 // If not and there is no else, then this operation is just useless.
577 if (!op.hasElse() || op.getElseBlock()->empty()) {
578 rewriter.eraseOp(op);
579 return success();
580 }
581
582 // Otherwise, invert the condition and move the 'else' block to the 'then'
583 // region if the condition is a 2-state operation. This changes x prop
584 // behavior so it needs to be guarded.
585 if (is2StateExpression(op.getCond())) {
586 auto cond = comb::createOrFoldNot(op.getLoc(), op.getCond(), rewriter);
587 op.setOperand(cond);
588
589 auto *thenBlock = op.getThenBlock(), *elseBlock = op.getElseBlock();
590
591 // Move the body of the then block over to the else.
592 thenBlock->getOperations().splice(thenBlock->end(),
593 elseBlock->getOperations());
594 rewriter.eraseBlock(elseBlock);
595 return success();
596 }
597 return failure();
598}
599
600//===----------------------------------------------------------------------===//
601// AlwaysOp
602//===----------------------------------------------------------------------===//
603
604AlwaysOp::Condition AlwaysOp::getCondition(size_t idx) {
605 return Condition{EventControl(cast<IntegerAttr>(getEvents()[idx]).getInt()),
606 getOperand(idx)};
607}
608
609void AlwaysOp::build(OpBuilder &builder, OperationState &result,
610 ArrayRef<sv::EventControl> events, ArrayRef<Value> clocks,
611 std::function<void()> bodyCtor) {
612 assert(events.size() == clocks.size() &&
613 "mismatch between event and clock list");
614 OpBuilder::InsertionGuard guard(builder);
615
616 SmallVector<Attribute> eventAttrs;
617 for (auto event : events)
618 eventAttrs.push_back(
619 builder.getI32IntegerAttr(static_cast<int32_t>(event)));
620 result.addAttribute("events", builder.getArrayAttr(eventAttrs));
621 result.addOperands(clocks);
622
623 // Set up the body. Moves the insert point
624 builder.createBlock(result.addRegion());
625
626 // Fill in the body of the #ifdef.
627 if (bodyCtor)
628 bodyCtor();
629}
630
631/// Ensure that the symbol being instantiated exists and is an InterfaceOp.
632LogicalResult AlwaysOp::verify() {
633 if (getEvents().size() != getNumOperands())
634 return emitError("different number of operands and events");
635 return success();
636}
637
638static ParseResult parseEventList(
639 OpAsmParser &p, Attribute &eventsAttr,
640 SmallVectorImpl<OpAsmParser::UnresolvedOperand> &clocksOperands) {
641
642 // Parse zero or more conditions intoevents and clocksOperands.
643 SmallVector<Attribute> events;
644
645 auto loc = p.getCurrentLocation();
646 StringRef keyword;
647 if (!p.parseOptionalKeyword(&keyword)) {
648 while (1) {
649 auto kind = sv::symbolizeEventControl(keyword);
650 if (!kind.has_value())
651 return p.emitError(loc, "expected 'posedge', 'negedge', or 'edge'");
652 auto eventEnum = static_cast<int32_t>(*kind);
653 events.push_back(p.getBuilder().getI32IntegerAttr(eventEnum));
654
655 clocksOperands.push_back({});
656 if (p.parseOperand(clocksOperands.back()))
657 return failure();
658
659 if (failed(p.parseOptionalComma()))
660 break;
661 if (p.parseKeyword(&keyword))
662 return failure();
663 }
664 }
665 eventsAttr = p.getBuilder().getArrayAttr(events);
666 return success();
667}
668
669static void printEventList(OpAsmPrinter &p, AlwaysOp op, ArrayAttr portsAttr,
670 OperandRange operands) {
671 for (size_t i = 0, e = op.getNumConditions(); i != e; ++i) {
672 if (i != 0)
673 p << ", ";
674 auto cond = op.getCondition(i);
675 p << stringifyEventControl(cond.event);
676 p << ' ';
677 p.printOperand(cond.value);
678 }
679}
680
681//===----------------------------------------------------------------------===//
682// AlwaysFFOp
683//===----------------------------------------------------------------------===//
684
685void AlwaysFFOp::build(OpBuilder &builder, OperationState &result,
686 EventControl clockEdge, Value clock,
687 std::function<void()> bodyCtor) {
688 OpBuilder::InsertionGuard guard(builder);
689
690 result.addAttribute(
691 "clockEdge", builder.getI32IntegerAttr(static_cast<int32_t>(clockEdge)));
692 result.addOperands(clock);
693 result.addAttribute(
694 "resetStyle",
695 builder.getI32IntegerAttr(static_cast<int32_t>(ResetType::NoReset)));
696
697 // Set up the body. Moves Insert Point
698 builder.createBlock(result.addRegion());
699
700 if (bodyCtor)
701 bodyCtor();
702
703 // Set up the reset region.
704 result.addRegion();
705}
706
707void AlwaysFFOp::build(OpBuilder &builder, OperationState &result,
708 EventControl clockEdge, Value clock,
709 ResetType resetStyle, EventControl resetEdge,
710 Value reset, std::function<void()> bodyCtor,
711 std::function<void()> resetCtor) {
712 OpBuilder::InsertionGuard guard(builder);
713
714 result.addAttribute(
715 "clockEdge", builder.getI32IntegerAttr(static_cast<int32_t>(clockEdge)));
716 result.addOperands(clock);
717 result.addAttribute("resetStyle", builder.getI32IntegerAttr(
718 static_cast<int32_t>(resetStyle)));
719 result.addAttribute(
720 "resetEdge", builder.getI32IntegerAttr(static_cast<int32_t>(resetEdge)));
721 result.addOperands(reset);
722
723 // Set up the body. Moves Insert Point.
724 builder.createBlock(result.addRegion());
725
726 if (bodyCtor)
727 bodyCtor();
728
729 // Set up the reset. Moves Insert Point.
730 builder.createBlock(result.addRegion());
731
732 if (resetCtor)
733 resetCtor();
734}
735
736//===----------------------------------------------------------------------===//
737// AlwaysCombOp
738//===----------------------------------------------------------------------===//
739
740void AlwaysCombOp::build(OpBuilder &builder, OperationState &result,
741 std::function<void()> bodyCtor) {
742 OpBuilder::InsertionGuard guard(builder);
743
744 builder.createBlock(result.addRegion());
745
746 if (bodyCtor)
747 bodyCtor();
748}
749
750//===----------------------------------------------------------------------===//
751// InitialOp
752//===----------------------------------------------------------------------===//
753
754void InitialOp::build(OpBuilder &builder, OperationState &result,
755 std::function<void()> bodyCtor) {
756 OpBuilder::InsertionGuard guard(builder);
757
758 builder.createBlock(result.addRegion());
759
760 // Fill in the body of the #ifdef.
761 if (bodyCtor)
762 bodyCtor();
763}
764
765//===----------------------------------------------------------------------===//
766// CaseOp
767//===----------------------------------------------------------------------===//
768
769/// Return the letter for the specified pattern bit, e.g. "0", "1", "x" or "z".
771 switch (bit) {
773 return '0';
775 return '1';
777 return 'x';
779 return 'z';
780 }
781 llvm_unreachable("invalid casez PatternBit");
782}
783
784/// Return the specified bit, bit 0 is the least significant bit.
785auto CaseBitPattern::getBit(size_t bitNumber) const -> CasePatternBit {
786 return CasePatternBit(unsigned(intAttr.getValue()[bitNumber * 2]) +
787 2 * unsigned(intAttr.getValue()[bitNumber * 2 + 1]));
788}
789
791 for (size_t i = 0, e = getWidth(); i != e; ++i)
792 if (getBit(i) == CasePatternBit::AnyX)
793 return true;
794 return false;
795}
796
798 for (size_t i = 0, e = getWidth(); i != e; ++i)
799 if (getBit(i) == CasePatternBit::AnyZ)
800 return true;
801 return false;
802}
803static SmallVector<CasePatternBit> getPatternBitsForValue(const APInt &value) {
804 SmallVector<CasePatternBit> result;
805 result.reserve(value.getBitWidth());
806 for (size_t i = 0, e = value.getBitWidth(); i != e; ++i)
807 result.push_back(CasePatternBit(value[i]));
808
809 return result;
810}
811
812// Get a CaseBitPattern from a specified list of PatternBits. Bits are
813// specified in most least significant order - element zero is the least
814// significant bit.
815CaseBitPattern::CaseBitPattern(const APInt &value, MLIRContext *context)
816 : CaseBitPattern(getPatternBitsForValue(value), context) {}
817
818// Get a CaseBitPattern from a specified list of PatternBits. Bits are
819// specified in most least significant order - element zero is the least
820// significant bit.
821CaseBitPattern::CaseBitPattern(ArrayRef<CasePatternBit> bits,
822 MLIRContext *context)
823 : CasePattern(CPK_bit) {
824 APInt pattern(bits.size() * 2, 0);
825 for (auto elt : llvm::reverse(bits)) {
826 pattern <<= 2;
827 pattern |= unsigned(elt);
828 }
829 auto patternType = IntegerType::get(context, bits.size() * 2);
830 intAttr = IntegerAttr::get(patternType, pattern);
831}
832
833auto CaseOp::getCases() -> SmallVector<CaseInfo, 4> {
834 SmallVector<CaseInfo, 4> result;
835 assert(getCasePatterns().size() == getNumRegions() &&
836 "case pattern / region count mismatch");
837 size_t nextRegion = 0;
838 for (auto elt : getCasePatterns()) {
839 llvm::TypeSwitch<Attribute>(elt)
840 .Case<hw::EnumFieldAttr>([&](auto enumAttr) {
841 result.push_back({std::make_unique<CaseEnumPattern>(enumAttr),
842 &getRegion(nextRegion++).front()});
843 })
844 .Case<IntegerAttr>([&](auto intAttr) {
845 result.push_back({std::make_unique<CaseBitPattern>(intAttr),
846 &getRegion(nextRegion++).front()});
847 })
848 .Case<CaseDefaultPattern::AttrType>([&](auto) {
849 result.push_back({std::make_unique<CaseDefaultPattern>(getContext()),
850 &getRegion(nextRegion++).front()});
851 })
852 .Default([](auto) {
853 assert(false && "invalid case pattern attribute type");
854 });
855 }
856
857 return result;
858}
859
861 return cast<hw::EnumFieldAttr>(enumAttr).getField();
862}
863
864/// Parse case op.
865/// case op ::= `sv.case` case-style? validation-qualifier? cond `:` type
866/// attr-dict case-pattern^*
867/// case-style ::= `case` | `casex` | `casez`
868/// validation-qualifier (see SV Spec 12.5.3) ::= `unique` | `unique0`
869/// | `priority`
870/// case-pattern ::= `case` bit-pattern `:` region
871ParseResult CaseOp::parse(OpAsmParser &parser, OperationState &result) {
872 auto &builder = parser.getBuilder();
873
874 OpAsmParser::UnresolvedOperand condOperand;
875 Type condType;
876
877 auto loc = parser.getCurrentLocation();
878
879 StringRef keyword;
880 if (!parser.parseOptionalKeyword(&keyword, {"case", "casex", "casez"})) {
881 auto kind = symbolizeCaseStmtType(keyword);
882 auto caseEnum = static_cast<int32_t>(kind.value());
883 result.addAttribute("caseStyle", builder.getI32IntegerAttr(caseEnum));
884 }
885
886 // Parse validation qualifier.
887 if (!parser.parseOptionalKeyword(
888 &keyword, {"plain", "priority", "unique", "unique0"})) {
889 auto kind = symbolizeValidationQualifierTypeEnum(keyword);
890 result.addAttribute("validationQualifier",
891 ValidationQualifierTypeEnumAttr::get(
892 builder.getContext(), kind.value()));
893 }
894
895 if (parser.parseOperand(condOperand) || parser.parseColonType(condType) ||
896 parser.parseOptionalAttrDict(result.attributes) ||
897 parser.resolveOperand(condOperand, condType, result.operands))
898 return failure();
899
900 // Check the integer type.
901 Type canonicalCondType = hw::getCanonicalType(condType);
902 hw::EnumType enumType = dyn_cast<hw::EnumType>(canonicalCondType);
903 unsigned condWidth = 0;
904 if (!enumType) {
905 if (!result.operands[0].getType().isSignlessInteger())
906 return parser.emitError(loc, "condition must have signless integer type");
907 condWidth = condType.getIntOrFloatBitWidth();
908 }
909
910 // Parse all the cases.
911 SmallVector<Attribute> casePatterns;
912 SmallVector<CasePatternBit, 16> caseBits;
913 while (1) {
914 if (succeeded(parser.parseOptionalKeyword("default"))) {
915 casePatterns.push_back(CaseDefaultPattern(parser.getContext()).attr());
916 } else if (failed(parser.parseOptionalKeyword("case"))) {
917 // Not default or case, must be the end of the cases.
918 break;
919 } else if (enumType) {
920 // Enumerated case; parse the case value.
921 StringRef caseVal;
922
923 if (parser.parseKeyword(&caseVal))
924 return failure();
925
926 if (!enumType.contains(caseVal))
927 return parser.emitError(loc)
928 << "case value '" + caseVal + "' is not a member of enum type "
929 << enumType;
930 casePatterns.push_back(
931 hw::EnumFieldAttr::get(parser.getEncodedSourceLoc(loc),
932 builder.getStringAttr(caseVal), condType));
933 } else {
934 // Parse the pattern. It always starts with b, so it is an MLIR
935 // keyword.
936 StringRef caseVal;
937 loc = parser.getCurrentLocation();
938 if (parser.parseKeyword(&caseVal))
939 return failure();
940
941 if (caseVal.front() != 'b')
942 return parser.emitError(loc, "expected case value starting with 'b'");
943 caseVal = caseVal.drop_front();
944
945 // Parse and decode each bit, we reverse the list later for MSB->LSB.
946 for (; !caseVal.empty(); caseVal = caseVal.drop_front()) {
947 CasePatternBit bit;
948 switch (caseVal.front()) {
949 case '0':
951 break;
952 case '1':
954 break;
955 case 'x':
957 break;
958 case 'z':
960 break;
961 default:
962 return parser.emitError(loc, "unexpected case bit '")
963 << caseVal.front() << "'";
964 }
965 caseBits.push_back(bit);
966 }
967
968 if (caseVal.size() > condWidth)
969 return parser.emitError(loc, "too many bits specified in pattern");
970 std::reverse(caseBits.begin(), caseBits.end());
971
972 // High zeros may be missing.
973 if (caseBits.size() < condWidth)
974 caseBits.append(condWidth - caseBits.size(), CasePatternBit::Zero);
975
976 auto resultPattern = CaseBitPattern(caseBits, builder.getContext());
977 casePatterns.push_back(resultPattern.attr());
978 caseBits.clear();
979 }
980
981 // Parse the case body.
982 auto caseRegion = std::make_unique<Region>();
983 if (parser.parseColon() || parser.parseRegion(*caseRegion))
984 return failure();
985 result.addRegion(std::move(caseRegion));
986 }
987
988 result.addAttribute("casePatterns", builder.getArrayAttr(casePatterns));
989 return success();
990}
991
992void CaseOp::print(OpAsmPrinter &p) {
993 p << ' ';
994 if (getCaseStyle() == CaseStmtType::CaseXStmt)
995 p << "casex ";
996 else if (getCaseStyle() == CaseStmtType::CaseZStmt)
997 p << "casez ";
998
999 if (getValidationQualifier() !=
1000 ValidationQualifierTypeEnum::ValidationQualifierPlain)
1001 p << stringifyValidationQualifierTypeEnum(getValidationQualifier()) << ' ';
1002
1003 p << getCond() << " : " << getCond().getType();
1004 p.printOptionalAttrDict(
1005 (*this)->getAttrs(),
1006 /*elidedAttrs=*/{"casePatterns", "caseStyle", "validationQualifier"});
1007
1008 for (auto &caseInfo : getCases()) {
1009 p.printNewline();
1010 auto &pattern = caseInfo.pattern;
1011
1012 llvm::TypeSwitch<CasePattern *>(pattern.get())
1013 .Case<CaseBitPattern>([&](auto bitPattern) {
1014 p << "case b";
1015 for (size_t bit = 0, e = bitPattern->getWidth(); bit != e; ++bit)
1016 p << getLetter(bitPattern->getBit(e - bit - 1));
1017 })
1018 .Case<CaseEnumPattern>([&](auto enumPattern) {
1019 p << "case " << enumPattern->getFieldValue();
1020 })
1021 .Case<CaseDefaultPattern>([&](auto) { p << "default"; })
1022 .Default([&](auto) { assert(false && "unhandled case pattern"); });
1023
1024 p << ": ";
1025 p.printRegion(*caseInfo.block->getParent(), /*printEntryBlockArgs=*/false,
1026 /*printBlockTerminators=*/true);
1027 }
1028}
1029
1030LogicalResult CaseOp::verify() {
1031 if (!(hw::isHWIntegerType(getCond().getType()) ||
1032 hw::isHWEnumType(getCond().getType())))
1033 return emitError("condition must have either integer or enum type");
1034
1035 // Ensure that the number of regions and number of case values match.
1036 if (getCasePatterns().size() != getNumRegions())
1037 return emitOpError("case pattern / region count mismatch");
1038 return success();
1039}
1040
1041/// This ctor allows you to build a CaseZ with some number of cases, getting
1042/// a callback for each case.
1043void CaseOp::build(
1044 OpBuilder &builder, OperationState &result, CaseStmtType caseStyle,
1045 ValidationQualifierTypeEnum validationQualifier, Value cond,
1046 size_t numCases,
1047 std::function<std::unique_ptr<CasePattern>(size_t)> caseCtor) {
1048 result.addOperands(cond);
1049 result.addAttribute("caseStyle",
1050 CaseStmtTypeAttr::get(builder.getContext(), caseStyle));
1051 result.addAttribute("validationQualifier",
1052 ValidationQualifierTypeEnumAttr::get(
1053 builder.getContext(), validationQualifier));
1054 SmallVector<Attribute> casePatterns;
1055
1056 OpBuilder::InsertionGuard guard(builder);
1057
1058 // Fill in the cases with the callback.
1059 for (size_t i = 0, e = numCases; i != e; ++i) {
1060 builder.createBlock(result.addRegion());
1061 casePatterns.push_back(caseCtor(i)->attr());
1062 }
1063
1064 result.addAttribute("casePatterns", builder.getArrayAttr(casePatterns));
1065}
1066
1067// Strength reduce case styles based on the bit patterns.
1068LogicalResult CaseOp::canonicalize(CaseOp op, PatternRewriter &rewriter) {
1069 if (op.getCaseStyle() == CaseStmtType::CaseStmt)
1070 return failure();
1071 if (isa<hw::EnumType>(op.getCond().getType()))
1072 return failure();
1073
1074 auto caseInfo = op.getCases();
1075 bool noXZ = llvm::all_of(caseInfo, [](const CaseInfo &ci) {
1076 return !ci.pattern.get()->hasX() && !ci.pattern.get()->hasZ();
1077 });
1078 bool noX = llvm::all_of(caseInfo, [](const CaseInfo &ci) {
1079 if (isa<CaseDefaultPattern>(ci.pattern))
1080 return true;
1081 return !ci.pattern.get()->hasX();
1082 });
1083 bool noZ = llvm::all_of(caseInfo, [](const CaseInfo &ci) {
1084 if (isa<CaseDefaultPattern>(ci.pattern))
1085 return true;
1086 return !ci.pattern.get()->hasZ();
1087 });
1088
1089 if (op.getCaseStyle() == CaseStmtType::CaseXStmt) {
1090 if (noXZ) {
1091 rewriter.modifyOpInPlace(op, [&]() {
1092 op.setCaseStyleAttr(
1093 CaseStmtTypeAttr::get(op.getContext(), CaseStmtType::CaseStmt));
1094 });
1095 return success();
1096 }
1097 if (noX) {
1098 rewriter.modifyOpInPlace(op, [&]() {
1099 op.setCaseStyleAttr(
1100 CaseStmtTypeAttr::get(op.getContext(), CaseStmtType::CaseZStmt));
1101 });
1102 return success();
1103 }
1104 }
1105
1106 if (op.getCaseStyle() == CaseStmtType::CaseZStmt && noZ) {
1107 rewriter.modifyOpInPlace(op, [&]() {
1108 op.setCaseStyleAttr(
1109 CaseStmtTypeAttr::get(op.getContext(), CaseStmtType::CaseStmt));
1110 });
1111 return success();
1112 }
1113
1114 return failure();
1115}
1116
1117//===----------------------------------------------------------------------===//
1118// OrderedOutputOp
1119//===----------------------------------------------------------------------===//
1120
1121void OrderedOutputOp::build(OpBuilder &builder, OperationState &result,
1122 std::function<void()> body) {
1123 OpBuilder::InsertionGuard guard(builder);
1124
1125 builder.createBlock(result.addRegion());
1126
1127 // Fill in the body of the ordered block.
1128 if (body)
1129 body();
1130}
1131
1132//===----------------------------------------------------------------------===//
1133// ForOp
1134//===----------------------------------------------------------------------===//
1135
1136void ForOp::build(OpBuilder &builder, OperationState &result,
1137 int64_t lowerBound, int64_t upperBound, int64_t step,
1138 IntegerType type, StringRef name,
1139 llvm::function_ref<void(BlockArgument)> body) {
1140 auto lb = hw::ConstantOp::create(builder, result.location, type, lowerBound);
1141 auto ub = hw::ConstantOp::create(builder, result.location, type, upperBound);
1142 auto st = hw::ConstantOp::create(builder, result.location, type, step);
1143 build(builder, result, lb, ub, st, name, body);
1144}
1145void ForOp::build(OpBuilder &builder, OperationState &result, Value lowerBound,
1146 Value upperBound, Value step, StringRef name,
1147 llvm::function_ref<void(BlockArgument)> body) {
1148 OpBuilder::InsertionGuard guard(builder);
1149 build(builder, result, lowerBound, upperBound, step, name);
1150 auto *region = result.regions.front().get();
1151 builder.createBlock(region);
1152 BlockArgument blockArgument =
1153 region->addArgument(lowerBound.getType(), result.location);
1154
1155 if (body)
1156 body(blockArgument);
1157}
1158
1159void ForOp::getAsmBlockArgumentNames(mlir::Region &region,
1160 mlir::OpAsmSetValueNameFn setNameFn) {
1161 auto *block = &region.front();
1162 setNameFn(block->getArgument(0), getInductionVarNameAttr());
1163}
1164
1165ParseResult ForOp::parse(OpAsmParser &parser, OperationState &result) {
1166 auto &builder = parser.getBuilder();
1167 Type type;
1168
1169 OpAsmParser::Argument inductionVariable;
1170 OpAsmParser::UnresolvedOperand lb, ub, step;
1171 // Parse the optional initial iteration arguments.
1172 SmallVector<OpAsmParser::Argument, 4> regionArgs;
1173
1174 // Parse the induction variable followed by '='.
1175 if (parser.parseOperand(inductionVariable.ssaName) || parser.parseEqual() ||
1176 // Parse loop bounds.
1177 parser.parseOperand(lb) || parser.parseKeyword("to") ||
1178 parser.parseOperand(ub) || parser.parseKeyword("step") ||
1179 parser.parseOperand(step) || parser.parseColon() ||
1180 parser.parseType(type))
1181 return failure();
1182
1183 regionArgs.push_back(inductionVariable);
1184
1185 // Resolve input operands.
1186 regionArgs.front().type = type;
1187 if (parser.resolveOperand(lb, type, result.operands) ||
1188 parser.resolveOperand(ub, type, result.operands) ||
1189 parser.resolveOperand(step, type, result.operands))
1190 return failure();
1191
1192 // Parse the body region.
1193 Region *body = result.addRegion();
1194 if (parser.parseRegion(*body, regionArgs))
1195 return failure();
1196
1197 // Parse the optional attribute list.
1198 if (parser.parseOptionalAttrDict(result.attributes))
1199 return failure();
1200
1201 if (!inductionVariable.ssaName.name.empty()) {
1202 if (!isdigit(inductionVariable.ssaName.name[1]))
1203 // Retrive from its SSA name.
1204 result.attributes.append(
1205 {builder.getStringAttr("inductionVarName"),
1206 builder.getStringAttr(inductionVariable.ssaName.name.drop_front())});
1207 }
1208
1209 return success();
1210}
1211
1212void ForOp::print(OpAsmPrinter &p) {
1213 p << " " << getInductionVar() << " = " << getLowerBound() << " to "
1214 << getUpperBound() << " step " << getStep();
1215 p << " : " << getInductionVar().getType() << ' ';
1216 p.printRegion(getRegion(),
1217 /*printEntryBlockArgs=*/false,
1218 /*printBlockTerminators=*/false);
1219 p.printOptionalAttrDict((*this)->getAttrs(), {"inductionVarName"});
1220}
1221
1222LogicalResult ForOp::canonicalize(ForOp op, PatternRewriter &rewriter) {
1223 APInt lb, ub, step;
1224 if (matchPattern(op.getLowerBound(), mlir::m_ConstantInt(&lb)) &&
1225 matchPattern(op.getUpperBound(), mlir::m_ConstantInt(&ub)) &&
1226 matchPattern(op.getStep(), mlir::m_ConstantInt(&step)) &&
1227 lb + step == ub) {
1228 // Unroll the loop if it's executed only once.
1229 rewriter.replaceAllUsesWith(op.getInductionVar(), op.getLowerBound());
1230 replaceOpWithRegion(rewriter, op, op.getBodyRegion());
1231 rewriter.eraseOp(op);
1232 return success();
1233 }
1234 return failure();
1235}
1236
1237//===----------------------------------------------------------------------===//
1238// Assignment statements
1239//===----------------------------------------------------------------------===//
1240
1241LogicalResult BPAssignOp::verify() {
1242 if (isa<sv::WireOp>(getDest().getDefiningOp()))
1243 return emitOpError(
1244 "Verilog disallows procedural assignment to a net type (did you intend "
1245 "to use a variable type, e.g., sv.reg?)");
1246 return success();
1247}
1248
1249LogicalResult PAssignOp::verify() {
1250 if (isa<sv::WireOp>(getDest().getDefiningOp()))
1251 return emitOpError(
1252 "Verilog disallows procedural assignment to a net type (did you intend "
1253 "to use a variable type, e.g., sv.reg?)");
1254 return success();
1255}
1256
1257namespace {
1258// This represents a slice of an array.
1259struct ArraySlice {
1260 Value array;
1261 Value start;
1262 size_t size; // Represent a range array[start, start + size).
1263
1264 // Get a struct from the value. Return std::nullopt if the value doesn't
1265 // represent an array slice.
1266 static std::optional<ArraySlice> getArraySlice(Value v) {
1267 auto *op = v.getDefiningOp();
1268 if (!op)
1269 return std::nullopt;
1270 return TypeSwitch<Operation *, std::optional<ArraySlice>>(op)
1271 .Case<hw::ArrayGetOp, ArrayIndexInOutOp>(
1272 [](auto arrayIndex) -> std::optional<ArraySlice> {
1273 hw::ConstantOp constant =
1274 arrayIndex.getIndex()
1275 .template getDefiningOp<hw::ConstantOp>();
1276 if (!constant)
1277 return std::nullopt;
1278 return ArraySlice{/*array=*/arrayIndex.getInput(),
1279 /*start=*/constant,
1280 /*end=*/1};
1281 })
1282 .Case<hw::ArraySliceOp>([](hw::ArraySliceOp slice)
1283 -> std::optional<ArraySlice> {
1284 auto constant = slice.getLowIndex().getDefiningOp<hw::ConstantOp>();
1285 if (!constant)
1286 return std::nullopt;
1287 return ArraySlice{
1288 /*array=*/slice.getInput(), /*start=*/constant,
1289 /*end=*/
1290 hw::type_cast<hw::ArrayType>(slice.getType()).getNumElements()};
1291 })
1292 .Case<sv::IndexedPartSelectInOutOp>(
1293 [](sv::IndexedPartSelectInOutOp index)
1294 -> std::optional<ArraySlice> {
1295 auto constant = index.getBase().getDefiningOp<hw::ConstantOp>();
1296 if (!constant || index.getDecrement())
1297 return std::nullopt;
1298 return ArraySlice{/*array=*/index.getInput(),
1299 /*start=*/constant,
1300 /*end=*/index.getWidth()};
1301 })
1302 .Default([](auto) { return std::nullopt; });
1303 }
1304
1305 // Create a pair of ArraySlice from source and destination of assignments.
1306 static std::optional<std::pair<ArraySlice, ArraySlice>>
1307 getAssignedRange(Operation *op) {
1308 assert((isa<PAssignOp, BPAssignOp>(op) && "assignments are expected"));
1309 auto srcRange = ArraySlice::getArraySlice(op->getOperand(1));
1310 if (!srcRange)
1311 return std::nullopt;
1312 auto destRange = ArraySlice::getArraySlice(op->getOperand(0));
1313 if (!destRange)
1314 return std::nullopt;
1315
1316 return std::make_pair(*destRange, *srcRange);
1317 }
1318};
1319} // namespace
1320
1321// This canonicalization merges neiboring assignments of array elements into
1322// array slice assignments. e.g.
1323// a[0] <= b[1]
1324// a[1] <= b[2]
1325// ->
1326// a[1:0] <= b[2:1]
1327template <typename AssignTy>
1328static LogicalResult mergeNeiboringAssignments(AssignTy op,
1329 PatternRewriter &rewriter) {
1330 // Get assigned ranges of each assignment.
1331 auto assignedRangeOpt = ArraySlice::getAssignedRange(op);
1332 if (!assignedRangeOpt)
1333 return failure();
1334
1335 auto [dest, src] = *assignedRangeOpt;
1336 AssignTy nextAssign = dyn_cast_or_null<AssignTy>(op->getNextNode());
1337 bool changed = false;
1338 SmallVector<Location> loc{op.getLoc()};
1339 // Check that a next operation is a same kind of the assignment.
1340 while (nextAssign) {
1341 auto nextAssignedRange = ArraySlice::getAssignedRange(nextAssign);
1342 if (!nextAssignedRange)
1343 break;
1344 auto [nextDest, nextSrc] = *nextAssignedRange;
1345 // Check that these assignments are mergaable.
1346 if (dest.array != nextDest.array || src.array != nextSrc.array ||
1347 !hw::isOffset(dest.start, nextDest.start, dest.size) ||
1348 !hw::isOffset(src.start, nextSrc.start, src.size))
1349 break;
1350
1351 dest.size += nextDest.size;
1352 src.size += nextSrc.size;
1353 changed = true;
1354 loc.push_back(nextAssign.getLoc());
1355 rewriter.eraseOp(nextAssign);
1356 nextAssign = dyn_cast_or_null<AssignTy>(op->getNextNode());
1357 }
1358
1359 if (!changed)
1360 return failure();
1361
1362 // From here, construct assignments of array slices.
1363 auto resultType = hw::ArrayType::get(
1364 hw::type_cast<hw::ArrayType>(src.array.getType()).getElementType(),
1365 src.size);
1366 auto newDest = sv::IndexedPartSelectInOutOp::create(
1367 rewriter, op.getLoc(), dest.array, dest.start, dest.size);
1368 auto newSrc = hw::ArraySliceOp::create(rewriter, op.getLoc(), resultType,
1369 src.array, src.start);
1370 auto newLoc = rewriter.getFusedLoc(loc);
1371 auto newOp = rewriter.replaceOpWithNewOp<AssignTy>(op, newDest, newSrc);
1372 newOp->setLoc(newLoc);
1373 return success();
1374}
1375
1376LogicalResult PAssignOp::canonicalize(PAssignOp op, PatternRewriter &rewriter) {
1377 return mergeNeiboringAssignments(op, rewriter);
1378}
1379
1380LogicalResult BPAssignOp::canonicalize(BPAssignOp op,
1381 PatternRewriter &rewriter) {
1382 return mergeNeiboringAssignments(op, rewriter);
1383}
1384
1385//===----------------------------------------------------------------------===//
1386// TypeDecl operations
1387//===----------------------------------------------------------------------===//
1388
1389void InterfaceOp::build(OpBuilder &builder, OperationState &result,
1390 StringRef sym_name, std::function<void()> body) {
1391 OpBuilder::InsertionGuard guard(builder);
1392
1393 result.addAttribute(::SymbolTable::getSymbolAttrName(),
1394 builder.getStringAttr(sym_name));
1395 builder.createBlock(result.addRegion());
1396 if (body)
1397 body();
1398}
1399
1400ModportType InterfaceOp::getModportType(StringRef modportName) {
1401 assert(lookupSymbol<InterfaceModportOp>(modportName) &&
1402 "Modport symbol not found.");
1403 auto *ctxt = getContext();
1404 return ModportType::get(
1405 getContext(),
1406 SymbolRefAttr::get(ctxt, getSymName(),
1407 {SymbolRefAttr::get(ctxt, modportName)}));
1408}
1409
1410Type InterfaceOp::getSignalType(StringRef signalName) {
1411 InterfaceSignalOp signal = lookupSymbol<InterfaceSignalOp>(signalName);
1412 assert(signal && "Interface signal symbol not found.");
1413 return signal.getType();
1414}
1415
1416static ParseResult parseModportStructs(OpAsmParser &parser,
1417 ArrayAttr &portsAttr) {
1418
1419 auto *context = parser.getBuilder().getContext();
1420
1421 SmallVector<Attribute, 8> ports;
1422 auto parseElement = [&]() -> ParseResult {
1423 auto direction = ModportDirectionAttr::parse(parser, {});
1424 if (!direction)
1425 return failure();
1426
1427 FlatSymbolRefAttr signal;
1428 if (parser.parseAttribute(signal))
1429 return failure();
1430
1431 ports.push_back(ModportStructAttr::get(
1432 context, cast<ModportDirectionAttr>(direction), signal));
1433 return success();
1434 };
1435 if (parser.parseCommaSeparatedList(OpAsmParser::Delimiter::Paren,
1436 parseElement))
1437 return failure();
1438
1439 portsAttr = ArrayAttr::get(context, ports);
1440 return success();
1441}
1442
1443static void printModportStructs(OpAsmPrinter &p, Operation *,
1444 ArrayAttr portsAttr) {
1445 p << "(";
1446 llvm::interleaveComma(portsAttr, p, [&](Attribute attr) {
1447 auto port = cast<ModportStructAttr>(attr);
1448 p << stringifyEnum(port.getDirection().getValue());
1449 p << ' ';
1450 p.printSymbolName(port.getSignal().getRootReference().getValue());
1451 });
1452 p << ')';
1453}
1454
1455void InterfaceSignalOp::build(mlir::OpBuilder &builder,
1456 ::mlir::OperationState &state, StringRef name,
1457 mlir::Type type) {
1458 build(builder, state, name, mlir::TypeAttr::get(type));
1459}
1460
1461void InterfaceModportOp::build(OpBuilder &builder, OperationState &state,
1462 StringRef name, ArrayRef<StringRef> inputs,
1463 ArrayRef<StringRef> outputs) {
1464 auto *ctxt = builder.getContext();
1465 SmallVector<Attribute, 8> directions;
1466 auto inputDir = ModportDirectionAttr::get(ctxt, ModportDirection::input);
1467 auto outputDir = ModportDirectionAttr::get(ctxt, ModportDirection::output);
1468 for (auto input : inputs)
1469 directions.push_back(ModportStructAttr::get(
1470 ctxt, inputDir, SymbolRefAttr::get(ctxt, input)));
1471 for (auto output : outputs)
1472 directions.push_back(ModportStructAttr::get(
1473 ctxt, outputDir, SymbolRefAttr::get(ctxt, output)));
1474 build(builder, state, name, ArrayAttr::get(ctxt, directions));
1475}
1476
1477std::optional<size_t> InterfaceInstanceOp::getTargetResultIndex() {
1478 // Inner symbols on instance operations target the op not any result.
1479 return std::nullopt;
1480}
1481
1482/// Suggest a name for each result value based on the saved result names
1483/// attribute.
1484void InterfaceInstanceOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
1485 setNameFn(getResult(), getName());
1486}
1487
1488/// Ensure that the symbol being instantiated exists and is an InterfaceOp.
1489LogicalResult InterfaceInstanceOp::verify() {
1490 if (getName().empty())
1491 return emitOpError("requires non-empty name");
1492 return success();
1493}
1494
1495LogicalResult
1496InterfaceInstanceOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1497 auto *symtable = SymbolTable::getNearestSymbolTable(*this);
1498 if (!symtable)
1499 return emitError("sv.interface.instance must exist within a region "
1500 "which has a symbol table.");
1501 auto ifaceTy = getType();
1502 auto *referencedOp =
1503 symbolTable.lookupSymbolIn(symtable, ifaceTy.getInterface());
1504 if (!referencedOp)
1505 return emitError("Symbol not found: ") << ifaceTy.getInterface() << ".";
1506 if (!isa<InterfaceOp>(referencedOp))
1507 return emitError("Symbol ")
1508 << ifaceTy.getInterface() << " is not an InterfaceOp.";
1509 return success();
1510}
1511
1512/// Ensure that the symbol being instantiated exists and is an
1513/// InterfaceModportOp.
1514LogicalResult
1515GetModportOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1516 auto *symtable = SymbolTable::getNearestSymbolTable(*this);
1517 if (!symtable)
1518 return emitError("sv.interface.instance must exist within a region "
1519 "which has a symbol table.");
1520
1521 auto ifaceTy = getType();
1522 auto *referencedOp =
1523 symbolTable.lookupSymbolIn(symtable, ifaceTy.getModport());
1524 if (!referencedOp)
1525 return emitError("Symbol not found: ") << ifaceTy.getModport() << ".";
1526 if (!isa<InterfaceModportOp>(referencedOp))
1527 return emitError("Symbol ")
1528 << ifaceTy.getModport() << " is not an InterfaceModportOp.";
1529 return success();
1530}
1531
1532void GetModportOp::build(OpBuilder &builder, OperationState &state, Value value,
1533 StringRef field) {
1534 auto ifaceTy = dyn_cast<InterfaceType>(value.getType());
1535 assert(ifaceTy && "GetModportOp expects an InterfaceType.");
1536 auto fieldAttr = SymbolRefAttr::get(builder.getContext(), field);
1537 auto modportSym =
1538 SymbolRefAttr::get(ifaceTy.getInterface().getRootReference(), fieldAttr);
1539 build(builder, state, ModportType::get(builder.getContext(), modportSym),
1540 value, fieldAttr);
1541}
1542
1543/// Lookup the op for the modport declaration. This returns null on invalid
1544/// IR.
1545InterfaceModportOp
1546GetModportOp::getReferencedDecl(const hw::HWSymbolCache &cache) {
1547 return dyn_cast_or_null<InterfaceModportOp>(
1548 cache.getDefinition(getFieldAttr()));
1549}
1550
1551void ReadInterfaceSignalOp::build(OpBuilder &builder, OperationState &state,
1552 Value iface, StringRef signalName) {
1553 auto ifaceTy = dyn_cast<InterfaceType>(iface.getType());
1554 assert(ifaceTy && "ReadInterfaceSignalOp expects an InterfaceType.");
1555 auto fieldAttr = SymbolRefAttr::get(builder.getContext(), signalName);
1556 InterfaceOp ifaceDefOp = SymbolTable::lookupNearestSymbolFrom<InterfaceOp>(
1557 iface.getDefiningOp(), ifaceTy.getInterface());
1558 assert(ifaceDefOp &&
1559 "ReadInterfaceSignalOp could not resolve an InterfaceOp.");
1560 build(builder, state, ifaceDefOp.getSignalType(signalName), iface, fieldAttr);
1561}
1562
1563/// Lookup the op for the signal declaration. This returns null on invalid
1564/// IR.
1565InterfaceSignalOp
1566ReadInterfaceSignalOp::getReferencedDecl(const hw::HWSymbolCache &cache) {
1567 return dyn_cast_or_null<InterfaceSignalOp>(
1568 cache.getDefinition(getSignalNameAttr()));
1569}
1570
1571ParseResult parseIfaceTypeAndSignal(OpAsmParser &p, Type &ifaceTy,
1572 FlatSymbolRefAttr &signalName) {
1573 SymbolRefAttr fullSym;
1574 if (p.parseAttribute(fullSym) || fullSym.getNestedReferences().size() != 1)
1575 return failure();
1576
1577 auto *ctxt = p.getBuilder().getContext();
1578 ifaceTy = InterfaceType::get(
1579 ctxt, FlatSymbolRefAttr::get(fullSym.getRootReference()));
1580 signalName = FlatSymbolRefAttr::get(fullSym.getLeafReference());
1581 return success();
1582}
1583
1584void printIfaceTypeAndSignal(OpAsmPrinter &p, Operation *op, Type type,
1585 FlatSymbolRefAttr signalName) {
1586 InterfaceType ifaceTy = dyn_cast<InterfaceType>(type);
1587 assert(ifaceTy && "Expected an InterfaceType");
1588 auto sym = SymbolRefAttr::get(ifaceTy.getInterface().getRootReference(),
1589 {signalName});
1590 p << sym;
1591}
1592
1593LogicalResult verifySignalExists(Value ifaceVal, FlatSymbolRefAttr signalName) {
1594 auto ifaceTy = dyn_cast<InterfaceType>(ifaceVal.getType());
1595 if (!ifaceTy)
1596 return failure();
1597 InterfaceOp iface = SymbolTable::lookupNearestSymbolFrom<InterfaceOp>(
1598 ifaceVal.getDefiningOp(), ifaceTy.getInterface());
1599 if (!iface)
1600 return failure();
1601 InterfaceSignalOp signal = iface.lookupSymbol<InterfaceSignalOp>(signalName);
1602 if (!signal)
1603 return failure();
1604 return success();
1605}
1606
1607Operation *
1608InterfaceInstanceOp::getReferencedInterface(const hw::HWSymbolCache *cache) {
1609 FlatSymbolRefAttr interface = getInterfaceType().getInterface();
1610 if (cache)
1611 if (auto *result = cache->getDefinition(interface))
1612 return result;
1613
1614 auto topLevelModuleOp = (*this)->getParentOfType<ModuleOp>();
1615 if (!topLevelModuleOp)
1616 return nullptr;
1617
1618 return topLevelModuleOp.lookupSymbol(interface);
1619}
1620
1621LogicalResult AssignInterfaceSignalOp::verify() {
1622 return verifySignalExists(getIface(), getSignalNameAttr());
1623}
1624
1625LogicalResult ReadInterfaceSignalOp::verify() {
1626 return verifySignalExists(getIface(), getSignalNameAttr());
1627}
1628
1629//===----------------------------------------------------------------------===//
1630// WireOp
1631//===----------------------------------------------------------------------===//
1632
1633void WireOp::build(OpBuilder &builder, OperationState &odsState,
1634 Type elementType, StringAttr name,
1635 hw::InnerSymAttr innerSym) {
1636 if (!name)
1637 name = builder.getStringAttr("");
1638 if (innerSym)
1639 odsState.addAttribute(hw::InnerSymbolTable::getInnerSymbolAttrName(),
1640 innerSym);
1641
1642 odsState.addAttribute("name", name);
1643 odsState.addTypes(InOutType::get(elementType));
1644}
1645
1646/// Suggest a name for each result value based on the saved result names
1647/// attribute.
1648void WireOp::getAsmResultNames(OpAsmSetValueNameFn setNameFn) {
1649 // If the wire has an optional 'name' attribute, use it.
1650 auto nameAttr = (*this)->getAttrOfType<StringAttr>("name");
1651 if (!nameAttr.getValue().empty())
1652 setNameFn(getResult(), nameAttr.getValue());
1653}
1654
1655std::optional<size_t> WireOp::getTargetResultIndex() { return 0; }
1656
1657// If this wire is only written to, delete the wire and all writers.
1658LogicalResult WireOp::canonicalize(WireOp wire, PatternRewriter &rewriter) {
1659 // Block if op has SV attributes.
1660 if (hasSVAttributes(wire))
1661 return failure();
1662
1663 // If the wire has a symbol, then we can't delete it.
1664 if (wire.getInnerSymAttr())
1665 return failure();
1666
1667 // Wires have inout type, so they'll have assigns and read_inout operations
1668 // that work on them. If anything unexpected is found then leave it alone.
1669 SmallVector<sv::ReadInOutOp> reads;
1670 sv::AssignOp write;
1671
1672 for (auto *user : wire->getUsers()) {
1673 if (auto read = dyn_cast<sv::ReadInOutOp>(user)) {
1674 reads.push_back(read);
1675 continue;
1676 }
1677
1678 // Otherwise must be an assign, and we must not have seen a write yet.
1679 auto assign = dyn_cast<sv::AssignOp>(user);
1680 // Either the wire has more than one write or another kind of Op (other than
1681 // AssignOp and ReadInOutOp), then can't optimize.
1682 if (!assign || write)
1683 return failure();
1684
1685 // If the assign op has SV attributes, we don't want to delete the
1686 // assignment.
1687 if (hasSVAttributes(assign))
1688 return failure();
1689
1690 write = assign;
1691 }
1692
1693 Value connected;
1694 if (!write) {
1695 // If no write and only reads, then replace with ZOp.
1696 // SV 6.6: "If no driver is connected to a net, its
1697 // value shall be high-impedance (z) unless the net is a trireg"
1698 connected = ConstantZOp::create(
1699 rewriter, wire.getLoc(),
1700 cast<InOutType>(wire.getResult().getType()).getElementType());
1701 } else if (isa<hw::HWModuleOp>(write->getParentOp()))
1702 connected = write.getSrc();
1703 else
1704 // If the write is happening at the module level then we don't have any
1705 // use-before-def checking to do, so we only handle that for now.
1706 return failure();
1707
1708 // If the wire has a name attribute, propagate the name to the expression.
1709 if (auto *connectedOp = connected.getDefiningOp())
1710 if (!wire.getName().empty())
1711 rewriter.modifyOpInPlace(connectedOp, [&] {
1712 connectedOp->setAttr("sv.namehint", wire.getNameAttr());
1713 });
1714
1715 // Ok, we can do this. Replace all the reads with the connected value.
1716 for (auto read : reads)
1717 rewriter.replaceOp(read, connected);
1718
1719 // And remove the write and wire itself.
1720 if (write)
1721 rewriter.eraseOp(write);
1722 rewriter.eraseOp(wire);
1723 return success();
1724}
1725
1726//===----------------------------------------------------------------------===//
1727// IndexedPartSelectInOutOp
1728//===----------------------------------------------------------------------===//
1729
1730// A helper function to infer a return type of IndexedPartSelectInOutOp.
1731static Type getElementTypeOfWidth(Type type, int32_t width) {
1732 auto elemTy = cast<hw::InOutType>(type).getElementType();
1733 if (isa<IntegerType>(elemTy))
1734 return hw::InOutType::get(IntegerType::get(type.getContext(), width));
1735 if (isa<hw::ArrayType>(elemTy))
1736 return hw::InOutType::get(hw::ArrayType::get(
1737 cast<hw::ArrayType>(elemTy).getElementType(), width));
1738 return {};
1739}
1740
1741LogicalResult IndexedPartSelectInOutOp::inferReturnTypes(
1742 MLIRContext *context, std::optional<Location> loc, ValueRange operands,
1743 DictionaryAttr attrs, mlir::OpaqueProperties properties,
1744 mlir::RegionRange regions, SmallVectorImpl<Type> &results) {
1745 Adaptor adaptor(operands, attrs, properties, regions);
1746 auto width = adaptor.getWidthAttr();
1747 if (!width)
1748 return failure();
1749
1750 auto typ = getElementTypeOfWidth(operands[0].getType(),
1751 width.getValue().getZExtValue());
1752 if (!typ)
1753 return failure();
1754 results.push_back(typ);
1755 return success();
1756}
1757
1758LogicalResult IndexedPartSelectInOutOp::verify() {
1759 unsigned inputWidth = 0, resultWidth = 0;
1760 auto opWidth = getWidth();
1761 auto inputElemTy = cast<InOutType>(getInput().getType()).getElementType();
1762 auto resultElemTy = cast<InOutType>(getType()).getElementType();
1763 if (auto i = dyn_cast<IntegerType>(inputElemTy))
1764 inputWidth = i.getWidth();
1765 else if (auto i = hw::type_cast<hw::ArrayType>(inputElemTy))
1766 inputWidth = i.getNumElements();
1767 else
1768 return emitError("input element type must be Integer or Array");
1769
1770 if (auto resType = dyn_cast<IntegerType>(resultElemTy))
1771 resultWidth = resType.getWidth();
1772 else if (auto resType = hw::type_cast<hw::ArrayType>(resultElemTy))
1773 resultWidth = resType.getNumElements();
1774 else
1775 return emitError("result element type must be Integer or Array");
1776
1777 if (opWidth > inputWidth)
1778 return emitError("slice width should not be greater than input width");
1779 if (opWidth != resultWidth)
1780 return emitError("result width must be equal to slice width");
1781 return success();
1782}
1783
1784OpFoldResult IndexedPartSelectInOutOp::fold(FoldAdaptor) {
1785 if (getType() == getInput().getType())
1786 return getInput();
1787 return {};
1788}
1789
1790//===----------------------------------------------------------------------===//
1791// IndexedPartSelectOp
1792//===----------------------------------------------------------------------===//
1793
1794LogicalResult IndexedPartSelectOp::inferReturnTypes(
1795 MLIRContext *context, std::optional<Location> loc, ValueRange operands,
1796 DictionaryAttr attrs, mlir::OpaqueProperties properties,
1797 mlir::RegionRange regions, SmallVectorImpl<Type> &results) {
1798 Adaptor adaptor(operands, attrs, properties, regions);
1799 auto width = adaptor.getWidthAttr();
1800 if (!width)
1801 return failure();
1802
1803 results.push_back(IntegerType::get(context, width.getInt()));
1804 return success();
1805}
1806
1807LogicalResult IndexedPartSelectOp::verify() {
1808 auto opWidth = getWidth();
1809
1810 unsigned resultWidth = cast<IntegerType>(getType()).getWidth();
1811 unsigned inputWidth = cast<IntegerType>(getInput().getType()).getWidth();
1812
1813 if (opWidth > inputWidth)
1814 return emitError("slice width should not be greater than input width");
1815 if (opWidth != resultWidth)
1816 return emitError("result width must be equal to slice width");
1817 return success();
1818}
1819
1820//===----------------------------------------------------------------------===//
1821// StructFieldInOutOp
1822//===----------------------------------------------------------------------===//
1823
1824LogicalResult StructFieldInOutOp::inferReturnTypes(
1825 MLIRContext *context, std::optional<Location> loc, ValueRange operands,
1826 DictionaryAttr attrs, mlir::OpaqueProperties properties,
1827 mlir::RegionRange regions, SmallVectorImpl<Type> &results) {
1828 Adaptor adaptor(operands, attrs, properties, regions);
1829 auto field = adaptor.getFieldAttr();
1830 if (!field)
1831 return failure();
1832 auto structType =
1833 hw::type_cast<hw::StructType>(getInOutElementType(operands[0].getType()));
1834 auto resultType = structType.getFieldType(field);
1835 if (!resultType)
1836 return failure();
1837
1838 results.push_back(hw::InOutType::get(resultType));
1839 return success();
1840}
1841
1842//===----------------------------------------------------------------------===//
1843// Other ops.
1844//===----------------------------------------------------------------------===//
1845
1846LogicalResult AliasOp::verify() {
1847 // Must have at least two operands.
1848 if (getAliases().size() < 2)
1849 return emitOpError("alias must have at least two operands");
1850
1851 return success();
1852}
1853
1854//===----------------------------------------------------------------------===//
1855// BindOp
1856//===----------------------------------------------------------------------===//
1857
1858/// Instances must be at the top level of the hw.module (or within a `ifdef)
1859// and are typically at the end of it, so we scan backwards to find them.
1860template <class Op>
1861static Op findInstanceSymbolInBlock(StringAttr name, Block *body) {
1862 for (auto &op : llvm::reverse(body->getOperations())) {
1863 if (auto instance = dyn_cast<Op>(op)) {
1864 if (auto innerSym = instance.getInnerSym())
1865 if (innerSym->getSymName() == name)
1866 return instance;
1867 }
1868
1869 if (auto ifdef = dyn_cast<IfDefOp>(op)) {
1870 if (auto result =
1871 findInstanceSymbolInBlock<Op>(name, ifdef.getThenBlock()))
1872 return result;
1873 if (ifdef.hasElse())
1874 if (auto result =
1875 findInstanceSymbolInBlock<Op>(name, ifdef.getElseBlock()))
1876 return result;
1877 }
1878 }
1879 return {};
1880}
1881
1882hw::InstanceOp BindOp::getReferencedInstance(const hw::HWSymbolCache *cache) {
1883 // If we have a cache, directly look up the referenced instance.
1884 if (cache) {
1885 auto result = cache->getInnerDefinition(getInstance());
1886 return cast<hw::InstanceOp>(result.getOp());
1887 }
1888
1889 // Otherwise, resolve the instance by looking up the module ...
1890 auto topLevelModuleOp = (*this)->getParentOfType<ModuleOp>();
1891 if (!topLevelModuleOp)
1892 return {};
1893
1894 auto hwModule = dyn_cast_or_null<hw::HWModuleOp>(
1895 topLevelModuleOp.lookupSymbol(getInstance().getModule()));
1896 if (!hwModule)
1897 return {};
1898
1899 // ... then look up the instance within it.
1900 return findInstanceSymbolInBlock<hw::InstanceOp>(getInstance().getName(),
1901 hwModule.getBodyBlock());
1902}
1903
1904/// Ensure that the symbol being instantiated exists and is an InterfaceOp.
1905LogicalResult BindOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1906 auto module = (*this)->getParentOfType<mlir::ModuleOp>();
1907 auto hwModule = dyn_cast_or_null<hw::HWModuleOp>(
1908 symbolTable.lookupSymbolIn(module, getInstance().getModule()));
1909 if (!hwModule)
1910 return emitError("Referenced module doesn't exist ")
1911 << getInstance().getModule() << "::" << getInstance().getName();
1912
1913 auto inst = findInstanceSymbolInBlock<hw::InstanceOp>(
1914 getInstance().getName(), hwModule.getBodyBlock());
1915 if (!inst)
1916 return emitError("Referenced instance doesn't exist ")
1917 << getInstance().getModule() << "::" << getInstance().getName();
1918 if (!inst.getDoNotPrint())
1919 return emitError("Referenced instance isn't marked as doNotPrint");
1920 return success();
1921}
1922
1923void BindOp::build(OpBuilder &builder, OperationState &odsState, StringAttr mod,
1924 StringAttr name) {
1925 auto ref = hw::InnerRefAttr::get(mod, name);
1926 odsState.addAttribute("instance", ref);
1927}
1928
1929//===----------------------------------------------------------------------===//
1930// BindInterfaceOp
1931//===----------------------------------------------------------------------===//
1932
1933sv::InterfaceInstanceOp
1934BindInterfaceOp::getReferencedInstance(const hw::HWSymbolCache *cache) {
1935 // If we have a cache, directly look up the referenced instance.
1936 if (cache) {
1937 auto result = cache->getInnerDefinition(getInstance());
1938 return cast<sv::InterfaceInstanceOp>(result.getOp());
1939 }
1940
1941 // Otherwise, resolve the instance by looking up the module ...
1942 auto *symbolTable = SymbolTable::getNearestSymbolTable(*this);
1943 if (!symbolTable)
1944 return {};
1945 auto *parentOp =
1946 lookupSymbolInNested(symbolTable, getInstance().getModule().getValue());
1947 if (!parentOp)
1948 return {};
1949
1950 // ... then look up the instance within it.
1951 return findInstanceSymbolInBlock<sv::InterfaceInstanceOp>(
1952 getInstance().getName(), &parentOp->getRegion(0).front());
1953}
1954
1955/// Ensure that the symbol being instantiated exists and is an InterfaceOp.
1956LogicalResult
1957BindInterfaceOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
1958 auto *parentOp =
1959 symbolTable.lookupNearestSymbolFrom(*this, getInstance().getModule());
1960 if (!parentOp)
1961 return emitError("Referenced module doesn't exist ")
1962 << getInstance().getModule() << "::" << getInstance().getName();
1963
1964 auto inst = findInstanceSymbolInBlock<sv::InterfaceInstanceOp>(
1965 getInstance().getName(), &parentOp->getRegion(0).front());
1966 if (!inst)
1967 return emitError("Referenced interface doesn't exist ")
1968 << getInstance().getModule() << "::" << getInstance().getName();
1969 if (!inst.getDoNotPrint())
1970 return emitError("Referenced interface isn't marked as doNotPrint");
1971 return success();
1972}
1973
1974//===----------------------------------------------------------------------===//
1975// XMROp
1976//===----------------------------------------------------------------------===//
1977
1978ParseResult parseXMRPath(::mlir::OpAsmParser &parser, ArrayAttr &pathAttr,
1979 StringAttr &terminalAttr) {
1980 SmallVector<Attribute> strings;
1981 ParseResult ret = parser.parseCommaSeparatedList([&]() {
1982 StringAttr result;
1983 StringRef keyword;
1984 if (succeeded(parser.parseOptionalKeyword(&keyword))) {
1985 strings.push_back(parser.getBuilder().getStringAttr(keyword));
1986 return success();
1987 }
1988 if (succeeded(parser.parseAttribute(
1989 result, parser.getBuilder().getType<NoneType>()))) {
1990 strings.push_back(result);
1991 return success();
1992 }
1993 return failure();
1994 });
1995 if (succeeded(ret)) {
1996 pathAttr = parser.getBuilder().getArrayAttr(
1997 ArrayRef<Attribute>(strings).drop_back());
1998 terminalAttr = cast<StringAttr>(*strings.rbegin());
1999 }
2000 return ret;
2001}
2002
2003void printXMRPath(OpAsmPrinter &p, XMROp op, ArrayAttr pathAttr,
2004 StringAttr terminalAttr) {
2005 llvm::interleaveComma(pathAttr, p);
2006 p << ", " << terminalAttr;
2007}
2008
2009/// Ensure that the symbol being instantiated exists and is a HierPathOp.
2010LogicalResult XMRRefOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2011 auto *table = SymbolTable::getNearestSymbolTable(*this);
2012 auto path = dyn_cast_or_null<hw::HierPathOp>(
2013 symbolTable.lookupSymbolIn(table, getRefAttr()));
2014 if (!path)
2015 return emitError("Referenced path doesn't exist ") << getRefAttr();
2016
2017 return success();
2018}
2019
2020hw::HierPathOp XMRRefOp::getReferencedPath(const hw::HWSymbolCache *cache) {
2021 if (cache)
2022 if (auto *result = cache->getDefinition(getRefAttr().getAttr()))
2023 return cast<hw::HierPathOp>(result);
2024
2025 auto topLevelModuleOp = (*this)->getParentOfType<ModuleOp>();
2026 return topLevelModuleOp.lookupSymbol<hw::HierPathOp>(getRefAttr().getValue());
2027}
2028
2029//===----------------------------------------------------------------------===//
2030// Verification Ops.
2031//===----------------------------------------------------------------------===//
2032
2033static LogicalResult eraseIfZeroOrNotZero(Operation *op, Value value,
2034 PatternRewriter &rewriter,
2035 bool eraseIfZero) {
2036 if (auto constant = value.getDefiningOp<hw::ConstantOp>())
2037 if (constant.getValue().isZero() == eraseIfZero) {
2038 rewriter.eraseOp(op);
2039 return success();
2040 }
2041
2042 return failure();
2043}
2044
2045template <class Op, bool EraseIfZero = false>
2046static LogicalResult canonicalizeImmediateVerifOp(Op op,
2047 PatternRewriter &rewriter) {
2048 return eraseIfZeroOrNotZero(op, op.getExpression(), rewriter, EraseIfZero);
2049}
2050
2051void AssertOp::getCanonicalizationPatterns(RewritePatternSet &results,
2052 MLIRContext *context) {
2053 results.add(canonicalizeImmediateVerifOp<AssertOp>);
2054}
2055
2056void AssumeOp::getCanonicalizationPatterns(RewritePatternSet &results,
2057 MLIRContext *context) {
2058 results.add(canonicalizeImmediateVerifOp<AssumeOp>);
2059}
2060
2061void CoverOp::getCanonicalizationPatterns(RewritePatternSet &results,
2062 MLIRContext *context) {
2063 results.add(canonicalizeImmediateVerifOp<CoverOp, /* EraseIfZero = */ true>);
2064}
2065
2066template <class Op, bool EraseIfZero = false>
2067static LogicalResult canonicalizeConcurrentVerifOp(Op op,
2068 PatternRewriter &rewriter) {
2069 return eraseIfZeroOrNotZero(op, op.getProperty(), rewriter, EraseIfZero);
2070}
2071
2072void AssertConcurrentOp::getCanonicalizationPatterns(RewritePatternSet &results,
2073 MLIRContext *context) {
2074 results.add(canonicalizeConcurrentVerifOp<AssertConcurrentOp>);
2075}
2076
2077void AssumeConcurrentOp::getCanonicalizationPatterns(RewritePatternSet &results,
2078 MLIRContext *context) {
2079 results.add(canonicalizeConcurrentVerifOp<AssumeConcurrentOp>);
2080}
2081
2082void CoverConcurrentOp::getCanonicalizationPatterns(RewritePatternSet &results,
2083 MLIRContext *context) {
2084 results.add(
2085 canonicalizeConcurrentVerifOp<CoverConcurrentOp, /* EraseIfZero */ true>);
2086}
2087
2088//===----------------------------------------------------------------------===//
2089// SV generate ops
2090//===----------------------------------------------------------------------===//
2091
2092/// Parse cases formatted like:
2093/// case (pattern, "name") { ... }
2094bool parseCaseRegions(OpAsmParser &p, ArrayAttr &patternsArray,
2095 ArrayAttr &caseNamesArray,
2096 SmallVectorImpl<std::unique_ptr<Region>> &caseRegions) {
2097 SmallVector<Attribute> patterns;
2098 SmallVector<Attribute> names;
2099 while (!p.parseOptionalKeyword("case")) {
2100 Attribute pattern;
2101 StringAttr name;
2102 std::unique_ptr<Region> region = std::make_unique<Region>();
2103 if (p.parseLParen() || p.parseAttribute(pattern) || p.parseComma() ||
2104 p.parseAttribute(name) || p.parseRParen() || p.parseRegion(*region))
2105 return true;
2106 patterns.push_back(pattern);
2107 names.push_back(name);
2108 if (region->empty())
2109 region->push_back(new Block());
2110 caseRegions.push_back(std::move(region));
2111 }
2112 patternsArray = p.getBuilder().getArrayAttr(patterns);
2113 caseNamesArray = p.getBuilder().getArrayAttr(names);
2114 return false;
2115}
2116
2117/// Print cases formatted like:
2118/// case (pattern, "name") { ... }
2119void printCaseRegions(OpAsmPrinter &p, Operation *, ArrayAttr patternsArray,
2120 ArrayAttr namesArray,
2121 MutableArrayRef<Region> caseRegions) {
2122 assert(patternsArray.size() == caseRegions.size());
2123 assert(patternsArray.size() == namesArray.size());
2124 for (size_t i = 0, e = caseRegions.size(); i < e; ++i) {
2125 p.printNewline();
2126 p << "case (" << patternsArray[i] << ", " << namesArray[i] << ") ";
2127 p.printRegion(caseRegions[i]);
2128 }
2129 p.printNewline();
2130}
2131
2132LogicalResult GenerateCaseOp::verify() {
2133 size_t numPatterns = getCasePatterns().size();
2134 if (getCaseRegions().size() != numPatterns ||
2135 getCaseNames().size() != numPatterns)
2136 return emitOpError(
2137 "Size of caseRegions, patterns, and caseNames must match");
2138
2139 StringSet<> usedNames;
2140 for (Attribute name : getCaseNames()) {
2141 StringAttr nameStr = dyn_cast<StringAttr>(name);
2142 if (!nameStr)
2143 return emitOpError("caseNames must all be string attributes");
2144 if (usedNames.contains(nameStr.getValue()))
2145 return emitOpError("caseNames must be unique");
2146 usedNames.insert(nameStr.getValue());
2147 }
2148
2149 // mlir::FailureOr<Type> condType = evaluateParametricType();
2150
2151 return success();
2152}
2153
2154ModportStructAttr ModportStructAttr::get(MLIRContext *context,
2155 ModportDirection direction,
2156 FlatSymbolRefAttr signal) {
2157 return get(context, ModportDirectionAttr::get(context, direction), signal);
2158}
2159
2160//===----------------------------------------------------------------------===//
2161// FuncOp
2162//===----------------------------------------------------------------------===//
2163
2164ParseResult FuncOp::parse(OpAsmParser &parser, OperationState &result) {
2165 auto builder = parser.getBuilder();
2166 // Parse visibility.
2167 (void)mlir::impl::parseOptionalVisibilityKeyword(parser, result.attributes);
2168
2169 // Parse the name as a symbol.
2170 StringAttr nameAttr;
2171 if (parser.parseSymbolName(nameAttr, SymbolTable::getSymbolAttrName(),
2172 result.attributes))
2173 return failure();
2174
2175 SmallVector<hw::module_like_impl::PortParse> ports;
2176 TypeAttr modType;
2177 if (failed(
2178 hw::module_like_impl::parseModuleSignature(parser, ports, modType)))
2179 return failure();
2180
2181 result.addAttribute(FuncOp::getModuleTypeAttrName(result.name), modType);
2182
2183 // Convert the specified array of dictionary attrs (which may have null
2184 // entries) to an ArrayAttr of dictionaries.
2185 auto unknownLoc = builder.getUnknownLoc();
2186 SmallVector<Attribute> attrs, inputLocs, outputLocs;
2187 auto nonEmptyLocsFn = [unknownLoc](Attribute attr) {
2188 return attr && cast<Location>(attr) != unknownLoc;
2189 };
2190
2191 for (auto &port : ports) {
2192 attrs.push_back(port.attrs ? port.attrs : builder.getDictionaryAttr({}));
2193 auto loc = port.sourceLoc ? Location(*port.sourceLoc) : unknownLoc;
2194 (port.direction == hw::PortInfo::Direction::Output ? outputLocs : inputLocs)
2195 .push_back(loc);
2196 }
2197
2198 result.addAttribute(FuncOp::getPerArgumentAttrsAttrName(result.name),
2199 builder.getArrayAttr(attrs));
2200
2201 if (llvm::any_of(outputLocs, nonEmptyLocsFn))
2202 result.addAttribute(FuncOp::getResultLocsAttrName(result.name),
2203 builder.getArrayAttr(outputLocs));
2204 // Parse the attribute dict.
2205 if (failed(parser.parseOptionalAttrDictWithKeyword(result.attributes)))
2206 return failure();
2207
2208 // Add the entry block arguments.
2209 SmallVector<OpAsmParser::Argument, 4> entryArgs;
2210 for (auto &port : ports)
2211 if (port.direction != hw::ModulePort::Direction::Output)
2212 entryArgs.push_back(port);
2213
2214 // Parse the optional function body. The printer will not print the body if
2215 // its empty, so disallow parsing of empty body in the parser.
2216 auto *body = result.addRegion();
2217 llvm::SMLoc loc = parser.getCurrentLocation();
2218
2219 mlir::OptionalParseResult parseResult =
2220 parser.parseOptionalRegion(*body, entryArgs,
2221 /*enableNameShadowing=*/false);
2222 if (parseResult.has_value()) {
2223 if (failed(*parseResult))
2224 return failure();
2225 // Function body was parsed, make sure its not empty.
2226 if (body->empty())
2227 return parser.emitError(loc, "expected non-empty function body");
2228 } else {
2229 if (llvm::any_of(inputLocs, nonEmptyLocsFn))
2230 result.addAttribute(FuncOp::getInputLocsAttrName(result.name),
2231 builder.getArrayAttr(inputLocs));
2232 }
2233
2234 return success();
2235}
2236
2237void FuncOp::getAsmBlockArgumentNames(mlir::Region &region,
2238 mlir::OpAsmSetValueNameFn setNameFn) {
2239 if (region.empty())
2240 return;
2241 // Assign port names to the bbargs.
2242 auto func = cast<FuncOp>(region.getParentOp());
2243
2244 auto *block = &region.front();
2245
2246 auto names = func.getModuleType().getInputNames();
2247 for (size_t i = 0, e = block->getNumArguments(); i != e; ++i) {
2248 // Let mlir deterministically convert names to valid identifiers
2249 setNameFn(block->getArgument(i), cast<StringAttr>(names[i]));
2250 }
2251}
2252
2253Type FuncOp::getExplicitlyReturnedType() {
2254 if (!getPerArgumentAttrs() || getNumOutputs() == 0)
2255 return {};
2256
2257 // Check if the last port is used as an explicit return.
2258 auto lastArgument = getModuleType().getPorts().back();
2259 auto lastArgumentAttr = dyn_cast<DictionaryAttr>(
2260 getPerArgumentAttrsAttr()[getPerArgumentAttrsAttr().size() - 1]);
2261
2262 if (lastArgument.dir == hw::ModulePort::Output && lastArgumentAttr &&
2263 lastArgumentAttr.getAs<UnitAttr>(getExplicitlyReturnedAttrName()))
2264 return lastArgument.type;
2265 return {};
2266}
2267
2268ArrayRef<Attribute> FuncOp::getAllPortAttrs() {
2269 if (getPerArgumentAttrs())
2270 return getPerArgumentAttrs()->getValue();
2271 return {};
2272}
2273
2274void FuncOp::setAllPortAttrs(ArrayRef<Attribute> attrs) {
2275 setPerArgumentAttrsAttr(ArrayAttr::get(getContext(), attrs));
2276}
2277
2278void FuncOp::removeAllPortAttrs() { setPerArgumentAttrsAttr({}); }
2279SmallVector<Location> FuncOp::getAllPortLocs() {
2280 SmallVector<Location> portLocs;
2281 portLocs.reserve(getNumPorts());
2282 auto resultLocs = getResultLocsAttr();
2283 unsigned inputCount = 0;
2284 auto modType = getModuleType();
2285 auto unknownLoc = UnknownLoc::get(getContext());
2286 auto *body = getBodyBlock();
2287 auto inputLocs = getInputLocsAttr();
2288 for (unsigned i = 0, e = getNumPorts(); i < e; ++i) {
2289 if (modType.isOutput(i)) {
2290 auto loc = resultLocs
2291 ? cast<Location>(
2292 resultLocs.getValue()[portLocs.size() - inputCount])
2293 : unknownLoc;
2294 portLocs.push_back(loc);
2295 } else {
2296 auto loc = body ? body->getArgument(inputCount).getLoc()
2297 : (inputLocs ? cast<Location>(inputLocs[inputCount])
2298 : unknownLoc);
2299 portLocs.push_back(loc);
2300 ++inputCount;
2301 }
2302 }
2303 return portLocs;
2304}
2305
2306void FuncOp::setAllPortLocsAttrs(llvm::ArrayRef<mlir::Attribute> locs) {
2307 SmallVector<Attribute> resultLocs, inputLocs;
2308 unsigned inputCount = 0;
2309 auto modType = getModuleType();
2310 auto *body = getBodyBlock();
2311 for (unsigned i = 0, e = getNumPorts(); i < e; ++i) {
2312 if (modType.isOutput(i))
2313 resultLocs.push_back(locs[i]);
2314 else if (body)
2315 body->getArgument(inputCount++).setLoc(cast<Location>(locs[i]));
2316 else // Need to store locations in an attribute if declaration.
2317 inputLocs.push_back(locs[i]);
2318 }
2319 setResultLocsAttr(ArrayAttr::get(getContext(), resultLocs));
2320 if (!body)
2321 setInputLocsAttr(ArrayAttr::get(getContext(), inputLocs));
2322}
2323
2324SmallVector<hw::PortInfo> FuncOp::getPortList() { return getPortList(false); }
2325
2326hw::PortInfo FuncOp::getPort(size_t idx) {
2327 auto modTy = getHWModuleType();
2328 auto emptyDict = DictionaryAttr::get(getContext());
2329 LocationAttr loc = getPortLoc(idx);
2330 DictionaryAttr attrs = dyn_cast_or_null<DictionaryAttr>(getPortAttrs(idx));
2331 if (!attrs)
2332 attrs = emptyDict;
2333 return {modTy.getPorts()[idx],
2334 modTy.isOutput(idx) ? modTy.getOutputIdForPortId(idx)
2335 : modTy.getInputIdForPortId(idx),
2336 attrs, loc};
2337}
2338
2339SmallVector<hw::PortInfo> FuncOp::getPortList(bool excludeExplicitReturn) {
2340 auto modTy = getModuleType();
2341 auto emptyDict = DictionaryAttr::get(getContext());
2342 auto skipLastArgument = getExplicitlyReturnedType() && excludeExplicitReturn;
2343 SmallVector<hw::PortInfo> retval;
2344 auto portAttr = getAllPortLocs();
2345 for (unsigned i = 0, e = skipLastArgument ? modTy.getNumPorts() - 1
2346 : modTy.getNumPorts();
2347 i < e; ++i) {
2348 DictionaryAttr attrs = emptyDict;
2349 if (auto perArgumentAttr = getPerArgumentAttrs())
2350 if (auto argumentAttr =
2351 dyn_cast_or_null<DictionaryAttr>((*perArgumentAttr)[i]))
2352 attrs = argumentAttr;
2353
2354 retval.push_back({modTy.getPorts()[i],
2355 modTy.isOutput(i) ? modTy.getOutputIdForPortId(i)
2356 : modTy.getInputIdForPortId(i),
2357 attrs, portAttr[i]});
2358 }
2359 return retval;
2360}
2361
2362void FuncOp::print(OpAsmPrinter &p) {
2363 FuncOp op = *this;
2364 // Print the operation and the function name.
2365 auto funcName =
2366 op->getAttrOfType<StringAttr>(SymbolTable::getSymbolAttrName())
2367 .getValue();
2368 p << ' ';
2369
2370 StringRef visibilityAttrName = SymbolTable::getVisibilityAttrName();
2371 if (auto visibility = op->getAttrOfType<StringAttr>(visibilityAttrName))
2372 p << visibility.getValue() << ' ';
2373 p.printSymbolName(funcName);
2375 p, op.getBody(), op.getModuleType(),
2376 op.getPerArgumentAttrsAttr()
2377 ? ArrayRef<Attribute>(op.getPerArgumentAttrsAttr().getValue())
2378 : ArrayRef<Attribute>{},
2379 getAllPortLocs());
2380
2381 mlir::function_interface_impl::printFunctionAttributes(
2382 p, op,
2383 {visibilityAttrName, getModuleTypeAttrName(),
2384 getPerArgumentAttrsAttrName(), getInputLocsAttrName(),
2385 getResultLocsAttrName()});
2386 // Print the body if this is not an external function.
2387 Region &body = op->getRegion(0);
2388 if (!body.empty()) {
2389 p << ' ';
2390 p.printRegion(body, /*printEntryBlockArgs=*/false,
2391 /*printBlockTerminators=*/true);
2392 }
2393}
2394
2395//===----------------------------------------------------------------------===//
2396// ReturnOp
2397//===----------------------------------------------------------------------===//
2398
2399LogicalResult ReturnOp::verify() {
2400 auto func = getParentOp<sv::FuncOp>();
2401 auto funcResults = func.getResultTypes();
2402 auto returnedValues = getOperands();
2403 if (funcResults.size() != returnedValues.size())
2404 return emitOpError("must have same number of operands as region results.");
2405 // Check that the types of our operands and the region's results match.
2406 for (size_t i = 0, e = funcResults.size(); i < e; ++i) {
2407 if (funcResults[i] != returnedValues[i].getType()) {
2408 emitOpError("output types must match function. In "
2409 "operand ")
2410 << i << ", expected " << funcResults[i] << ", but got "
2411 << returnedValues[i].getType() << ".";
2412 return failure();
2413 }
2414 }
2415 return success();
2416}
2417
2418//===----------------------------------------------------------------------===//
2419// Call Ops
2420//===----------------------------------------------------------------------===//
2421
2422static Value
2424 mlir::Operation::result_range results) {
2425 if (!op.getExplicitlyReturnedType())
2426 return {};
2427 return results.back();
2428}
2429
2430Value FuncCallOp::getExplicitlyReturnedValue(sv::FuncOp op) {
2431 return getExplicitlyReturnedValueImpl(op, getResults());
2432}
2433
2434Value FuncCallProceduralOp::getExplicitlyReturnedValue(sv::FuncOp op) {
2435 return getExplicitlyReturnedValueImpl(op, getResults());
2436}
2437
2438LogicalResult
2439FuncCallProceduralOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2440 auto referencedOp = dyn_cast_or_null<sv::FuncOp>(
2441 symbolTable.lookupNearestSymbolFrom(*this, getCalleeAttr()));
2442 if (!referencedOp)
2443 return emitError("cannot find function declaration '")
2444 << getCallee() << "'";
2445 return success();
2446}
2447
2448LogicalResult FuncCallOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2449 auto referencedOp = dyn_cast_or_null<sv::FuncOp>(
2450 symbolTable.lookupNearestSymbolFrom(*this, getCalleeAttr()));
2451 if (!referencedOp)
2452 return emitError("cannot find function declaration '")
2453 << getCallee() << "'";
2454
2455 // Non-procedural call cannot have output arguments.
2456 if (referencedOp.getNumOutputs() != 1 ||
2457 !referencedOp.getExplicitlyReturnedType()) {
2458 auto diag = emitError()
2459 << "function called in a non-procedural region must "
2460 "return a single result";
2461 diag.attachNote(referencedOp.getLoc()) << "doesn't satisfy the constraint";
2462 return failure();
2463 }
2464 return success();
2465}
2466
2467//===----------------------------------------------------------------------===//
2468// FuncDPIImportOp
2469//===----------------------------------------------------------------------===//
2470
2471LogicalResult
2472FuncDPIImportOp::verifySymbolUses(SymbolTableCollection &symbolTable) {
2473 auto referencedOp = dyn_cast_or_null<sv::FuncOp>(
2474 symbolTable.lookupNearestSymbolFrom(*this, getCalleeAttr()));
2475
2476 if (!referencedOp)
2477 return emitError("cannot find function declaration '")
2478 << getCallee() << "'";
2479 if (!referencedOp.isDeclaration())
2480 return emitError("imported function must be a declaration but '")
2481 << getCallee() << "' is defined";
2482 return success();
2483}
2484
2485//===----------------------------------------------------------------------===//
2486// Assert Property Like ops
2487//===----------------------------------------------------------------------===//
2488
2490// Check that a clock is never given without an event
2491// and that an event is never given with a clock.
2492static LogicalResult verify(Value clock, bool eventExists, mlir::Location loc) {
2493 if ((!clock && eventExists) || (clock && !eventExists))
2494 return mlir::emitError(
2495 loc, "Every clock must be associated to an even and vice-versa!");
2496 return success();
2497}
2498} // namespace AssertPropertyLikeOp
2499
2500LogicalResult AssertPropertyOp::verify() {
2501 return AssertPropertyLikeOp::verify(getClock(), getEvent().has_value(),
2502 getLoc());
2503}
2504
2505LogicalResult AssumePropertyOp::verify() {
2506 return AssertPropertyLikeOp::verify(getClock(), getEvent().has_value(),
2507 getLoc());
2508}
2509
2510LogicalResult CoverPropertyOp::verify() {
2511 return AssertPropertyLikeOp::verify(getClock(), getEvent().has_value(),
2512 getLoc());
2513}
2514
2515//===----------------------------------------------------------------------===//
2516// TableGen generated logic.
2517//===----------------------------------------------------------------------===//
2518
2519// Provide the autogenerated implementation guts for the Op classes.
2520#define GET_OP_CLASSES
2521#include "circt/Dialect/SV/SV.cpp.inc"
assert(baseType &&"element must be base type")
MlirType elementType
Definition CHIRRTL.cpp:29
static bool hasSVAttributes(Operation *op)
Definition CombFolds.cpp:66
#define isdigit(x)
Definition FIRLexer.cpp:26
static LogicalResult canonicalizeImmediateVerifOp(Op op, PatternRewriter &rewriter)
static void replaceOpWithRegion(PatternRewriter &rewriter, Operation *op, Region &region)
Replaces the given op with the contents of the given single-block region.
static LogicalResult eraseIfZeroOrNotZero(Operation *op, Value predicate, Value enable, PatternRewriter &rewriter, bool eraseIfZero)
static SmallVector< PortInfo > getPortList(ModuleTy &mod)
Definition HWOps.cpp:1428
static SmallVector< Location > getAllPortLocs(ModTy module)
Definition HWOps.cpp:1206
@ Output
Definition HW.h:35
static Location getLoc(DefSlot slot)
Definition Mem2Reg.cpp:216
static std::optional< APInt > getInt(Value value)
Helper to convert a value to a constant integer if it is one.
static Block * getBodyBlock(FModuleLike mod)
RewritePatternSet pattern
bool parseCaseRegions(OpAsmParser &p, ArrayAttr &patternsArray, ArrayAttr &caseNamesArray, SmallVectorImpl< std::unique_ptr< Region > > &caseRegions)
Parse cases formatted like: case (pattern, "name") { ... }.
Definition SVOps.cpp:2094
ParseResult parseIfaceTypeAndSignal(OpAsmParser &p, Type &ifaceTy, FlatSymbolRefAttr &signalName)
Definition SVOps.cpp:1571
LogicalResult verifySignalExists(Value ifaceVal, FlatSymbolRefAttr signalName)
Definition SVOps.cpp:1593
void printCaseRegions(OpAsmPrinter &p, Operation *, ArrayAttr patternsArray, ArrayAttr namesArray, MutableArrayRef< Region > caseRegions)
Print cases formatted like: case (pattern, "name") { ... }.
Definition SVOps.cpp:2119
static Value getExplicitlyReturnedValueImpl(sv::FuncOp op, mlir::Operation::result_range results)
Definition SVOps.cpp:2423
void printIfaceTypeAndSignal(OpAsmPrinter &p, Operation *op, Type type, FlatSymbolRefAttr signalName)
Definition SVOps.cpp:1584
static void printModportStructs(OpAsmPrinter &p, Operation *, ArrayAttr portsAttr)
Definition SVOps.cpp:1443
static LogicalResult canonicalizeConcurrentVerifOp(Op op, PatternRewriter &rewriter)
Definition SVOps.cpp:2067
static ParseResult parseEventList(OpAsmParser &p, Attribute &eventsAttr, SmallVectorImpl< OpAsmParser::UnresolvedOperand > &clocksOperands)
Definition SVOps.cpp:638
static MacroDeclOp getReferencedMacro(const hw::HWSymbolCache *cache, Operation *op, FlatSymbolRefAttr macroName)
Definition SVOps.cpp:153
static LogicalResult canonicalizeIfDefLike(Op op, PatternRewriter &rewriter)
Definition SVOps.cpp:442
ParseResult parseXMRPath(::mlir::OpAsmParser &parser, ArrayAttr &pathAttr, StringAttr &terminalAttr)
Definition SVOps.cpp:1978
static Type getElementTypeOfWidth(Type type, int32_t width)
Definition SVOps.cpp:1731
static LogicalResult mergeNeiboringAssignments(AssignTy op, PatternRewriter &rewriter)
Definition SVOps.cpp:1328
static Op findInstanceSymbolInBlock(StringAttr name, Block *body)
Instances must be at the top level of the hw.module (or within a `ifdef)
Definition SVOps.cpp:1861
static void printEventList(OpAsmPrinter &p, AlwaysOp op, ArrayAttr portsAttr, OperandRange operands)
Definition SVOps.cpp:669
static SmallVector< CasePatternBit > getPatternBitsForValue(const APInt &value)
Definition SVOps.cpp:803
static ParseResult parseImplicitInitType(OpAsmParser &p, mlir::Type regType, std::optional< OpAsmParser::UnresolvedOperand > &initValue, mlir::Type &initType)
Definition SVOps.cpp:294
static LogicalResult verifyMacroIdentSymbolUses(Operation *op, FlatSymbolRefAttr attr, SymbolTableCollection &symbolTable)
Verifies symbols referenced by macro identifiers.
Definition SVOps.cpp:98
static void getVerbatimExprAsmResultNames(Operation *op, function_ref< void(Value, StringRef)> setNameFn)
Get the asm name for sv.verbatim.expr and sv.verbatim.expr.se.
Definition SVOps.cpp:114
static void printImplicitInitType(OpAsmPrinter &p, Operation *op, mlir::Type regType, mlir::Value initValue, mlir::Type initType)
Definition SVOps.cpp:308
static ParseResult parseModportStructs(OpAsmParser &parser, ArrayAttr &portsAttr)
Definition SVOps.cpp:1416
static Operation * lookupSymbolInNested(Operation *symbolTableOp, StringRef symbol)
Returns the operation registered with the given symbol name with the regions of 'symbolTableOp'.
Definition SVOps.cpp:73
void printXMRPath(OpAsmPrinter &p, XMROp op, ArrayAttr pathAttr, StringAttr terminalAttr)
Definition SVOps.cpp:2003
static InstancePath empty
This stores lookup tables to make manipulating and working with the IR more efficient.
Definition HWSymCache.h:27
HWSymbolCache::Item getInnerDefinition(mlir::StringAttr modSymbol, mlir::StringAttr name) const
Definition HWSymCache.h:65
mlir::Operation * getDefinition(mlir::Attribute attr) const override
Lookup a definition for 'symbol' in the cache.
Definition HWSymCache.h:56
static StringRef getInnerSymbolAttrName()
Return the name of the attribute used for inner symbol names.
IntegerAttr intAttr
Definition SVOps.h:122
CasePatternBit getBit(size_t bitNumber) const
Return the specified bit, bit 0 is the least significant bit.
Definition SVOps.cpp:785
bool hasZ() const override
Return true if this pattern has an Z.
Definition SVOps.cpp:797
CaseBitPattern(ArrayRef< CasePatternBit > bits, MLIRContext *context)
Get a CasePattern from a specified list of CasePatternBit.
Definition SVOps.cpp:821
bool hasX() const override
Return true if this pattern has an X.
Definition SVOps.cpp:790
hw::EnumFieldAttr enumAttr
Definition SVOps.h:139
StringRef getFieldValue() const
Definition SVOps.cpp:860
Signals that an operations regions are procedural.
Definition SVOps.h:160
create(array_value, low_index, ret_type)
Definition hw.py:466
create(data_type, value)
Definition hw.py:433
Definition sv.py:68
static LogicalResult verify(Value clock, bool eventExists, mlir::Location loc)
Definition SVOps.cpp:2492
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
Definition CalyxOps.cpp:55
Direction
The direction of a Component or Cell port.
Definition CalyxOps.h:76
Value createOrFoldNot(Location loc, Value value, OpBuilder &builder, bool twoState=false)
Create a `‘Not’' gate on a value.
Definition CombOps.cpp:65
uint64_t getWidth(Type t)
Definition ESIPasses.cpp:32
size_t getNumPorts(Operation *op)
Return the number of ports in a module-like thing (modules, memories, etc)
StringAttr getName(ArrayAttr names, size_t idx)
Return the name at the specified index of the ArrayAttr or null if it cannot be determined.
ParseResult parseModuleSignature(OpAsmParser &parser, SmallVectorImpl< PortParse > &args, TypeAttr &modType)
New Style parsing.
void printModuleSignatureNew(OpAsmPrinter &p, Region &body, hw::ModuleType modType, ArrayRef< Attribute > portAttrs, ArrayRef< Location > locAttrs)
bool isHWIntegerType(mlir::Type type)
Return true if the specified type is a value HW Integer type.
Definition HWTypes.cpp:60
bool isOffset(Value base, Value index, uint64_t offset)
Definition HWOps.cpp:1842
FunctionType getModuleType(Operation *module)
Return the signature for the specified module as a function type.
Definition HWOps.cpp:529
bool isHWEnumType(mlir::Type type)
Return true if the specified type is a HW Enum type.
Definition HWTypes.cpp:73
mlir::Type getCanonicalType(mlir::Type type)
Definition HWTypes.cpp:49
CasePatternBit
This describes the bit in a pattern, 0/1/x/z.
Definition SVOps.h:48
char getLetter(CasePatternBit bit)
Return the letter for the specified pattern bit, e.g. "0", "1", "x" or "z".
Definition SVOps.cpp:770
bool hasSVAttributes(mlir::Operation *op)
Helper functions to handle SV attributes.
bool is2StateExpression(Value v)
Returns if the expression is known to be 2-state (binary)
Definition SVOps.cpp:40
mlir::Type getInOutElementType(mlir::Type type)
Return the element type of an InOutType or null if the operand isn't an InOut type.
Definition SVTypes.cpp:42
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.
Definition hw.py:1
function_ref< void(Value, StringRef)> OpAsmSetValueNameFn
Definition LLVM.h:183
Definition sv.py:1
This holds the name, type, direction of a module's ports.