2121USING_YOSYS_NAMESPACE
2222PRIVATE_NAMESPACE_BEGIN
2323
24+ static std::string ff_base_name (const std::string &name)
25+ {
26+ if (!name.empty () && name.back () == ' ]' ) {
27+ size_t open = name.rfind (' [' );
28+ if (open != std::string::npos && open + 1 < name.size () - 1 ) {
29+ std::string inner = name.substr (open + 1 , name.size () - open - 2 );
30+ if (inner.find_first_not_of (" 0123456789" ) == std::string::npos)
31+ return name.substr (0 , open);
32+ }
33+ }
34+ return name;
35+ }
36+
2437struct AnnotateFfWidthPass : public Pass {
2538 AnnotateFfWidthPass () : Pass(" annotate_ff_width" , " annotate every flip-flop with its bit-width" ) { }
2639 void help () override
@@ -40,20 +53,23 @@ struct AnnotateFfWidthPass : public Pass {
4053 break ;
4154 extra_args (args, argidx, design);
4255
43- // Loop through all flip-flops and annotate with their width
56+ // Loop through all flip-flops in a module and annotate with their width
4457 int annotated = 0 ;
4558 for (auto module : design->selected_modules ()) {
59+ // First, count the number of flip-flops of the same base name.
60+ dict<std::string, int > name_counts;
61+ std::vector<std::pair<RTLIL ::Cell *, std::string>> ff_cells;
4662 for (auto cell : module ->selected_cells ()) {
4763 if (!RTLIL::builtin_ff_cell_types ().count (cell->type ))
4864 continue ;
49- int width ;
50- if (cell-> hasParam ( ID :: WIDTH ))
51- width = cell-> getParam ( ID :: WIDTH ). as_int ( );
52- else if (cell-> hasPort ( ID ::Q))
53- width = GetSize (cell-> getPort ( ID ::Q));
54- else
55- width = 1 ;
56- cell ->set_string_attribute (ID (ff_width), std::to_string (width));
65+ std::string base = ff_base_name (cell-> name . str ()) ;
66+ name_counts[base]++;
67+ ff_cells. push_back ({cell, base} );
68+ }
69+ // Then, annotate each flip-flop with the count for its base name.
70+ for ( auto &it : ff_cells) {
71+ int width = name_counts[it. second ] ;
72+ it. first ->set_string_attribute (ID (ff_width), std::to_string (width));
5773 annotated++;
5874 }
5975 }
0 commit comments