19#include "mlir/IR/ImplicitLocOpBuilder.h"
20#include "llvm/ADT/SmallString.h"
21#include "llvm/ADT/TypeSwitch.h"
24using namespace firrtl;
31 Value &cached =
cache[type];
33 cached =
builder.create<UnknownValueOp>(type);
43 ImplicitLocOpBuilder locBuilder(loc, builder.getInsertionBlock(),
44 builder.getInsertionPoint());
46 builder.restoreInsertionPoint(locBuilder.saveInsertionPoint());
49template <
typename ATy,
typename IndexOp,
bool isBundle >
53 auto dstAggTy = type_dyn_cast<ATy>(dstFType);
56 auto srcAggTy = type_dyn_cast<ATy>(srcFType);
65 ConnectOp::create(builder, dst, src);
70 auto dstField = IndexOp::create(builder, dst, i);
71 auto srcField = IndexOp::create(builder, src, i);
72 if constexpr (isBundle) {
73 if (dstAggTy.getElement(i).isFlip)
74 std::swap(dstField, srcField);
85 auto dstFType = type_cast<FIRRTLType>(dst.getType());
86 auto srcFType = type_cast<FIRRTLType>(src.getType());
87 auto dstType = type_dyn_cast<FIRRTLBaseType>(dstFType);
88 auto srcType = type_dyn_cast<FIRRTLBaseType>(srcFType);
92 if (type_isa<RefType>(dstFType)) {
93 if (dstFType != srcFType)
94 src = RefCastOp::create(builder, dstFType, src);
95 RefDefineOp::create(builder, dst, src);
96 }
else if (type_isa<PropertyType>(dstFType) &&
97 type_isa<PropertyType>(srcFType)) {
99 PropAssignOp::create(builder, dst, src);
100 }
else if (type_isa<DomainType>(dstFType) &&
101 type_isa<DomainType>(srcFType)) {
102 DomainDefineOp::create(builder, dst, src);
103 }
else if (failed(connectIfAggregates<OpenBundleType, OpenSubfieldOp, true>(
104 builder, dst, dstFType, src, srcFType)) &&
106 connectIfAggregates<OpenVectorType, OpenSubindexOp, false>(
107 builder, dst, dstFType, src, srcFType))) {
109 ConnectOp::create(builder, dst, src);
115 if (isa<AnalogType>(dstType)) {
116 AttachOp::create(builder, ArrayRef{dst, src});
121 if (dstType == srcType && dstType.isPassive() &&
122 !dstType.hasUninferredWidth() && !dstType.containsAnalog()) {
123 MatchingConnectOp::create(builder, dst, src);
127 if (succeeded(connectIfAggregates<BundleType, SubfieldOp, true>(
128 builder, dst, dstFType, src, srcFType)) ||
129 succeeded(connectIfAggregates<FVectorType, SubindexOp, false>(
130 builder, dst, dstFType, src, srcFType)))
133 if ((dstType.hasUninferredReset() || srcType.hasUninferredReset()) &&
134 dstType != srcType) {
135 srcType = dstType.getConstType(srcType.isConst());
136 src = UninferredResetCastOp::create(builder, srcType, src);
140 auto dstWidth = dstType.getBitWidthOrSentinel();
141 auto srcWidth = srcType.getBitWidthOrSentinel();
142 if (dstWidth < 0 || srcWidth < 0) {
149 if (dstType != srcType && dstType.getWidthlessType() != srcType &&
151 src = ConstCastOp::create(builder, dstType.getWidthlessType(), src);
154 ConnectOp::create(builder, dst, src);
159 if (dstWidth < srcWidth) {
160 mlir::emitWarning(builder.getLoc())
161 <<
"RHS width " << srcWidth <<
" exceeds LHS width " << dstWidth
162 <<
", inserting implicit truncation";
166 type_cast<IntType>(dstType).
getConstType(srcType.isConst());
167 bool isSignedDest = tmpType.
isSigned();
170 UIntType::get(dstType.getContext(), dstWidth, srcType.isConst());
171 src = TailPrimOp::create(builder, tmpType, src, srcWidth - dstWidth);
174 src = AsSIntPrimOp::create(builder,
175 dstType.getConstType(tmpType.
isConst()), src);
176 }
else if (srcWidth < dstWidth) {
178 src = PadPrimOp::create(builder, src, dstWidth);
181 if (
auto srcType = type_cast<FIRRTLBaseType>(src.getType());
182 srcType && dstType != srcType &&
184 src = ConstCastOp::create(builder, dstType, src);
189 if (dstType == src.getType() && dstType.isPassive() &&
190 !dstType.hasUninferredWidth()) {
191 MatchingConnectOp::create(builder, dst, src);
193 ConnectOp::create(builder, dst, src);
197 auto intType = type_cast<IntType>(type);
198 assert((!intType.hasWidth() ||
199 (
unsigned)intType.getWidthOrSentinel() == value.getBitWidth()) &&
200 "value / type width mismatch");
202 intType.isSigned() ? IntegerType::Signed : IntegerType::Unsigned;
204 IntegerType::get(type.getContext(), value.getBitWidth(), intSign);
205 return IntegerAttr::get(attrType, value);
211 int32_t width = abs(type_cast<IntType>(type).getWidthOrSentinel());
218 int32_t width = abs(type_cast<IntType>(type).getWidthOrSentinel());
220 type, APInt(width, -1,
false,
true));
226 for (
auto *user : value.getUsers())
227 if (
auto propassign = dyn_cast<PropAssignOp>(user))
228 if (propassign.getDest() == value)
243 for (
auto *user : val.getUsers()) {
244 if (
auto connect = dyn_cast<FConnectLike>(user)) {
245 if (connect.getDest() != val)
247 return connect.getSrc();
254 bool lookThroughNodes,
255 bool lookThroughCasts) {
260 auto updateVal = [&](Value thisVal) {
261 for (
auto *user : thisVal.getUsers()) {
262 if (
auto connect = dyn_cast<FConnectLike>(user)) {
263 if (connect.getDest() != val)
265 val = connect.getSrc();
275 if (
auto blockArg = dyn_cast<BlockArgument>(val)) {
276 FModuleOp op = cast<FModuleOp>(val.getParentBlock()->getParentOp());
277 auto direction = op.getPortDirection(blockArg.getArgNumber());
285 auto *op = val.getDefiningOp();
288 if (
auto inst = dyn_cast<InstanceOp>(op)) {
289 auto resultNo = cast<OpResult>(val).getResultNumber();
292 return inst.getResult(resultNo);
299 updateVal(op->getResult(0));
304 if (lookThroughNodes && isa<NodeOp>(op)) {
305 val = cast<NodeOp>(op).getInput();
309 if (lookThroughCasts &&
310 isa<AsUIntPrimOp, AsSIntPrimOp, AsClockPrimOp, AsAsyncResetPrimOp>(
312 val = op->getOperand(0);
317 if (isa<PadPrimOp, TailPrimOp>(op)) {
318 val = op->getOperand(0);
333 bool lookThroughNodes,
bool lookThroughCasts,
337 assert(value.getType().isPassive() &&
"this code was not tested with flips");
348 struct StackElement {
350 : dst(dst), src(src), current(current), it(current.user_begin()),
363 Value::user_iterator it;
367 SmallVector<StackElement> workStack;
373 auto value = src.getValue();
374 workStack.emplace_back(dst, src, value, src.
getFieldID());
380 auto fieldRef = original;
388 auto val = fieldRef.getValue();
391 if (
auto blockArg = dyn_cast<BlockArgument>(val)) {
392 auto *parent = val.getParentBlock()->getParentOp();
393 auto module = cast<FModuleLike>(parent);
394 auto direction =
module.getPortDirection(blockArg.getArgNumber());
397 if (!callback(original, fieldRef))
401 addToWorklist(original, fieldRef);
405 auto *op = val.getDefiningOp();
408 if (
auto inst = dyn_cast<InstanceOp>(op)) {
409 auto resultNo = cast<OpResult>(val).getResultNumber();
412 if (!callback(original, fieldRef))
416 addToWorklist(original, fieldRef);
422 addToWorklist(original, fieldRef);
427 if (lookThroughNodes && isa<NodeOp>(op)) {
428 auto input = cast<NodeOp>(op).getInput();
430 fieldRef = next.getSubField(fieldRef.getFieldID());
435 if (lookThroughCasts &&
436 isa<AsUIntPrimOp, AsSIntPrimOp, AsClockPrimOp, AsAsyncResetPrimOp>(
438 auto input = op->getOperand(0);
440 fieldRef = next.getSubField(fieldRef.getFieldID());
445 if (isa<PadPrimOp, TailPrimOp>(op)) {
446 auto input = op->getOperand(0);
448 fieldRef = next.getSubField(fieldRef.getFieldID());
457 if (!callback(original, fieldRef))
465 if (workStack.empty())
467 auto &back = workStack.back();
468 auto current = back.current;
470 if (back.it == current.user_end()) {
471 workStack.pop_back();
477 auto *user = *back.it++;
478 auto fieldID = back.fieldID;
480 if (
auto subfield = dyn_cast<SubfieldOp>(user)) {
481 BundleType bundleType = subfield.getInput().getType();
482 auto index = subfield.getFieldIndex();
483 auto subID = bundleType.getFieldID(index);
485 if (fieldID && index != bundleType.getIndexForFieldID(fieldID))
487 auto subRef = fieldRef.getSubField(subID);
488 auto subOriginal = original.getSubField(subID);
489 auto value = subfield.getResult();
492 workStack.emplace_back(subOriginal, subRef, value, 0);
495 workStack.emplace_back(subOriginal, subRef, value, fieldID - subID);
497 }
else if (
auto subindex = dyn_cast<SubindexOp>(user)) {
498 FVectorType vectorType = subindex.getInput().getType();
499 auto index = subindex.getIndex();
500 auto subID = vectorType.getFieldID(index);
502 if (fieldID && index != vectorType.getIndexForFieldID(fieldID))
504 auto subRef = fieldRef.getSubField(subID);
505 auto subOriginal = original.getSubField(subID);
506 auto value = subindex.getResult();
509 workStack.emplace_back(subOriginal, subRef, value, 0);
512 workStack.emplace_back(subOriginal, subRef, value, fieldID - subID);
514 }
else if (
auto connect = dyn_cast<FConnectLike>(user)) {
516 if (connect.getDest() != current)
534 if (LLVM_UNLIKELY(!value))
538 auto *op = value.getDefiningOp();
545 return TypeSwitch<Operation *, FieldRef>(op)
546 .Case<RefCastOp, ConstCastOp, UninferredResetCastOp>(
547 [lookThroughCasts](
auto op) {
548 if (!lookThroughCasts)
552 .Case<SubfieldOp, OpenSubfieldOp, SubindexOp, OpenSubindexOp, RefSubOp,
554 [](
auto subOp) {
return subOp.getAccessedField(); })
559 bool lookThroughCasts) {
560 if (LLVM_UNLIKELY(!value))
566 auto deltaRef =
getDeltaRef(value, lookThroughCasts);
570 id = deltaRef.getSubField(
id).getFieldID();
572 value = deltaRef.getValue();
577static void getDeclName(Value value, SmallString<64> &
string,
bool nameSafe) {
580 if (
auto arg = dyn_cast<BlockArgument>(value)) {
582 auto *op = arg.getOwner()->getParentOp();
583 TypeSwitch<Operation *>(op).Case<FModuleOp, ClassOp>([&](
auto op) {
584 auto name = cast<StringAttr>(op.getPortNames()[arg.getArgNumber()]);
585 string += name.getValue();
590 auto *op = value.getDefiningOp();
591 TypeSwitch<Operation *>(op)
592 .Case<ObjectOp>([&](ObjectOp op) {
593 string += op.getInstanceName();
596 .Case<InstanceOp, InstanceChoiceOp, MemOp>([&](
auto op) {
597 string += op.getName();
598 string += nameSafe ?
"_" :
".";
599 string += op.getPortName(cast<OpResult>(value).getResultNumber());
602 .Case<FNamableOp>([&](
auto op) {
603 string += op.getName();
606 .Case<mlir::UnrealizedConversionCastOp>(
607 [&](mlir::UnrealizedConversionCastOp cast) {
609 if (cast.getNumResults() == 1 && cast.getNumOperands() == 1 &&
610 cast.getResult(0).getType() == cast.getOperand(0).getType()) {
611 value = cast.getInputs()[0];
626std::pair<std::string, bool>
628 SmallString<64> name;
631 bool rootKnown = !name.empty();
633 auto type = value.getType();
637 if (
auto refTy = type_dyn_cast<RefType>(type))
638 type = refTy.getType();
640 if (
auto bundleType = type_dyn_cast<BundleType>(type)) {
641 auto index = bundleType.getIndexForFieldID(localID);
643 auto &element = bundleType.getElements()[index];
645 name += nameSafe ?
"_" :
".";
646 name += element.name.getValue();
649 localID = localID - bundleType.getFieldID(index);
650 }
else if (
auto bundleType = type_dyn_cast<OpenBundleType>(type)) {
651 auto index = bundleType.getIndexForFieldID(localID);
653 auto &element = bundleType.getElements()[index];
655 name += nameSafe ?
"_" :
".";
656 name += element.name.getValue();
659 localID = localID - bundleType.getFieldID(index);
660 }
else if (
auto vecType = type_dyn_cast<FVectorType>(type)) {
661 auto index = vecType.getIndexForFieldID(localID);
662 name += nameSafe ?
"_" :
"[";
663 name += std::to_string(index);
667 type = vecType.getElementType();
668 localID = localID - vecType.getFieldID(index);
669 }
else if (
auto vecType = type_dyn_cast<OpenVectorType>(type)) {
670 auto index = vecType.getIndexForFieldID(localID);
671 name += nameSafe ?
"_" :
"[";
672 name += std::to_string(index);
676 type = vecType.getElementType();
677 localID = localID - vecType.getFieldID(index);
678 }
else if (
auto classType = type_dyn_cast<ClassType>(type)) {
679 auto index = classType.getIndexForFieldID(localID);
680 auto &element = classType.getElement(index);
681 name += nameSafe ?
"_" :
".";
682 name += element.name.getValue();
684 localID = localID - classType.getFieldID(index);
690 llvm_unreachable(
"unsupported type");
694 return {name.str().str(), rootKnown};
702 Value value,
unsigned fieldID) {
704 while (fieldID != 0) {
706 .
Case<BundleType>([&](
auto bundle) {
707 auto index = bundle.getIndexForFieldID(fieldID);
708 value = SubfieldOp::create(builder, value, index);
709 fieldID -= bundle.getFieldID(index);
711 .Case<OpenBundleType>([&](
auto bundle) {
712 auto index = bundle.getIndexForFieldID(fieldID);
713 value = OpenSubfieldOp::create(builder, value, index);
714 fieldID -= bundle.getFieldID(index);
716 .Case<FVectorType>([&](
auto vector) {
717 auto index = vector.getIndexForFieldID(fieldID);
718 value = SubindexOp::create(builder, value, index);
719 fieldID -= vector.getFieldID(index);
721 .Case<OpenVectorType>([&](
auto vector) {
722 auto index = vector.getIndexForFieldID(fieldID);
723 value = OpenSubindexOp::create(builder, value, index);
724 fieldID -= vector.getFieldID(index);
726 .Case<RefType>([&](
auto reftype) {
728 .template Case<BundleType, FVectorType>([&](
auto type) {
729 auto index = type.getIndexForFieldID(fieldID);
730 value = RefSubOp::create(builder, value, index);
731 fieldID -= type.getFieldID(index);
733 .Default([&](
auto _) {
734 llvm::report_fatal_error(
735 "unrecognized type for indexing through with fieldID");
739 .Default([&](
auto _) {
740 llvm::report_fatal_error(
741 "unrecognized type for indexing through with fieldID");
761 return fn(0, type,
false);
763 uint64_t fieldID = 0;
764 auto recurse = [&](
auto &&f,
FIRRTLBaseType type,
bool isFlip) ->
void {
766 .
Case<BundleType>([&](BundleType bundle) {
767 for (
size_t i = 0, e = bundle.getNumElements(); i < e; ++i) {
769 f(f, bundle.getElementType(i),
770 isFlip ^ bundle.getElement(i).isFlip);
773 .
template Case<FVectorType>([&](FVectorType vector) {
774 for (
size_t i = 0, e = vector.getNumElements(); i < e; ++i) {
776 f(f, vector.getElementType(), isFlip);
779 .
template Case<FEnumType>([&](FEnumType fenum) {
783 fn(fieldID, fenum, isFlip);
786 assert(groundType.isGround() &&
787 "only ground types are expected here");
788 fn(fieldID, groundType, isFlip);
791 recurse(recurse, type,
false);
798 if (
auto arg = dyn_cast<BlockArgument>(root)) {
799 auto mod = cast<FModuleLike>(arg.getOwner()->getParentOp());
810 return TypeSwitch<Operation *, FieldRef>(ist.
getOp())
811 .Case<FModuleOp>([&](
auto fmod) {
817 auto symOp = dyn_cast<hw::InnerSymbolOpInterface>(ist.
getOp());
818 assert(symOp && symOp.getTargetResultIndex() &&
819 (symOp.supportsPerFieldSymbols() || ist.
getField() == 0));
825 MLIRContext *
context, hw::InnerSymAttr attr, uint64_t fieldID,
827 SmallVector<hw::InnerSymPropertiesAttr> props;
830 if (
auto sym = attr.getSymIfExists(fieldID))
832 llvm::append_range(props, attr.getProps());
836 auto sym = StringAttr::get(
context, getNamespace().newName(
"sym"));
837 props.push_back(hw::InnerSymPropertiesAttr::get(
842 [](
auto &p,
auto &q) {
return p.getFieldID() < q.getFieldID(); });
843 return {hw::InnerSymAttr::get(
context, props), sym};
850 if (
auto mod = dyn_cast<FModuleLike>(target.
getOp())) {
851 auto portIdx = target.
getPort();
852 assert(portIdx < mod.getNumPorts());
856 mod.setPortSymbolAttr(portIdx, attr);
861 if (
auto symOp = dyn_cast<hw::InnerSymbolOpInterface>(target.
getOp())) {
865 symOp.setInnerSymbolAttr(attr);
870 assert(0 &&
"target must be port of FModuleLike or InnerSymbol");
878 module = cast<FModuleLike>(target.getOp());
880 module = target.getOp()->getParentOfType<FModuleOp>();
884 return getNamespace(module);
893 auto mod = target.
isPort() ? dyn_cast<FModuleLike>(target.
getOp())
894 : target.
getOp()->getParentOfType<FModuleOp>();
896 "must be an operation inside an FModuleOp or port of FModuleLike");
897 return hw::InnerRefAttr::get(SymbolTable::getSymbolName(mod),
902std::pair<bool, std::optional<mlir::LocationAttr>>
904 StringAttr &locatorFilenameCache,
905 FileLineColLoc &fileLineColLocCache,
908 if (!spelling.starts_with(
"@[") || !spelling.ends_with(
"]"))
909 return {
false, std::nullopt};
911 spelling = spelling.drop_front(2).drop_back(1);
915 auto decodeLocator = [&](StringRef input,
unsigned &resultLineNo,
916 unsigned &resultColNo) -> StringRef {
918 auto spaceLoc = input.find_last_of(
' ');
919 if (spaceLoc == StringRef::npos)
922 auto filename = input.take_front(spaceLoc);
923 auto lineAndColumn = input.drop_front(spaceLoc + 1);
927 StringRef lineStr, colStr;
928 std::tie(lineStr, colStr) = lineAndColumn.split(
':');
931 if (lineStr.getAsInteger(10, resultLineNo))
933 if (!colStr.empty()) {
934 if (colStr.front() !=
'{') {
935 if (colStr.getAsInteger(10, resultColNo))
939 if (colStr.drop_front().split(
',').first.getAsInteger(10, resultColNo))
947 unsigned lineNo = 0, columnNo = 0;
948 StringRef filename = decodeLocator(spelling, lineNo, columnNo);
949 if (filename.empty())
950 return {
false, std::nullopt};
955 return {
true, std::nullopt};
959 auto getFileLineColLoc = [&](StringRef filename,
unsigned lineNo,
960 unsigned columnNo) -> FileLineColLoc {
962 StringAttr filenameId = locatorFilenameCache;
963 if (filenameId.str() != filename) {
965 locatorFilenameCache = filenameId = StringAttr::get(
context, filename);
969 return fileLineColLocCache =
970 FileLineColLoc::get(filenameId, lineNo, columnNo);
974 auto result = fileLineColLocCache;
975 if (result && result.getLine() == lineNo && result.getColumn() == columnNo)
978 return fileLineColLocCache =
979 FileLineColLoc::get(filenameId, lineNo, columnNo);
990 SmallVector<Location> extraLocs;
991 auto spaceLoc = filename.find_last_of(
' ');
992 while (spaceLoc != StringRef::npos) {
995 unsigned nextLineNo = 0, nextColumnNo = 0;
997 decodeLocator(filename.take_front(spaceLoc), nextLineNo, nextColumnNo);
1000 if (nextFilename.empty())
1006 getFileLineColLoc(filename.drop_front(spaceLoc + 1), lineNo, columnNo);
1007 extraLocs.push_back(loc);
1008 filename = nextFilename;
1009 lineNo = nextLineNo;
1010 columnNo = nextColumnNo;
1011 spaceLoc = filename.find_last_of(
' ');
1014 mlir::LocationAttr result = getFileLineColLoc(filename, lineNo, columnNo);
1015 if (!extraLocs.empty()) {
1016 extraLocs.push_back(result);
1017 std::reverse(extraLocs.begin(), extraLocs.end());
1018 result = FusedLoc::get(
context, extraLocs);
1020 return {
true, result};
1027 Type type, std::optional<Location> loc,
1028 llvm::function_ref<hw::TypeAliasType(Type, BaseTypeAliasType, Location)>
1030 auto firType = type_dyn_cast<FIRRTLBaseType>(type);
1036 if (BaseTypeAliasType aliasType = dyn_cast<BaseTypeAliasType>(firType)) {
1038 loc = UnknownLoc::get(type.getContext());
1039 type =
lowerType(aliasType.getInnerType(), loc, getTypeDeclFn);
1040 return getTypeDeclFn(type, aliasType, *loc);
1043 firType = firType.getPassiveType();
1045 if (
auto bundle = type_dyn_cast<BundleType>(firType)) {
1046 mlir::SmallVector<hw::StructType::FieldInfo, 8> hwfields;
1047 for (
auto element : bundle) {
1048 Type etype =
lowerType(element.type, loc, getTypeDeclFn);
1051 hwfields.push_back(hw::StructType::FieldInfo{element.name, etype});
1053 return hw::StructType::get(type.getContext(), hwfields);
1055 if (
auto vec = type_dyn_cast<FVectorType>(firType)) {
1056 auto elemTy =
lowerType(vec.getElementType(), loc, getTypeDeclFn);
1059 return hw::ArrayType::get(elemTy, vec.getNumElements());
1061 if (
auto fenum = type_dyn_cast<FEnumType>(firType)) {
1062 mlir::SmallVector<hw::UnionType::FieldInfo, 8> hwfields;
1064 for (
auto element : fenum) {
1065 Type etype =
lowerType(element.type, loc, getTypeDeclFn);
1068 hwfields.push_back(hw::UnionType::FieldInfo{element.name, etype, 0});
1069 if (element.type.getBitWidthOrSentinel() != 0)
1072 auto tagTy = IntegerType::get(type.getContext(), fenum.getTagWidth());
1075 auto bodyTy = hw::UnionType::get(type.getContext(), hwfields);
1076 hw::StructType::FieldInfo fields[2] = {
1077 {StringAttr::get(type.getContext(),
"tag"), tagTy},
1078 {StringAttr::get(type.getContext(),
"body"), bodyTy}};
1079 return hw::StructType::get(type.getContext(), fields);
1081 if (type_isa<ClockType>(firType))
1082 return seq::ClockType::get(firType.getContext());
1084 auto width = firType.getBitWidthOrSentinel();
1086 return IntegerType::get(type.getContext(), width);
1092 mlir::ImplicitLocOpBuilder &builderOM) {
1094 auto *
context = op->getContext();
1095 auto id = DistinctAttr::create(UnitAttr::get(
context));
1096 TargetKind kind = TargetKind::Reference;
1099 NamedAttrList fields;
1100 fields.append(
"id",
id);
1101 fields.append(
"class", StringAttr::get(
context,
"circt.tracker"));
1103 fields.append(
"circt.nonlocal", mlir::FlatSymbolRefAttr::get(nla));
1107 if (isa<InstanceOp, FModuleLike>(op))
1108 kind = TargetKind::Instance;
1112 return PathOp::create(builderOM, kind,
id);
1121 llvm::StringRef formatString,
1122 llvm::ArrayRef<mlir::Value> specOperands,
1123 mlir::StringAttr &formatStringResult,
1124 llvm::SmallVectorImpl<mlir::Value> &operands) {
1127 llvm::SmallString<64> validatedFormatString;
1129 for (
size_t i = 0, e = formatString.size(), opIdx = 0; i != e; ++i) {
1130 auto c = formatString[i];
1135 validatedFormatString.push_back(c);
1138 llvm::SmallString<6> width;
1139 c = formatString[++i];
1142 c = formatString[++i];
1149 return mlir::emitError(loc) <<
"ASCII character format specifiers "
1150 "('%c') may not specify a width";
1156 validatedFormatString.append(width);
1157 if (specOperands.size() <= opIdx)
1158 return mlir::emitError(loc) <<
"not enough operands for format "
1160 operands.push_back(specOperands[opIdx++]);
1164 return mlir::emitError(loc)
1165 <<
"literal percents ('%%') may not specify a width";
1169 return mlir::emitError(loc)
1170 <<
"unknown printf substitution '%" << width << c <<
"'";
1172 validatedFormatString.push_back(c);
1180 if (formatString[i + 1] !=
'{') {
1181 validatedFormatString.push_back(c);
1187 while (formatString[i] !=
'}')
1189 if (formatString[i] !=
'}')
1190 return mlir::emitError(loc)
1191 <<
"expected '}' to terminate special substitution";
1193 auto specialString = formatString.slice(start, i);
1194 if (specialString ==
"SimulationTime") {
1195 operands.push_back(TimeOp::create(builder, loc));
1196 }
else if (specialString ==
"HierarchicalModuleName") {
1197 operands.push_back(HierarchicalModuleNameOp::create(builder, loc));
1199 return mlir::emitError(loc)
1200 <<
"unknown printf substitution '" << specialString
1201 <<
"' (did you misspell it?)";
1204 validatedFormatString.append(
"{{}}");
1209 validatedFormatString.push_back(c);
1213 formatStringResult = builder.getStringAttr(validatedFormatString);
1214 return mlir::success();
1222 Operation *operation) {
1223 if (
auto mod = dyn_cast<mlir::ModuleOp>(operation))
1224 for (
auto &op : *mod.getBody())
1225 if ((operation = dyn_cast<CircuitOp>(&op)))
1228 for (
auto option : cast<CircuitOp>(operation).getOps<OptionOp>())
1229 for (
auto optionCase : option.getOps<OptionCaseOp>())
1230 cache[{option.getSymNameAttr(), optionCase.getSymNameAttr()}] =
1231 optionCase.getCaseMacroAttr();
1236 StringAttr caseName)
const {
1237 auto it = cache.find({optionName, caseName});
1238 if (it == cache.end())
assert(baseType &&"element must be base type")
MlirType uint64_t numElements
static std::unique_ptr< Context > context
static LogicalResult connectIfAggregates(ImplicitLocOpBuilder &builder, Value dst, FIRRTLType dstFType, Value src, FIRRTLType srcFType)
static void getDeclName(Value value, SmallString< 64 > &string, bool nameSafe)
Get the string name of a value which is a direct child of a declaration op.
static Value lookThroughWires(Value value)
Trace a value through wires to its original definition.
This class represents a reference to a specific field or element of an aggregate value.
unsigned getFieldID() const
Get the field ID of this FieldRef, which is a unique identifier mapped to a specific field in a bundl...
Value getValue() const
Get the Value which created this location.
This class provides a read-only projection over the MLIR attributes that represent a set of annotatio...
bool applyToOperation(Operation *op) const
Store the annotations in this set in an operation's annotations attribute, overwriting any existing a...
void addAnnotations(ArrayRef< Annotation > annotations)
Add more annotations to this annotation set.
bool isConst() const
Returns true if this is a 'const' type that can only hold compile-time constant values.
This class implements the same functionality as TypeSwitch except that it uses firrtl::type_dyn_cast ...
FIRRTLTypeSwitch< T, ResultT > & Case(CallableT &&caseFn)
Add a case on the given type.
FlatSymbolRefAttr getMacro(StringAttr optionName, StringAttr caseName) const
InstanceChoiceMacroTable(Operation *op)
This is the common base class between SIntType and UIntType.
IntType getConstType(bool isConst) const
Return a 'const' or non-'const' version of this type.
ImplicitLocOpBuilder & builder
SmallDenseMap< Type, Value, 8 > cache
Value getUnknown(PropertyType type)
Get or create an UnknownValueOp for the given property type.
The target of an inner symbol, the entity the symbol is a handle for.
auto getField() const
Return the target's fieldID.
auto getPort() const
Return the target's port, if valid. Check "isPort()".
bool isPort() const
Return if this targets a port.
Operation * getOp() const
Return the target's base operation. For ports, this is the module.
llvm::function_ref< hw::InnerSymbolNamespace &(FModuleLike mod)> GetNamespaceCallback
FieldRef getFieldRefForTarget(const hw::InnerSymTarget &ist)
Get FieldRef pointing to the specified inner symbol target, which must be valid.
FieldRef getDeltaRef(Value value, bool lookThroughCasts=false)
Get the delta indexing from a value, as a FieldRef.
FIRRTLBaseType getBaseType(Type type)
If it is a base type, return it as is.
FieldRef getFieldRefFromValue(Value value, bool lookThroughCasts=false)
Get the FieldRef from a value.
mlir::TypedValue< FIRRTLBaseType > FIRRTLBaseValue
void walkGroundTypes(FIRRTLType firrtlType, llvm::function_ref< void(uint64_t, FIRRTLBaseType, bool)> fn)
Walk leaf ground types in the firrtlType and apply the function fn.
PathOp createPathRef(Operation *op, hw::HierPathOp nla, mlir::ImplicitLocOpBuilder &builderOM)
Add the tracker annotation to the op and get a PathOp to the op.
IntegerAttr getIntAttr(Type type, const APInt &value)
Utiility for generating a constant attribute.
std::pair< bool, std::optional< mlir::LocationAttr > > maybeStringToLocation(llvm::StringRef spelling, bool skipParsing, mlir::StringAttr &locatorFilenameCache, FileLineColLoc &fileLineColLocCache, MLIRContext *context)
std::pair< hw::InnerSymAttr, StringAttr > getOrAddInnerSym(MLIRContext *context, hw::InnerSymAttr attr, uint64_t fieldID, llvm::function_ref< hw::InnerSymbolNamespace &()> getNamespace)
Ensure that the the InnerSymAttr has a symbol on the field specified.
hw::InnerRefAttr getInnerRefTo(const hw::InnerSymTarget &target, GetNamespaceCallback getNamespace)
Obtain an inner reference to the target (operation or port), adding an inner symbol as necessary.
PropAssignOp getPropertyAssignment(FIRRTLPropertyValue value)
Return the single assignment to a Property value.
mlir::ParseResult parseFormatString(mlir::OpBuilder &builder, mlir::Location loc, llvm::StringRef formatString, llvm::ArrayRef< mlir::Value > specOperands, mlir::StringAttr &formatStringResult, llvm::SmallVectorImpl< mlir::Value > &operands)
Value getModuleScopedDriver(Value val, bool lookThroughWires, bool lookThroughNodes, bool lookThroughCasts)
Return the value that drives another FIRRTL value within module scope.
Value getDriverFromConnect(Value val)
Return the module-scoped driver of a value only looking through one connect.
Value getValueByFieldID(ImplicitLocOpBuilder builder, Value value, unsigned fieldID)
This gets the value targeted by a field id.
std::pair< std::string, bool > getFieldName(const FieldRef &fieldRef, bool nameSafe=false)
Get a string identifier representing the FieldRef.
llvm::function_ref< bool(const FieldRef &dst, const FieldRef &src)> WalkDriverCallback
Walk all the drivers of a value, passing in the connect operations drive the value.
mlir::TypedValue< PropertyType > FIRRTLPropertyValue
Type lowerType(Type type, std::optional< Location > loc={}, llvm::function_ref< hw::TypeAliasType(Type, BaseTypeAliasType, Location)> getTypeDeclFn={})
Given a type, return the corresponding lowered type for the HW dialect.
hw::InnerSymTarget getTargetFor(FieldRef ref)
Return the inner sym target for the specified value and fieldID.
bool areTypesConstCastable(FIRRTLType destType, FIRRTLType srcType, bool srcOuterTypeIsConst=false)
Returns whether the srcType can be const-casted to the destType.
bool walkDrivers(FIRRTLBaseValue value, bool lookThroughWires, bool lookThroughNodes, bool lookThroughCasts, WalkDriverCallback callback)
IntegerAttr getIntOnesAttr(Type type)
Utility for generating a constant all ones attribute.
void emitConnect(OpBuilder &builder, Location loc, Value lhs, Value rhs)
Emit a connect between two values.
IntegerAttr getIntZerosAttr(Type type)
Utility for generating a constant zero attribute.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.