FuelLabs / sway

🌴 Empowering everyone to build reliable and efficient smart contracts.
https://docs.fuel.network/docs/sway/
Apache License 2.0
62.8k stars 5.35k forks source link

U128 and common inefficient library types cause unreasonable bloat #3112

Open sezna opened 1 year ago

sezna commented 1 year ago

This issue generally tracks the fact that applications that make heavy use of wider integers like https://github.com/sway-libs/amm are taking a long time to compile, have significant bytecode bloat, and are gas inefficient.

We are currently investing in optimizing bytecode size via IR optimization passes. A few more strategic optimization passes will hopefully get us some major benefits, but we can't solely rely on that. A couple of other methods were proposed:

  1. VM instructions for things like quad-add.
  2. Bespoke intrinsics (or VM ops, but more likely intrinsics) for common mathematical operations like (x * y) / z -- this is extremely common in AMMs or other smart contracts that calculate ratios.

In general, we would like adding VM operations to be our last resort, as the VM should remain as minimal as possible. Additionally, it is a bad precedent to simply add opcodes when we have issues generating efficient code.

The consensus was that we can start by adding compiler intrinsics for specific math operations like (x * y) / z and quad add. These can utilize the fact that the result will fit in a u64 while the components (x * y) might not, to generate more efficient code. If after this, plus more optimization passes, we are still unable to generate efficient code, we will revisit the possibility of more VM opcodes.

If this summary is correct, I'll make sub-issues for these intrinsics and tracking bytecode bloat, perhaps in the CI.

cc @FuelLabs/sway-compiler

AlicanC commented 1 year ago

I've basically tried this for raw_ptr::add and such, and seen good bytecode size reductions in Vec tests: https://github.com/FuelLabs/sway/pull/3157