18#include "mlir/Pass/Pass.h"
19#include "llvm/Support/Debug.h"
22#define DEBUG_TYPE "lower-memory"
26#define GEN_PASS_DEF_FLATTENMEMORY
27#include "circt/Dialect/FIRRTL/Passes.h.inc"
32using namespace firrtl;
35struct FlattenMemoryPass
36 :
public circt::firrtl::impl::FlattenMemoryBase<FlattenMemoryPass> {
40 static bool hasSubAnno(MemOp op) {
41 for (
size_t portIdx = 0, e = op.getNumResults(); portIdx < e; ++portIdx)
42 for (
auto attr : op.getPortAnnotation(portIdx))
43 if (cast<DictionaryAttr>(attr).get(
"circt.fieldID"))
50 void runOnOperation()
override {
51 LLVM_DEBUG(llvm::dbgs() <<
"\n Running lower memory on module:"
53 SmallVector<Operation *> opsToErase;
54 getOperation().getBodyBlock()->walk([&](MemOp memOp) {
55 LLVM_DEBUG(llvm::dbgs() <<
"\n Memory:" << memOp);
60 for (
auto res : memOp.getResults())
61 if (isa<RefType>(res.getType()))
67 if (hasSubAnno(memOp))
72 SmallVector<FIRRTLBaseType> flatMemType;
73 if (!flattenType(memOp.getDataType(), flatMemType))
78 size_t memFlatWidth = 0;
79 SmallVector<int32_t> memWidths;
80 for (
auto f : flatMemType) {
81 LLVM_DEBUG(llvm::dbgs() <<
"\n field type:" << f);
82 auto w = f.getBitWidthOrSentinel();
83 memWidths.push_back(w);
93 auto maskGran = memWidths.front();
94 for (
auto w : ArrayRef(memWidths).drop_front())
95 maskGran = std::gcd(maskGran, w);
98 uint32_t totalmaskWidths = 0;
100 SmallVector<unsigned> maskWidths;
101 for (
auto w : memWidths) {
103 auto mWidth = w / maskGran;
104 maskWidths.push_back(mWidth);
105 totalmaskWidths += mWidth;
110 SmallVector<Type, 8> ports;
111 SmallVector<Attribute, 8> portNames;
113 auto *context = memOp.getContext();
114 ImplicitLocOpBuilder builder(memOp.getLoc(), memOp);
116 auto flatType = UIntType::get(context, memFlatWidth);
117 for (
auto port : memOp.getPorts()) {
118 ports.push_back(MemOp::getTypeForPort(memOp.getDepth(), flatType,
119 port.second, totalmaskWidths));
120 portNames.push_back(port.first);
124 auto flatMem = MemOp::create(
125 builder, ports, memOp.getReadLatency(), memOp.getWriteLatency(),
126 memOp.getDepth(), memOp.getRuw(), builder.getArrayAttr(portNames),
127 memOp.getNameAttr(), memOp.getNameKind(), memOp.getAnnotations(),
128 memOp.getPortAnnotations(), memOp.getInnerSymAttr(),
129 memOp.getInitAttr(), memOp.getPrefixAttr());
132 for (
size_t index = 0, rend = memOp.getNumResults(); index < rend;
138 auto result = memOp.getResult(index);
139 auto wire = WireOp::create(builder, result.getType(),
140 (memOp.getName() +
"_" +
141 memOp.getPortName(index).getValue())
144 result.replaceAllUsesWith(wire);
146 auto newResult = flatMem.getResult(index);
147 auto rType = type_cast<BundleType>(result.getType());
148 for (
size_t fieldIndex = 0, fend = rType.getNumElements();
149 fieldIndex != fend; ++fieldIndex) {
150 auto name = rType.getElement(fieldIndex).name;
151 auto oldField = SubfieldOp::create(builder, result, fieldIndex);
153 SubfieldOp::create(builder, newResult, fieldIndex);
156 if (!(name ==
"data" || name ==
"mask" || name ==
"wdata" ||
157 name ==
"wmask" || name ==
"rdata")) {
161 Value realOldField = oldField;
162 if (rType.getElement(fieldIndex).isFlip) {
165 builder.createOrFold<BitCastOp>(oldField.getType(), newField);
170 auto newFieldType = newField.getType();
171 auto oldFieldBitWidth =
getBitWidth(oldField.getType());
174 if (
getBitWidth(newFieldType) != *oldFieldBitWidth)
175 newFieldType = UIntType::get(context, *oldFieldBitWidth);
176 realOldField = BitCastOp::create(builder, newFieldType, oldField);
180 if ((name ==
"mask" || name ==
"wmask") &&
181 (maskWidths.size() != totalmaskWidths)) {
183 for (
const auto &m :
llvm::enumerate(maskWidths)) {
185 auto mBit = builder.createOrFold<BitsPrimOp>(
186 realOldField, m.index(), m.index());
188 for (
size_t repeat = 0; repeat < m.value(); repeat++)
189 if ((m.index() == 0 && repeat == 0) || !catMasks)
192 catMasks = builder.createOrFold<CatPrimOp>(
193 ValueRange{mBit, catMasks});
195 realOldField = catMasks;
200 builder.createOrFold<BitCastOp>(newField.getType(),
216 SmallVectorImpl<FIRRTLBaseType> &results) {
219 .
Case<BundleType>([&](
auto bundle) {
220 for (
auto &elt : bundle)
221 if (!flatten(elt.type))
225 .Case<FVectorType>([&](
auto vector) {
226 for (
size_t i = 0, e = vector.getNumElements(); i != e; ++i)
227 if (!flatten(vector.getElementType()))
231 .Case<IntType>([&](
IntType type) {
232 results.push_back(type);
235 .Case<FEnumType>([&](FEnumType type) {
236 results.emplace_back(type);
239 .Default([&](
auto) {
return false; });
242 return flatten(type) && results.size() > 1;
245 Value getSubWhatever(ImplicitLocOpBuilder *builder, Value val,
size_t index) {
246 if (BundleType bundle = type_dyn_cast<BundleType>(val.getType()))
247 return builder->create<SubfieldOp>(val, index);
248 if (FVectorType fvector = type_dyn_cast<FVectorType>(val.getType()))
249 return builder->create<SubindexOp>(val, index);
251 llvm_unreachable(
"Unknown aggregate type");
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.
This is the common base class between SIntType and UIntType.
std::optional< int32_t > getWidth() const
Return an optional containing the width, if the width is known (or empty if width is unknown).
mlir::TypedValue< FIRRTLBaseType > FIRRTLBaseValue
void emitConnect(OpBuilder &builder, Location loc, Value lhs, Value rhs)
Emit a connect between two values.
std::optional< int64_t > getBitWidth(FIRRTLBaseType type, bool ignoreFlip=false)
StringAttr getName(ArrayAttr names, size_t idx)
Return the name at the specified index of the ArrayAttr or null if it cannot be determined.
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.