diff --git a/passes/opt/opt_dff.cc b/passes/opt/opt_dff.cc index 8539432c0..4ed4b0cb6 100644 --- a/passes/opt/opt_dff.cc +++ b/passes/opt/opt_dff.cc @@ -738,7 +738,11 @@ struct OptDffWorker ModWalker modwalker(module->design, module); QuickConeSat qcsat(modwalker); - // Run as a separate sub-pass, so that we don't mutate (non-FF) cells under ModWalker. + // Defer mutating cells by removing them/emiting new flip flops so that + // cell references in modwalker are not invalidated + std::vector cells_to_remove; + std::vector ffs_to_emit; + bool did_something = false; for (auto cell : module->selected_cells()) { if (!RTLIL::builtin_ff_cell_types().count(cell->type)) @@ -830,16 +834,20 @@ struct OptDffWorker if (!removed_sigbits.count(i)) keep_bits.push_back(i); if (keep_bits.empty()) { - module->remove(cell); + cells_to_remove.emplace_back(cell); did_something = true; continue; } ff = ff.slice(keep_bits); ff.cell = cell; - ff.emit(); + ffs_to_emit.emplace_back(ff); did_something = true; } } + for (auto* cell : cells_to_remove) + module->remove(cell); + for (auto& ff : ffs_to_emit) + ff.emit(); return did_something; } }; diff --git a/tests/opt/bug5164.ys b/tests/opt/bug5164.ys new file mode 100644 index 000000000..4ee71fe45 --- /dev/null +++ b/tests/opt/bug5164.ys @@ -0,0 +1,60 @@ +read_rtlil <