grain-lang / grain

The Grain compiler toolchain and CLI. Home of the modern web staple. 🌾
https://grain-lang.org/
GNU Lesser General Public License v3.0
3.28k stars 113 forks source link

Compiler: make optimizations on consumers of runtime modules more robust #1990

Open alex-snezhko opened 9 months ago

alex-snezhko commented 9 months ago

There is some logic in the compiler that will make special optimizations to code based on if it consumes from certain files in the runtime (analyze_inline_wasm.re looking for runtime/unsafe/memory.gr for example). However if relative paths are used e.g. include "./memory.gr" from another file in runtime/unsafe this optimization wouldn't be picked up.

spotandjake commented 9 months ago

There is some logic in the compiler that will make special optimizations to code based on if it consumes from certain files in the runtime (analyze_inline_wasm.re looking for runtime/unsafe/memory.gr for example). However if relative paths are used e.g. include "./memory.gr" from another file in runtime/unsafe this optimization wouldn't be picked up.

Thoughts on adding some sort of macro if directive like c has so we could put these polyfills directly in the code and choose the implementation based on a compiler-provided constant such as primitive bulkMemory = "@wasm.bulk_memory?

As an alternative idea what if we added an @primitive("@wasm.memory_fill") flag above the definition which could tell the compiler that this is a polyfill for the case where the primtiive is not available, this allows the file to define the polyfill itself making it more robust. In the compiler this is just a case of setting the defintion to the primitive over the original value if we find this flag.