We implemented a similar concept in our C++ -> JavaScript/WebAssembly compiler (Cheerp) several years ago. It was a nice challenge.
https://labs.leaningtech.com/blog/reducing-webassembly-size-...