Optimize ternary expressions to branchless code when cheaper.
- Dominant language
- C++
- Stars
- 25.7k
- Forks
- 6.2k
- Avg merge
- 1d 11h
- Merged PRs (30d)
- 21
Description
## Abstract
The ability to cast `bool`s to `uint256` or `uint8`.
## Motivation
Branchless optimizations are becoming more and more common to see lately, but often they require dropping down into inline assembly since their efficiency depends on being able to treat a bool as a uint that resolves to either `1` in the true case or `0` if false. Solidity should support performing these conversions without jumps or branches as bools are already represented this way under the hood. Requiring devs to drop into assembly is presenting them with a bunch of extra footguns to hurt themselves with, adding this ability to the high level language will make Solidity safer for devs and make these optimization techniques more readable.
## Specification
I am not opinionated as to whether bools would have to be cast to `uint8`s or `uint256`s assuming they use the same amount of gas. I will demonstrate both possible options:
```solidity
bool status = false;
assert(uint256(status) == 0);
```
```solidity
bool status = true;
assert(uint8(status) == uint8(1));
```
## Backwards Compatibility
I don't think this would introduce any backwards compatibility issues, but please correct me if so!
Contributor guide
Research direction
The issue names no source file, test, or compiler entry point. Start by locating the existing handling for bool-to-integer conversions and ternary expressions, then verify completion with cases where false becomes 0 and true becomes 1 without introducing branches.
Written by the indexing model from the issue text.
Assessment
- Tech stack
- cpp, solidity
- Domain
- compilers
- Issue type
- Feature
- Difficulty
- 5/5
- Estimated time
- Over a week
- Activity status
- Stale
- Clarity
- Mostly clear
- Newbie friendliness
- 35/100