/* * Copyright (c) 2021, Andreas Kling * * SPDX-License-Identifier: BSD-2-Clause */ #pragma once #include #include #include #include #include #include #include #include namespace JS::Bytecode { struct Executable { NonnullOwnPtrVector basic_blocks; NonnullOwnPtr string_table; size_t number_of_registers { 0 }; String const& get_string(StringTableIndex index) const { return string_table->get(index); } }; class Generator { public: static Executable generate(ASTNode const&); Register allocate_register(); template OpType& emit(Args&&... args) { VERIFY(!is_current_block_terminated()); void* slot = next_slot(); grow(sizeof(OpType)); new (slot) OpType(forward(args)...); if constexpr (OpType::IsTerminator) m_current_basic_block->terminate({}); return *static_cast(slot); } template OpType& emit_with_extra_register_slots(size_t extra_register_slots, Args&&... args) { VERIFY(!is_current_block_terminated()); void* slot = next_slot(); grow(sizeof(OpType) + extra_register_slots * sizeof(Register)); new (slot) OpType(forward(args)...); if constexpr (OpType::IsTerminator) m_current_basic_block->terminate({}); return *static_cast(slot); } void begin_continuable_scope(Label continue_target); void end_continuable_scope(); void begin_breakable_scope(Label breakable_target); void end_breakable_scope(); [[nodiscard]] Label nearest_continuable_scope() const; [[nodiscard]] Label nearest_breakable_scope() const; void switch_to_basic_block(BasicBlock& block) { m_current_basic_block = █ } [[nodiscard]] BasicBlock& current_block() { return *m_current_basic_block; } BasicBlock& make_block(String name = {}) { if (name.is_empty()) name = String::number(m_next_block++); m_root_basic_blocks.append(BasicBlock::create(name)); return m_root_basic_blocks.last(); } bool is_current_block_terminated() const { return m_current_basic_block->is_terminated(); } StringTableIndex intern_string(StringView const& string) { return m_string_table->insert(string); } private: Generator(); ~Generator(); void grow(size_t); void* next_slot(); BasicBlock* m_current_basic_block { nullptr }; NonnullOwnPtrVector m_root_basic_blocks; NonnullOwnPtr m_string_table; u32 m_next_register { 2 }; u32 m_next_block { 1 }; Vector