1212#include < atomic>
1313#include < cassert>
1414#include < fmt/format.h>
15- #include < map>
1615#include < memory>
16+ #include < unordered_map>
17+ #include < utility>
18+ #include < vector>
1719
1820#include " ExtractMostFrequentlyUsedGlobals.hpp"
1921#include " support/index.h"
@@ -28,7 +30,7 @@ namespace warpo::passes {
2830
2931namespace {
3032
31- using Counter = std::map <wasm::Name, std::atomic<wasm::Index>>;
33+ using Counter = std::unordered_map <wasm::Name, std::atomic<wasm::Index>>;
3234struct Scanner : public wasm ::WalkerPass<wasm::PostWalker<Scanner>> {
3335 explicit Scanner (Counter &counter) : counter_(counter) {}
3436
@@ -72,17 +74,20 @@ static Counter createCounter(std::vector<std::unique_ptr<wasm::Global>> const &g
7274}
7375
7476static wasm::Name findMostFrequentlyUsed (Counter const &counter) {
75- wasm::Name maxGlobalName ;
76- wasm::Index maxCount = 0 ;
77+ std::vector<std::pair< wasm::Name, wasm::Index>> sorted ;
78+ sorted. reserve (counter. size ()) ;
7779 for (auto const &[name, count] : counter) {
7880 if (support::isDebug (PASS_NAME))
7981 fmt::println (" [" PASS_NAME " ] '{}' used {} times" , name.str , count.load ());
80- if (count.load () >= maxCount) {
81- maxCount = count.load ();
82- maxGlobalName = name;
83- }
82+ sorted.emplace_back (name, count.load ());
8483 }
85- return maxGlobalName;
84+ // Sort by count descending, then by name ascending to break ties deterministically.
85+ std::sort (sorted.begin (), sorted.end (), [](auto const &a, auto const &b) {
86+ if (a.second != b.second )
87+ return a.second > b.second ;
88+ return a.first < b.first ;
89+ });
90+ return sorted.front ().first ;
8691}
8792
8893static void extractGlobal (wasm::Module &m, wasm::Name const name) {
0 commit comments