LibJS: Make Optional<Operand> use less space

Shrink these down from 12 bytes to 8 bytes, which helps make many
bytecode instructions smaller.
This commit is contained in:
Andreas Kling 2025-03-27 15:11:15 +00:00 committed by Andreas Kling
commit 900f209b34
Notes: github-actions[bot] 2025-03-27 19:51:17 +00:00

View file

@ -14,6 +14,7 @@ namespace JS::Bytecode {
class Operand {
public:
enum class Type {
Invalid,
Register,
Local,
Constant,
@ -46,3 +47,102 @@ private:
};
}
namespace AK {
template<>
class Optional<JS::Bytecode::Operand> : public OptionalBase<JS::Bytecode::Operand> {
template<typename U>
friend class Optional;
public:
using ValueType = JS::Bytecode::Operand;
Optional() = default;
template<SameAs<OptionalNone> V>
Optional(V) { }
Optional(Optional<JS::Bytecode::Operand> const& other)
{
if (other.has_value())
m_value = other.m_value;
}
Optional(Optional&& other)
: m_value(other.m_value)
{
}
template<typename U = JS::Bytecode::Operand>
requires(!IsSame<OptionalNone, RemoveCVReference<U>>)
explicit(!IsConvertible<U&&, JS::Bytecode::Operand>) Optional(U&& value)
requires(!IsSame<RemoveCVReference<U>, Optional<JS::Bytecode::Operand>> && IsConstructible<JS::Bytecode::Operand, U &&>)
: m_value(forward<U>(value))
{
}
template<SameAs<OptionalNone> V>
Optional& operator=(V)
{
clear();
return *this;
}
Optional& operator=(Optional const& other)
{
if (this != &other) {
clear();
m_value = other.m_value;
}
return *this;
}
Optional& operator=(Optional&& other)
{
if (this != &other) {
clear();
m_value = other.m_value;
}
return *this;
}
void clear()
{
m_value = JS::Bytecode::Operand { JS::Bytecode::Operand::Type::Invalid, 0 };
}
[[nodiscard]] bool has_value() const
{
return m_value.type() != JS::Bytecode::Operand::Type::Invalid;
}
[[nodiscard]] JS::Bytecode::Operand& value() &
{
VERIFY(has_value());
return m_value;
}
[[nodiscard]] JS::Bytecode::Operand const& value() const&
{
VERIFY(has_value());
return m_value;
}
[[nodiscard]] JS::Bytecode::Operand value() &&
{
return release_value();
}
[[nodiscard]] JS::Bytecode::Operand release_value()
{
VERIFY(has_value());
JS::Bytecode::Operand released_value = m_value;
clear();
return released_value;
}
private:
JS::Bytecode::Operand m_value { JS::Bytecode::Operand::Type::Invalid, 0 };
};
}