Generator.h 2.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #pragma once
  7. #include <AK/NonnullOwnPtrVector.h>
  8. #include <AK/OwnPtr.h>
  9. #include <AK/SinglyLinkedList.h>
  10. #include <LibJS/Bytecode/BasicBlock.h>
  11. #include <LibJS/Bytecode/Label.h>
  12. #include <LibJS/Bytecode/Register.h>
  13. #include <LibJS/Forward.h>
  14. namespace JS::Bytecode {
  15. struct Executable {
  16. NonnullOwnPtrVector<BasicBlock> basic_blocks;
  17. size_t number_of_registers { 0 };
  18. };
  19. class Generator {
  20. public:
  21. static Executable generate(ASTNode const&);
  22. Register allocate_register();
  23. template<typename OpType, typename... Args>
  24. OpType& emit(Args&&... args)
  25. {
  26. VERIFY(!is_current_block_terminated());
  27. void* slot = next_slot();
  28. grow(sizeof(OpType));
  29. new (slot) OpType(forward<Args>(args)...);
  30. if constexpr (OpType::IsTerminator)
  31. m_current_basic_block->terminate({});
  32. return *static_cast<OpType*>(slot);
  33. }
  34. template<typename OpType, typename... Args>
  35. OpType& emit_with_extra_register_slots(size_t extra_register_slots, Args&&... args)
  36. {
  37. VERIFY(!is_current_block_terminated());
  38. void* slot = next_slot();
  39. grow(sizeof(OpType) + extra_register_slots * sizeof(Register));
  40. new (slot) OpType(forward<Args>(args)...);
  41. if constexpr (OpType::IsTerminator)
  42. m_current_basic_block->terminate({});
  43. return *static_cast<OpType*>(slot);
  44. }
  45. void begin_continuable_scope(Label continue_target);
  46. void end_continuable_scope();
  47. [[nodiscard]] Label nearest_continuable_scope() const;
  48. void switch_to_basic_block(BasicBlock& block)
  49. {
  50. m_current_basic_block = &block;
  51. }
  52. BasicBlock& make_block(String name = {})
  53. {
  54. if (name.is_empty())
  55. name = String::number(m_next_block++);
  56. m_root_basic_blocks.append(BasicBlock::create(name));
  57. return m_root_basic_blocks.last();
  58. }
  59. bool is_current_block_terminated() const
  60. {
  61. return m_current_basic_block->is_terminated();
  62. }
  63. private:
  64. Generator();
  65. ~Generator();
  66. void grow(size_t);
  67. void* next_slot();
  68. BasicBlock* m_current_basic_block { nullptr };
  69. NonnullOwnPtrVector<BasicBlock> m_root_basic_blocks;
  70. u32 m_next_register { 1 };
  71. u32 m_next_block { 1 };
  72. Vector<Label> m_continuable_scopes;
  73. };
  74. }