12 #include "mlir/Transforms/DialectConversion.h"
13 #include "llvm/ADT/TypeSwitch.h"
16 using namespace circt;
28 return llvm::none_of(moduleLikeOp.getHWModuleType().getPortTypes(),
33 llvm::SmallVector<Type> inner;
34 t.getInnerTypes(inner);
35 for (
auto [index,
innerType] : llvm::enumerate(inner))
44 OutputOpConversion(TypeConverter &typeConverter, MLIRContext *context,
45 DenseSet<Operation *> *opVisited)
49 matchAndRewrite(hw::OutputOp op, OpAdaptor adaptor,
50 ConversionPatternRewriter &rewriter)
const override {
51 llvm::SmallVector<Value> convOperands;
54 for (
auto operand : adaptor.getOperands()) {
56 auto explodedStruct = rewriter.create<hw::StructExplodeOp>(
58 llvm::copy(explodedStruct.getResults(),
59 std::back_inserter(convOperands));
61 convOperands.push_back(operand);
66 rewriter.replaceOpWithNewOp<hw::OutputOp>(op, convOperands);
67 opVisited->insert(op->getParentOp());
70 DenseSet<Operation *> *opVisited;
74 InstanceOpConversion(TypeConverter &typeConverter, MLIRContext *context,
75 DenseSet<hw::InstanceOp> *convertedOps,
76 const StringSet<> *externModules)
78 externModules(externModules) {}
81 matchAndRewrite(hw::InstanceOp op, OpAdaptor adaptor,
82 ConversionPatternRewriter &rewriter)
const override {
83 auto referencedMod = op.getReferencedModuleNameAttr();
86 if (externModules->contains(referencedMod.getValue()))
89 auto loc = op.getLoc();
91 llvm::SmallVector<Value> convOperands;
92 for (
auto operand : adaptor.getOperands()) {
94 auto explodedStruct = rewriter.create<hw::StructExplodeOp>(
96 llvm::copy(explodedStruct.getResults(),
97 std::back_inserter(convOperands));
99 convOperands.push_back(operand);
104 llvm::SmallVector<Type> newResultTypes;
105 for (
auto oldResultType : op.getResultTypes()) {
107 for (
auto t : structType.getElements())
108 newResultTypes.push_back(t.type);
110 newResultTypes.push_back(oldResultType);
115 auto newInstance = rewriter.create<hw::InstanceOp>(
116 loc, newResultTypes, op.getInstanceNameAttr(),
118 op.getArgNamesAttr(), op.getResultNamesAttr(), op.getParametersAttr(),
119 op.getInnerSymAttr());
122 llvm::SmallVector<Value> convResults;
123 size_t oldResultCntr = 0;
124 for (
size_t resIndex = 0; resIndex < newInstance.getNumResults();
126 Type oldResultType = op.getResultTypes()[oldResultCntr];
128 size_t nElements = structType.getElements().size();
131 newInstance.getResults().slice(resIndex, nElements));
132 convResults.push_back(implodedStruct.getResult());
133 resIndex += nElements - 1;
135 convResults.push_back(newInstance.getResult(resIndex));
139 rewriter.replaceOp(op, convResults);
140 convertedOps->insert(newInstance);
144 DenseSet<hw::InstanceOp> *convertedOps;
145 const StringSet<> *externModules;
148 using IOTypes = std::pair<TypeRange, TypeRange>;
152 DenseMap<unsigned, hw::StructType> argStructs, resStructs;
155 SmallVector<Type> argTypes, resTypes;
158 class FlattenIOTypeConverter :
public TypeConverter {
160 FlattenIOTypeConverter() {
161 addConversion([](Type type, SmallVectorImpl<Type> &results) {
164 results.push_back(type);
166 for (
auto field : structType.getElements())
168 results.push_back(field.type);
173 addTargetMaterialization([](OpBuilder &
builder, hw::StructType type,
174 ValueRange
inputs, Location loc) {
176 return result.getResult();
179 addTargetMaterialization([](OpBuilder &
builder, hw::TypeAliasType type,
180 ValueRange
inputs, Location loc) {
182 assert(structType &&
"expected struct type");
184 return result.getResult();
191 template <
typename... TOp>
193 ConversionTarget &target,
195 FlattenIOTypeConverter &typeConverter) {
210 target.addDynamicallyLegalOp<TOp...>([&](hw::HWModuleLike moduleLikeOp) {
215 auto ioInfoIt = ioMap.find(moduleLikeOp);
216 if (ioInfoIt == ioMap.end()) {
221 auto ioInfo = ioInfoIt->second;
223 auto compareTypes = [&](TypeRange oldTypes, TypeRange newTypes) {
224 return llvm::any_of(llvm::zip(oldTypes, newTypes), [&](
auto typePair) {
225 auto oldType = std::get<0>(typePair);
226 auto newType = std::get<1>(typePair);
227 return oldType != newType;
230 auto mtype = moduleLikeOp.getHWModuleType();
231 if (
compareTypes(mtype.getOutputTypes(), ioInfo.resTypes) ||
241 template <
typename T>
243 return llvm::any_of(module.getBody()->getOps<T>(),
244 [](T op) { return !isLegalModLikeOp(op); });
247 template <
typename T>
248 static DenseMap<Operation *, IOTypes>
populateIOMap(mlir::ModuleOp module) {
249 DenseMap<Operation *, IOTypes> ioMap;
250 for (
auto op : module.getOps<T>())
251 ioMap[op] = {op.getArgumentTypes(), op.getResultTypes()};
255 template <
typename ModTy,
typename T>
256 static llvm::SmallVector<Attribute>
258 DenseMap<unsigned, hw::StructType> &structMap, T oldNames,
260 llvm::SmallVector<Attribute> newNames;
261 for (
auto [i, oldName] : llvm::enumerate(oldNames)) {
263 auto it = structMap.find(i);
264 if (it == structMap.end()) {
272 auto structType = it->second;
273 for (
auto field : structType.getElements())
275 op->getContext(), oldName + Twine(joinChar) + field.name.str()));
280 template <
typename ModTy>
285 SmallVector<Attribute> newNames;
286 SmallVector<hw::ModulePort> oldPorts(oldModType.getPorts().begin(),
287 oldModType.getPorts().end());
288 for (
auto oldPort : oldPorts) {
289 auto oldName = oldPort.name;
291 for (
auto field : structType.getElements()) {
294 oldName.getValue() + Twine(joinChar) + field.name.str()));
297 newNames.push_back(oldName);
299 op.setAllPortNames(newNames);
302 static llvm::SmallVector<Location>
304 SmallVectorImpl<Location> &oldLocs) {
305 llvm::SmallVector<Location> newLocs;
306 for (
auto [i, oldLoc] : llvm::enumerate(oldLocs)) {
308 auto it = structMap.find(i);
309 if (it == structMap.end()) {
311 newLocs.push_back(oldLoc);
315 auto structType = it->second;
316 for (
size_t i = 0, e = structType.getElements().size(); i < e; ++i)
317 newLocs.push_back(oldLoc);
327 DenseMap<unsigned, hw::StructType> &structMap) {
328 auto locs = op.getInputLocs();
329 if (locs.empty() || op.getModuleBody().empty())
331 for (
auto [arg, loc] : llvm::zip(op.getBodyBlock()->getArguments(), locs))
335 static void setIOInfo(hw::HWModuleLike op, IOInfo &ioInfo) {
336 ioInfo.argTypes = op.getInputTypes();
337 ioInfo.resTypes = op.getOutputTypes();
338 for (
auto [i, arg] : llvm::enumerate(ioInfo.argTypes)) {
340 ioInfo.argStructs[i] = structType;
342 for (
auto [i, res] : llvm::enumerate(ioInfo.resTypes)) {
344 ioInfo.resStructs[i] = structType;
348 template <
typename T>
350 DenseMap<Operation *, IOInfo> ioInfoMap;
351 for (
auto op : module.getOps<T>()) {
354 ioInfoMap[op] = ioInfo;
359 template <
typename T>
361 StringSet<> &externModules,
363 auto *ctx = module.getContext();
364 FlattenIOTypeConverter typeConverter;
369 while (hasUnconvertedOps<T>(module)) {
370 ConversionTarget target(*ctx);
372 target.addLegalDialect<hw::HWDialect>();
376 auto ioInfoMap = populateIOInfoMap<T>(module);
381 llvm::DenseSet<hw::InstanceOp> convertedInstances;
386 DenseSet<Operation *> opVisited;
387 patterns.add<OutputOpConversion>(typeConverter, ctx, &opVisited);
389 patterns.add<InstanceOpConversion>(typeConverter, ctx, &convertedInstances,
391 target.addDynamicallyLegalOp<hw::OutputOp>(
392 [&](
auto op) {
return opVisited.contains(op->getParentOp()); });
393 target.addDynamicallyLegalOp<hw::InstanceOp>([&](hw::InstanceOp op) {
394 auto refName = op.getReferencedModuleName();
395 return externModules.contains(refName) ||
396 llvm::none_of(op->getOperands(), [](
auto operand) {
397 return isStructType(operand.getType());
401 DenseMap<Operation *, ArrayAttr> oldArgNames, oldResNames;
402 DenseMap<Operation *, SmallVector<Location>> oldArgLocs, oldResLocs;
403 DenseMap<Operation *, hw::ModuleType> oldModTypes;
405 for (
auto op : module.getOps<T>()) {
406 oldModTypes[op] = op.getHWModuleType();
407 oldArgNames[op] =
ArrayAttr::get(module.getContext(), op.getInputNames());
410 oldArgLocs[op] = op.getInputLocs();
411 oldResLocs[op] = op.getOutputLocs();
415 addSignatureConversion<T>(ioInfoMap, target,
patterns, typeConverter);
417 if (failed(applyPartialConversion(module, target, std::move(
patterns))))
421 for (
auto op : module.getOps<T>()) {
422 auto ioInfo = ioInfoMap[op];
426 newArgLocs.append(newResLocs.begin(), newResLocs.end());
427 op.setAllPortLocs(newArgLocs);
432 for (
auto instanceOp : convertedInstances) {
434 cast<hw::HWModuleLike>(SymbolTable::lookupNearestSymbolFrom(
435 instanceOp, instanceOp.getReferencedModuleNameAttr()));
438 if (!ioInfoMap.contains(targetModule)) {
441 ioInfoMap[targetModule] = ioInfo;
442 oldArgNames[targetModule] =
443 ArrayAttr::get(module.getContext(), targetModule.getInputNames());
444 oldResNames[targetModule] =
445 ArrayAttr::get(module.getContext(), targetModule.getOutputNames());
446 oldArgLocs[targetModule] = targetModule.getInputLocs();
447 oldResLocs[targetModule] = targetModule.getOutputLocs();
449 ioInfo = ioInfoMap[targetModule];
452 instanceOp.getContext(),
454 instanceOp,
"argNames", ioInfo.argStructs,
455 oldArgNames[targetModule].template getAsValueRange<StringAttr>(),
458 instanceOp.getContext(),
460 instanceOp,
"resultNames", ioInfo.resStructs,
461 oldResNames[targetModule].template getAsValueRange<StringAttr>(),
476 template <
typename... TOps>
478 StringSet<> &externModules,
char joinChar) {
479 return (failed(flattenOpsOfType<TOps>(module, recursive, externModules,
486 class FlattenIOPass :
public circt::hw::FlattenIOBase<FlattenIOPass> {
488 FlattenIOPass(
bool recursiveFlag,
bool flattenExternFlag,
char join) {
489 recursive = recursiveFlag;
490 flattenExtern = flattenExternFlag;
494 void runOnOperation()
override {
495 ModuleOp module = getOperation();
496 if (!flattenExtern) {
499 externModules.insert(m.getModuleName());
500 if (flattenIO<hw::HWModuleOp, hw::HWModuleGeneratedOp>(
501 module, recursive, externModules, joinChar))
507 hw::HWModuleGeneratedOp>(module, recursive, externModules,
513 StringSet<> externModules;
522 bool flattenExternFlag,
524 return std::make_unique<FlattenIOPass>(recursiveFlag, flattenExternFlag,
assert(baseType &&"element must be base type")
static LogicalResult compareTypes(Location loc, TypeRange rangeA, TypeRange rangeB)
static llvm::SmallVector< Type > getInnerTypes(hw::StructType t)
static llvm::SmallVector< Location > updateLocAttribute(DenseMap< unsigned, hw::StructType > &structMap, SmallVectorImpl< Location > &oldLocs)
static bool isLegalModLikeOp(hw::HWModuleLike moduleLikeOp)
static void updateBlockLocations(hw::HWModuleLike op, DenseMap< unsigned, hw::StructType > &structMap)
The conversion framework seems to throw away block argument locations.
static bool hasUnconvertedOps(mlir::ModuleOp module)
static llvm::SmallVector< Attribute > updateNameAttribute(ModTy op, StringRef attrName, DenseMap< unsigned, hw::StructType > &structMap, T oldNames, char joinChar)
static void setIOInfo(hw::HWModuleLike op, IOInfo &ioInfo)
static LogicalResult flattenOpsOfType(ModuleOp module, bool recursive, StringSet<> &externModules, char joinChar)
static DenseMap< Operation *, IOTypes > populateIOMap(mlir::ModuleOp module)
static void addSignatureConversion(DenseMap< Operation *, IOInfo > &ioMap, ConversionTarget &target, RewritePatternSet &patterns, FlattenIOTypeConverter &typeConverter)
static bool isStructType(Type type)
static void updateModulePortNames(ModTy op, hw::ModuleType oldModType, char joinChar)
static hw::StructType getStructType(Type type)
static bool flattenIO(ModuleOp module, bool recursive, StringSet<> &externModules, char joinChar)
static DenseMap< Operation *, IOInfo > populateIOInfoMap(mlir::ModuleOp module)
llvm::SmallVector< StringAttr > inputs
Direction get(bool isOutput)
Returns an output direction if isOutput is true, otherwise returns an input direction.
mlir::Type innerType(mlir::Type type)
void populateHWModuleLikeTypeConversionPattern(StringRef moduleLikeOpName, RewritePatternSet &patterns, TypeConverter &converter)
mlir::Type getCanonicalType(mlir::Type type)
std::unique_ptr< mlir::Pass > createFlattenIOPass(bool recursiveFlag=true, bool flattenExternFlag=false, char joinChar='.')
The InstanceGraph op interface, see InstanceGraphInterface.td for more details.