Generator.h 9.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275
  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/OwnPtr.h>
  8. #include <AK/SinglyLinkedList.h>
  9. #include <LibJS/AST.h>
  10. #include <LibJS/Bytecode/BasicBlock.h>
  11. #include <LibJS/Bytecode/CodeGenerationError.h>
  12. #include <LibJS/Bytecode/Executable.h>
  13. #include <LibJS/Bytecode/IdentifierTable.h>
  14. #include <LibJS/Bytecode/Label.h>
  15. #include <LibJS/Bytecode/Op.h>
  16. #include <LibJS/Bytecode/Register.h>
  17. #include <LibJS/Bytecode/StringTable.h>
  18. #include <LibJS/Forward.h>
  19. #include <LibJS/Runtime/FunctionKind.h>
  20. #include <LibRegex/Regex.h>
  21. namespace JS::Bytecode {
  22. class Generator {
  23. public:
  24. enum class SurroundingScopeKind {
  25. Global,
  26. Function,
  27. Block,
  28. };
  29. static CodeGenerationErrorOr<NonnullRefPtr<Executable>> generate(ASTNode const&, FunctionKind = FunctionKind::Normal);
  30. Register allocate_register();
  31. class SourceLocationScope {
  32. public:
  33. SourceLocationScope(Generator&, ASTNode const& node);
  34. ~SourceLocationScope();
  35. private:
  36. Generator& m_generator;
  37. ASTNode const* m_previous_node { nullptr };
  38. };
  39. class UnwindContext {
  40. public:
  41. UnwindContext(Generator&, Optional<Label> finalizer);
  42. UnwindContext const* previous() const { return m_previous_context; }
  43. void set_handler(Label handler) { m_handler = handler; }
  44. Optional<Label> handler() const { return m_handler; }
  45. Optional<Label> finalizer() const { return m_finalizer; }
  46. ~UnwindContext();
  47. private:
  48. Generator& m_generator;
  49. Optional<Label> m_finalizer;
  50. Optional<Label> m_handler {};
  51. UnwindContext const* m_previous_context { nullptr };
  52. };
  53. template<typename OpType, typename... Args>
  54. void emit(Args&&... args)
  55. {
  56. VERIFY(!is_current_block_terminated());
  57. size_t slot_offset = m_current_basic_block->size();
  58. grow(sizeof(OpType));
  59. void* slot = m_current_basic_block->data() + slot_offset;
  60. new (slot) OpType(forward<Args>(args)...);
  61. if constexpr (OpType::IsTerminator)
  62. m_current_basic_block->terminate({});
  63. auto* op = static_cast<OpType*>(slot);
  64. op->set_source_record({ m_current_ast_node->start_offset(), m_current_ast_node->end_offset() });
  65. }
  66. template<typename OpType, typename... Args>
  67. void emit_with_extra_register_slots(size_t extra_register_slots, Args&&... args)
  68. {
  69. VERIFY(!is_current_block_terminated());
  70. size_t size_to_allocate = round_up_to_power_of_two(sizeof(OpType) + extra_register_slots * sizeof(Register), alignof(void*));
  71. size_t slot_offset = m_current_basic_block->size();
  72. grow(size_to_allocate);
  73. void* slot = m_current_basic_block->data() + slot_offset;
  74. new (slot) OpType(forward<Args>(args)...);
  75. if constexpr (OpType::IsTerminator)
  76. m_current_basic_block->terminate({});
  77. auto* op = static_cast<OpType*>(slot);
  78. op->set_source_record({ m_current_ast_node->start_offset(), m_current_ast_node->end_offset() });
  79. }
  80. struct ReferenceRegisters {
  81. Register base; // [[Base]]
  82. Optional<Register> referenced_name; // [[ReferencedName]]
  83. Register this_value; // [[ThisValue]]
  84. };
  85. CodeGenerationErrorOr<Optional<ReferenceRegisters>> emit_load_from_reference(JS::ASTNode const&);
  86. CodeGenerationErrorOr<void> emit_store_to_reference(JS::ASTNode const&);
  87. CodeGenerationErrorOr<void> emit_store_to_reference(ReferenceRegisters const&);
  88. CodeGenerationErrorOr<void> emit_delete_reference(JS::ASTNode const&);
  89. CodeGenerationErrorOr<ReferenceRegisters> emit_super_reference(MemberExpression const&);
  90. void emit_set_variable(JS::Identifier const& identifier, Bytecode::Op::SetVariable::InitializationMode initialization_mode = Bytecode::Op::SetVariable::InitializationMode::Set, Bytecode::Op::EnvironmentMode mode = Bytecode::Op::EnvironmentMode::Lexical);
  91. void push_home_object(Register);
  92. void pop_home_object();
  93. void emit_new_function(JS::FunctionExpression const&, Optional<IdentifierTableIndex> lhs_name);
  94. CodeGenerationErrorOr<void> emit_named_evaluation_if_anonymous_function(Expression const&, Optional<IdentifierTableIndex> lhs_name);
  95. void begin_continuable_scope(Label continue_target, Vector<DeprecatedFlyString> const& language_label_set);
  96. void end_continuable_scope();
  97. void begin_breakable_scope(Label breakable_target, Vector<DeprecatedFlyString> const& language_label_set);
  98. void end_breakable_scope();
  99. [[nodiscard]] Label nearest_continuable_scope() const;
  100. [[nodiscard]] Label nearest_breakable_scope() const;
  101. void switch_to_basic_block(BasicBlock& block)
  102. {
  103. m_current_basic_block = &block;
  104. }
  105. [[nodiscard]] BasicBlock& current_block() { return *m_current_basic_block; }
  106. BasicBlock& make_block(DeprecatedString name = {})
  107. {
  108. if (name.is_empty())
  109. name = DeprecatedString::number(m_next_block++);
  110. auto block = BasicBlock::create(name);
  111. if (auto const* context = m_current_unwind_context) {
  112. if (context->handler().has_value())
  113. block->set_handler(context->handler().value().block());
  114. if (m_current_unwind_context->finalizer().has_value())
  115. block->set_finalizer(context->finalizer().value().block());
  116. }
  117. m_root_basic_blocks.append(move(block));
  118. return *m_root_basic_blocks.last();
  119. }
  120. bool is_current_block_terminated() const
  121. {
  122. return m_current_basic_block->is_terminated();
  123. }
  124. StringTableIndex intern_string(DeprecatedString string)
  125. {
  126. return m_string_table->insert(move(string));
  127. }
  128. RegexTableIndex intern_regex(ParsedRegex regex)
  129. {
  130. return m_regex_table->insert(move(regex));
  131. }
  132. IdentifierTableIndex intern_identifier(DeprecatedFlyString string)
  133. {
  134. return m_identifier_table->insert(move(string));
  135. }
  136. bool is_in_generator_or_async_function() const { return m_enclosing_function_kind == FunctionKind::Async || m_enclosing_function_kind == FunctionKind::Generator || m_enclosing_function_kind == FunctionKind::AsyncGenerator; }
  137. bool is_in_generator_function() const { return m_enclosing_function_kind == FunctionKind::Generator || m_enclosing_function_kind == FunctionKind::AsyncGenerator; }
  138. bool is_in_async_function() const { return m_enclosing_function_kind == FunctionKind::Async || m_enclosing_function_kind == FunctionKind::AsyncGenerator; }
  139. bool is_in_async_generator_function() const { return m_enclosing_function_kind == FunctionKind::AsyncGenerator; }
  140. enum class BindingMode {
  141. Lexical,
  142. Var,
  143. Global,
  144. };
  145. struct LexicalScope {
  146. SurroundingScopeKind kind;
  147. };
  148. void block_declaration_instantiation(ScopeNode const&);
  149. void begin_variable_scope();
  150. void end_variable_scope();
  151. enum class BlockBoundaryType {
  152. Break,
  153. Continue,
  154. Unwind,
  155. ReturnToFinally,
  156. LeaveLexicalEnvironment,
  157. };
  158. template<typename OpType>
  159. void perform_needed_unwinds()
  160. requires(OpType::IsTerminator && !IsSame<OpType, Op::Jump>)
  161. {
  162. for (size_t i = m_boundaries.size(); i > 0; --i) {
  163. auto boundary = m_boundaries[i - 1];
  164. using enum BlockBoundaryType;
  165. switch (boundary) {
  166. case Unwind:
  167. if constexpr (IsSame<OpType, Bytecode::Op::Throw>)
  168. return;
  169. emit<Bytecode::Op::LeaveUnwindContext>();
  170. break;
  171. case LeaveLexicalEnvironment:
  172. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  173. break;
  174. case Break:
  175. case Continue:
  176. break;
  177. case ReturnToFinally:
  178. return;
  179. };
  180. }
  181. }
  182. void generate_break();
  183. void generate_break(DeprecatedFlyString const& break_label);
  184. void generate_continue();
  185. void generate_continue(DeprecatedFlyString const& continue_label);
  186. void start_boundary(BlockBoundaryType type) { m_boundaries.append(type); }
  187. void end_boundary(BlockBoundaryType type)
  188. {
  189. VERIFY(m_boundaries.last() == type);
  190. m_boundaries.take_last();
  191. }
  192. void emit_get_by_id(IdentifierTableIndex);
  193. void emit_get_by_id_with_this(IdentifierTableIndex, Register);
  194. [[nodiscard]] size_t next_global_variable_cache() { return m_next_global_variable_cache++; }
  195. [[nodiscard]] size_t next_environment_variable_cache() { return m_next_environment_variable_cache++; }
  196. private:
  197. enum class JumpType {
  198. Continue,
  199. Break,
  200. };
  201. void generate_scoped_jump(JumpType);
  202. void generate_labelled_jump(JumpType, DeprecatedFlyString const& label);
  203. Generator();
  204. ~Generator() = default;
  205. void grow(size_t);
  206. struct LabelableScope {
  207. Label bytecode_target;
  208. Vector<DeprecatedFlyString> language_label_set;
  209. };
  210. BasicBlock* m_current_basic_block { nullptr };
  211. ASTNode const* m_current_ast_node { nullptr };
  212. UnwindContext const* m_current_unwind_context { nullptr };
  213. Vector<NonnullOwnPtr<BasicBlock>> m_root_basic_blocks;
  214. NonnullOwnPtr<StringTable> m_string_table;
  215. NonnullOwnPtr<IdentifierTable> m_identifier_table;
  216. NonnullOwnPtr<RegexTable> m_regex_table;
  217. u32 m_next_register { Register::reserved_register_count };
  218. u32 m_next_block { 1 };
  219. u32 m_next_property_lookup_cache { 0 };
  220. u32 m_next_global_variable_cache { 0 };
  221. u32 m_next_environment_variable_cache { 0 };
  222. FunctionKind m_enclosing_function_kind { FunctionKind::Normal };
  223. Vector<LabelableScope> m_continuable_scopes;
  224. Vector<LabelableScope> m_breakable_scopes;
  225. Vector<BlockBoundaryType> m_boundaries;
  226. Vector<Register> m_home_objects;
  227. };
  228. }