11 #include "mlir/Pass/Pass.h"
12 #include "mlir/Transforms/DialectConversion.h"
13 #include "llvm/ADT/TypeSwitch.h"
17 #define GEN_PASS_DEF_FLATTENIO
18 #include "circt/Dialect/HW/Passes.h.inc"
23 using namespace circt;
35 return llvm::none_of(moduleLikeOp.getHWModuleType().getPortTypes(),
40 llvm::SmallVector<Type> inner;
41 t.getInnerTypes(inner);
42 for (
auto [index,
innerType] : llvm::enumerate(inner))
51 OutputOpConversion(TypeConverter &typeConverter, MLIRContext *context,
52 DenseSet<Operation *> *opVisited)
56 matchAndRewrite(hw::OutputOp op, OpAdaptor adaptor,
57 ConversionPatternRewriter &rewriter)
const override {
58 llvm::SmallVector<Value> convOperands;
61 for (
auto operand : adaptor.getOperands()) {
63 auto explodedStruct = rewriter.create<hw::StructExplodeOp>(
65 llvm::copy(explodedStruct.getResults(),
66 std::back_inserter(convOperands));
68 convOperands.push_back(operand);
73 opVisited->insert(op->getParentOp());
74 rewriter.replaceOpWithNewOp<hw::OutputOp>(op, convOperands);
77 DenseSet<Operation *> *opVisited;
81 InstanceOpConversion(TypeConverter &typeConverter, MLIRContext *context,
82 DenseSet<hw::InstanceOp> *convertedOps,
83 const StringSet<> *externModules)
85 externModules(externModules) {}
88 matchAndRewrite(hw::InstanceOp op, OpAdaptor adaptor,
89 ConversionPatternRewriter &rewriter)
const override {
90 auto referencedMod = op.getReferencedModuleNameAttr();
93 if (externModules->contains(referencedMod.getValue()))
96 auto loc = op.getLoc();
98 llvm::SmallVector<Value> convOperands;
99 for (
auto operand : adaptor.getOperands()) {
101 auto explodedStruct = rewriter.create<hw::StructExplodeOp>(
103 llvm::copy(explodedStruct.getResults(),
104 std::back_inserter(convOperands));
106 convOperands.push_back(operand);
111 llvm::SmallVector<Type> newResultTypes;
112 for (
auto oldResultType : op.getResultTypes()) {
114 for (
auto t : structType.getElements())
115 newResultTypes.push_back(t.type);
117 newResultTypes.push_back(oldResultType);
122 auto newInstance = rewriter.create<hw::InstanceOp>(
123 loc, newResultTypes, op.getInstanceNameAttr(),
125 op.getArgNamesAttr(), op.getResultNamesAttr(), op.getParametersAttr(),
126 op.getInnerSymAttr(), op.getDoNotPrintAttr());
129 llvm::SmallVector<Value> convResults;
130 size_t oldResultCntr = 0;
131 for (
size_t resIndex = 0; resIndex < newInstance.getNumResults();
133 Type oldResultType = op.getResultTypes()[oldResultCntr];
135 size_t nElements = structType.getElements().size();
138 newInstance.getResults().slice(resIndex, nElements));
139 convResults.push_back(implodedStruct.getResult());
140 resIndex += nElements - 1;
142 convResults.push_back(newInstance.getResult(resIndex));
146 rewriter.replaceOp(op, convResults);
147 convertedOps->insert(newInstance);
151 DenseSet<hw::InstanceOp> *convertedOps;
152 const StringSet<> *externModules;
155 using IOTypes = std::pair<TypeRange, TypeRange>;
159 DenseMap<unsigned, hw::StructType> argStructs, resStructs;
162 SmallVector<Type> argTypes, resTypes;
165 class FlattenIOTypeConverter :
public TypeConverter {
167 FlattenIOTypeConverter() {
168 addConversion([](Type type, SmallVectorImpl<Type> &results) {
171 results.push_back(type);
173 for (
auto field : structType.getElements())
174 results.push_back(field.type);
179 addTargetMaterialization([](OpBuilder &builder, hw::StructType type,
180 ValueRange inputs, Location loc) {
182 return result.getResult();
185 addTargetMaterialization([](OpBuilder &builder, hw::TypeAliasType type,
186 ValueRange inputs, Location loc) {
188 return result.getResult();
195 template <
typename... TOp>
197 ConversionTarget &target,
199 FlattenIOTypeConverter &typeConverter) {
214 target.addDynamicallyLegalOp<TOp...>([&](hw::HWModuleLike moduleLikeOp) {
219 auto ioInfoIt = ioMap.find(moduleLikeOp);
220 if (ioInfoIt == ioMap.end()) {
225 auto ioInfo = ioInfoIt->second;
227 auto compareTypes = [&](TypeRange oldTypes, TypeRange newTypes) {
228 return llvm::any_of(llvm::zip(oldTypes, newTypes), [&](
auto typePair) {
229 auto oldType = std::get<0>(typePair);
230 auto newType = std::get<1>(typePair);
231 return oldType != newType;
234 auto mtype = moduleLikeOp.getHWModuleType();
235 if (
compareTypes(mtype.getOutputTypes(), ioInfo.resTypes) ||
245 template <
typename T>
247 return llvm::any_of(module.getBody()->getOps<T>(),
248 [](T op) { return !isLegalModLikeOp(op); });
251 template <
typename T>
252 static DenseMap<Operation *, IOTypes>
populateIOMap(mlir::ModuleOp module) {
253 DenseMap<Operation *, IOTypes> ioMap;
254 for (
auto op : module.getOps<T>())
255 ioMap[op] = {op.getArgumentTypes(), op.getResultTypes()};
259 template <
typename ModTy,
typename T>
260 static llvm::SmallVector<Attribute>
262 DenseMap<unsigned, hw::StructType> &structMap, T oldNames,
264 llvm::SmallVector<Attribute> newNames;
265 for (
auto [i, oldName] : llvm::enumerate(oldNames)) {
267 auto it = structMap.find(i);
268 if (it == structMap.end()) {
276 auto structType = it->second;
277 for (
auto field : structType.getElements())
279 op->getContext(), oldName + Twine(joinChar) + field.name.str()));
284 template <
typename ModTy>
289 SmallVector<Attribute> newNames;
290 SmallVector<hw::ModulePort> oldPorts(oldModType.getPorts().begin(),
291 oldModType.getPorts().end());
292 for (
auto oldPort : oldPorts) {
293 auto oldName = oldPort.name;
295 for (
auto field : structType.getElements()) {
298 oldName.getValue() + Twine(joinChar) + field.name.str()));
301 newNames.push_back(oldName);
303 op.setAllPortNames(newNames);
306 static llvm::SmallVector<Location>
308 SmallVectorImpl<Location> &oldLocs) {
309 llvm::SmallVector<Location> newLocs;
310 for (
auto [i, oldLoc] : llvm::enumerate(oldLocs)) {
312 auto it = structMap.find(i);
313 if (it == structMap.end()) {
315 newLocs.push_back(oldLoc);
319 auto structType = it->second;
320 for (
size_t i = 0, e = structType.getElements().size(); i < e; ++i)
321 newLocs.push_back(oldLoc);
331 DenseMap<unsigned, hw::StructType> &structMap) {
332 auto locs = op.getInputLocs();
333 if (locs.empty() || op.getModuleBody().empty())
335 for (
auto [arg, loc] : llvm::zip(op.getBodyBlock()->getArguments(), locs))
339 static void setIOInfo(hw::HWModuleLike op, IOInfo &ioInfo) {
340 ioInfo.argTypes = op.getInputTypes();
341 ioInfo.resTypes = op.getOutputTypes();
342 for (
auto [i, arg] : llvm::enumerate(ioInfo.argTypes)) {
344 ioInfo.argStructs[i] = structType;
346 for (
auto [i, res] : llvm::enumerate(ioInfo.resTypes)) {
348 ioInfo.resStructs[i] = structType;
352 template <
typename T>
354 DenseMap<Operation *, IOInfo> ioInfoMap;
355 for (
auto op : module.getOps<T>()) {
358 ioInfoMap[op] = ioInfo;
363 template <
typename T>
365 StringSet<> &externModules,
367 auto *ctx = module.getContext();
368 FlattenIOTypeConverter typeConverter;
373 while (hasUnconvertedOps<T>(module)) {
374 ConversionTarget target(*ctx);
376 target.addLegalDialect<hw::HWDialect>();
380 auto ioInfoMap = populateIOInfoMap<T>(module);
385 llvm::DenseSet<hw::InstanceOp> convertedInstances;
390 DenseSet<Operation *> opVisited;
391 patterns.add<OutputOpConversion>(typeConverter, ctx, &opVisited);
393 patterns.add<InstanceOpConversion>(typeConverter, ctx, &convertedInstances,
395 target.addDynamicallyLegalOp<hw::OutputOp>(
396 [&](
auto op) {
return opVisited.contains(op->getParentOp()); });
397 target.addDynamicallyLegalOp<hw::InstanceOp>([&](hw::InstanceOp op) {
398 auto refName = op.getReferencedModuleName();
399 return externModules.contains(refName) ||
400 llvm::none_of(op->getOperands(), [](
auto operand) {
401 return isStructType(operand.getType());
405 DenseMap<Operation *, ArrayAttr> oldArgNames, oldResNames;
406 DenseMap<Operation *, SmallVector<Location>> oldArgLocs, oldResLocs;
407 DenseMap<Operation *, hw::ModuleType> oldModTypes;
409 for (
auto op : module.getOps<T>()) {
410 oldModTypes[op] = op.getHWModuleType();
411 oldArgNames[op] =
ArrayAttr::get(module.getContext(), op.getInputNames());
414 oldArgLocs[op] = op.getInputLocs();
415 oldResLocs[op] = op.getOutputLocs();
419 addSignatureConversion<T>(ioInfoMap, target,
patterns, typeConverter);
421 if (failed(applyPartialConversion(module, target, std::move(
patterns))))
425 for (
auto op : module.getOps<T>()) {
426 auto ioInfo = ioInfoMap[op];
430 newArgLocs.append(newResLocs.begin(), newResLocs.end());
431 op.setAllPortLocs(newArgLocs);
436 for (
auto instanceOp : convertedInstances) {
438 cast<hw::HWModuleLike>(SymbolTable::lookupNearestSymbolFrom(
439 instanceOp, instanceOp.getReferencedModuleNameAttr()));
442 if (!ioInfoMap.contains(targetModule)) {
445 ioInfoMap[targetModule] = ioInfo;
446 oldArgNames[targetModule] =
447 ArrayAttr::get(module.getContext(), targetModule.getInputNames());
448 oldResNames[targetModule] =
449 ArrayAttr::get(module.getContext(), targetModule.getOutputNames());
450 oldArgLocs[targetModule] = targetModule.getInputLocs();
451 oldResLocs[targetModule] = targetModule.getOutputLocs();
453 ioInfo = ioInfoMap[targetModule];
456 instanceOp.getContext(),
458 instanceOp,
"argNames", ioInfo.argStructs,
459 oldArgNames[targetModule].template getAsValueRange<StringAttr>(),
462 instanceOp.getContext(),
464 instanceOp,
"resultNames", ioInfo.resStructs,
465 oldResNames[targetModule].template getAsValueRange<StringAttr>(),
480 template <
typename... TOps>
482 StringSet<> &externModules,
char joinChar) {
483 return (failed(flattenOpsOfType<TOps>(module, recursive, externModules,
490 class FlattenIOPass :
public circt::hw::impl::FlattenIOBase<FlattenIOPass> {
492 FlattenIOPass(
bool recursiveFlag,
bool flattenExternFlag,
char join) {
493 recursive = recursiveFlag;
494 flattenExtern = flattenExternFlag;
498 void runOnOperation()
override {
499 ModuleOp module = getOperation();
500 if (!flattenExtern) {
503 externModules.insert(m.getModuleName());
504 if (flattenIO<hw::HWModuleOp, hw::HWModuleGeneratedOp>(
505 module, recursive, externModules, joinChar))
511 hw::HWModuleGeneratedOp>(module, recursive, externModules,
517 StringSet<> externModules;
526 bool flattenExternFlag,
528 return std::make_unique<FlattenIOPass>(recursiveFlag, flattenExternFlag,
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)
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.