Generator.h 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335
  1. /*
  2. * Copyright (c) 2021-2024, 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. VM& vm() { return m_vm; }
  25. enum class SurroundingScopeKind {
  26. Global,
  27. Function,
  28. Block,
  29. };
  30. static CodeGenerationErrorOr<NonnullGCPtr<Executable>> generate(VM&, ASTNode const&, ReadonlySpan<FunctionParameter> parameters, FunctionKind = FunctionKind::Normal);
  31. Register allocate_register();
  32. void set_local_initialized(u32 local_index);
  33. [[nodiscard]] bool is_local_initialized(u32 local_index) const;
  34. class SourceLocationScope {
  35. public:
  36. SourceLocationScope(Generator&, ASTNode const& node);
  37. ~SourceLocationScope();
  38. private:
  39. Generator& m_generator;
  40. ASTNode const* m_previous_node { nullptr };
  41. };
  42. class UnwindContext {
  43. public:
  44. UnwindContext(Generator&, Optional<Label> finalizer);
  45. UnwindContext const* previous() const { return m_previous_context; }
  46. void set_handler(Label handler) { m_handler = handler; }
  47. Optional<Label> handler() const { return m_handler; }
  48. Optional<Label> finalizer() const { return m_finalizer; }
  49. ~UnwindContext();
  50. private:
  51. Generator& m_generator;
  52. Optional<Label> m_finalizer;
  53. Optional<Label> m_handler {};
  54. UnwindContext const* m_previous_context { nullptr };
  55. };
  56. template<typename OpType, typename... Args>
  57. requires(requires { OpType(declval<Args>()...); })
  58. void emit(Args&&... args)
  59. {
  60. VERIFY(!is_current_block_terminated());
  61. size_t slot_offset = m_current_basic_block->size();
  62. grow(sizeof(OpType));
  63. void* slot = m_current_basic_block->data() + slot_offset;
  64. new (slot) OpType(forward<Args>(args)...);
  65. if constexpr (OpType::IsTerminator)
  66. m_current_basic_block->terminate({});
  67. m_current_basic_block->add_source_map_entry(slot_offset, { m_current_ast_node->start_offset(), m_current_ast_node->end_offset() });
  68. }
  69. template<typename OpType, typename ExtraSlotType, typename... Args>
  70. requires(requires { OpType(declval<Args>()...); })
  71. void emit_with_extra_slots(size_t extra_slot_count, Args&&... args)
  72. {
  73. VERIFY(!is_current_block_terminated());
  74. size_t size_to_allocate = round_up_to_power_of_two(sizeof(OpType) + extra_slot_count * sizeof(ExtraSlotType), alignof(void*));
  75. size_t slot_offset = m_current_basic_block->size();
  76. grow(size_to_allocate);
  77. void* slot = m_current_basic_block->data() + slot_offset;
  78. new (slot) OpType(forward<Args>(args)...);
  79. if constexpr (OpType::IsTerminator)
  80. m_current_basic_block->terminate({});
  81. m_current_basic_block->add_source_map_entry(slot_offset, { m_current_ast_node->start_offset(), m_current_ast_node->end_offset() });
  82. }
  83. template<typename OpType, typename... Args>
  84. requires(requires { OpType(declval<Args>()...); })
  85. void emit_with_extra_operand_slots(size_t extra_operand_slots, Args&&... args)
  86. {
  87. emit_with_extra_slots<OpType, Operand>(extra_operand_slots, forward<Args>(args)...);
  88. }
  89. template<typename OpType, typename... Args>
  90. requires(requires { OpType(declval<Args>()...); })
  91. void emit_with_extra_value_slots(size_t extra_operand_slots, Args&&... args)
  92. {
  93. emit_with_extra_slots<OpType, Value>(extra_operand_slots, forward<Args>(args)...);
  94. }
  95. struct ReferenceOperands {
  96. Optional<Operand> base {}; // [[Base]]
  97. Optional<Operand> referenced_name {}; // [[ReferencedName]] as an operand
  98. Optional<IdentifierTableIndex> referenced_identifier {}; // [[ReferencedName]] as an identifier
  99. Optional<IdentifierTableIndex> referenced_private_identifier {}; // [[ReferencedName]] as a private identifier
  100. Optional<Operand> this_value {}; // [[ThisValue]]
  101. Optional<Operand> loaded_value {}; // Loaded value, if we've performed a load.
  102. };
  103. CodeGenerationErrorOr<ReferenceOperands> emit_load_from_reference(JS::ASTNode const&, Optional<Operand> preferred_dst = {});
  104. CodeGenerationErrorOr<void> emit_store_to_reference(JS::ASTNode const&, Operand value);
  105. CodeGenerationErrorOr<void> emit_store_to_reference(ReferenceOperands const&, Operand value);
  106. CodeGenerationErrorOr<Optional<Operand>> emit_delete_reference(JS::ASTNode const&);
  107. CodeGenerationErrorOr<ReferenceOperands> emit_super_reference(MemberExpression const&);
  108. void emit_set_variable(JS::Identifier const& identifier, Operand value, Bytecode::Op::SetVariable::InitializationMode initialization_mode = Bytecode::Op::SetVariable::InitializationMode::Set, Bytecode::Op::EnvironmentMode mode = Bytecode::Op::EnvironmentMode::Lexical);
  109. void push_home_object(Operand);
  110. void pop_home_object();
  111. void emit_new_function(Operand dst, JS::FunctionExpression const&, Optional<IdentifierTableIndex> lhs_name);
  112. CodeGenerationErrorOr<Optional<Operand>> emit_named_evaluation_if_anonymous_function(Expression const&, Optional<IdentifierTableIndex> lhs_name, Optional<Operand> preferred_dst = {});
  113. void begin_continuable_scope(Label continue_target, Vector<DeprecatedFlyString> const& language_label_set);
  114. void end_continuable_scope();
  115. void begin_breakable_scope(Label breakable_target, Vector<DeprecatedFlyString> const& language_label_set);
  116. void end_breakable_scope();
  117. [[nodiscard]] Label nearest_continuable_scope() const;
  118. [[nodiscard]] Label nearest_breakable_scope() const;
  119. void switch_to_basic_block(BasicBlock& block)
  120. {
  121. m_current_basic_block = &block;
  122. }
  123. [[nodiscard]] BasicBlock& current_block() { return *m_current_basic_block; }
  124. BasicBlock& make_block(String name = {})
  125. {
  126. if (name.is_empty())
  127. name = MUST(String::number(m_next_block++));
  128. auto block = BasicBlock::create(m_root_basic_blocks.size(), name);
  129. if (auto const* context = m_current_unwind_context) {
  130. if (context->handler().has_value())
  131. block->set_handler(*m_root_basic_blocks[context->handler().value().basic_block_index()]);
  132. if (m_current_unwind_context->finalizer().has_value())
  133. block->set_finalizer(*m_root_basic_blocks[context->finalizer().value().basic_block_index()]);
  134. }
  135. m_root_basic_blocks.append(move(block));
  136. return *m_root_basic_blocks.last();
  137. }
  138. bool is_current_block_terminated() const
  139. {
  140. return m_current_basic_block->is_terminated();
  141. }
  142. StringTableIndex intern_string(ByteString string)
  143. {
  144. return m_string_table->insert(move(string));
  145. }
  146. RegexTableIndex intern_regex(ParsedRegex regex)
  147. {
  148. return m_regex_table->insert(move(regex));
  149. }
  150. IdentifierTableIndex intern_identifier(DeprecatedFlyString string)
  151. {
  152. return m_identifier_table->insert(move(string));
  153. }
  154. Optional<IdentifierTableIndex> intern_identifier_for_expression(Expression const& expression);
  155. 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; }
  156. bool is_in_generator_function() const { return m_enclosing_function_kind == FunctionKind::Generator || m_enclosing_function_kind == FunctionKind::AsyncGenerator; }
  157. bool is_in_async_function() const { return m_enclosing_function_kind == FunctionKind::Async || m_enclosing_function_kind == FunctionKind::AsyncGenerator; }
  158. bool is_in_async_generator_function() const { return m_enclosing_function_kind == FunctionKind::AsyncGenerator; }
  159. enum class BindingMode {
  160. Lexical,
  161. Var,
  162. Global,
  163. };
  164. struct LexicalScope {
  165. SurroundingScopeKind kind;
  166. };
  167. void block_declaration_instantiation(ScopeNode const&);
  168. void begin_variable_scope();
  169. void end_variable_scope();
  170. enum class BlockBoundaryType {
  171. Break,
  172. Continue,
  173. Unwind,
  174. ReturnToFinally,
  175. LeaveFinally,
  176. LeaveLexicalEnvironment,
  177. };
  178. template<typename OpType>
  179. void perform_needed_unwinds()
  180. requires(OpType::IsTerminator && !IsSame<OpType, Op::Jump>)
  181. {
  182. for (size_t i = m_boundaries.size(); i > 0; --i) {
  183. auto boundary = m_boundaries[i - 1];
  184. using enum BlockBoundaryType;
  185. switch (boundary) {
  186. case Unwind:
  187. if constexpr (IsSame<OpType, Bytecode::Op::Throw>)
  188. return;
  189. emit<Bytecode::Op::LeaveUnwindContext>();
  190. break;
  191. case LeaveLexicalEnvironment:
  192. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  193. break;
  194. case Break:
  195. case Continue:
  196. break;
  197. case ReturnToFinally:
  198. return;
  199. case LeaveFinally:
  200. emit<Bytecode::Op::LeaveFinally>();
  201. break;
  202. };
  203. }
  204. }
  205. bool is_in_finalizer() const { return m_boundaries.contains_slow(BlockBoundaryType::LeaveFinally); }
  206. void generate_break();
  207. void generate_break(DeprecatedFlyString const& break_label);
  208. void generate_continue();
  209. void generate_continue(DeprecatedFlyString const& continue_label);
  210. void start_boundary(BlockBoundaryType type) { m_boundaries.append(type); }
  211. void end_boundary(BlockBoundaryType type)
  212. {
  213. VERIFY(m_boundaries.last() == type);
  214. m_boundaries.take_last();
  215. }
  216. [[nodiscard]] Operand get_this(Optional<Operand> preferred_dst = {});
  217. void emit_get_by_id(Operand dst, Operand base, IdentifierTableIndex property_identifier, Optional<IdentifierTableIndex> base_identifier = {});
  218. void emit_get_by_id_with_this(Operand dst, Operand base, IdentifierTableIndex, Operand this_value);
  219. void emit_iterator_value(Operand dst, Operand result);
  220. void emit_iterator_complete(Operand dst, Operand result);
  221. [[nodiscard]] size_t next_global_variable_cache() { return m_next_global_variable_cache++; }
  222. [[nodiscard]] size_t next_environment_variable_cache() { return m_next_environment_variable_cache++; }
  223. [[nodiscard]] size_t next_property_lookup_cache() { return m_next_property_lookup_cache++; }
  224. enum class DeduplicateConstant {
  225. Yes,
  226. No,
  227. };
  228. [[nodiscard]] Operand add_constant(Value value, DeduplicateConstant deduplicate_constant = DeduplicateConstant::Yes)
  229. {
  230. if (deduplicate_constant == DeduplicateConstant::Yes) {
  231. for (size_t i = 0; i < m_constants.size(); ++i) {
  232. if (m_constants[i] == value)
  233. return Operand(Operand::Type::Constant, i);
  234. }
  235. }
  236. m_constants.append(value);
  237. return Operand(Operand::Type::Constant, m_constants.size() - 1);
  238. }
  239. UnwindContext const* current_unwind_context() const { return m_current_unwind_context; }
  240. private:
  241. VM& m_vm;
  242. enum class JumpType {
  243. Continue,
  244. Break,
  245. };
  246. void generate_scoped_jump(JumpType);
  247. void generate_labelled_jump(JumpType, DeprecatedFlyString const& label);
  248. explicit Generator(VM&);
  249. ~Generator() = default;
  250. void grow(size_t);
  251. struct LabelableScope {
  252. Label bytecode_target;
  253. Vector<DeprecatedFlyString> language_label_set;
  254. };
  255. BasicBlock* m_current_basic_block { nullptr };
  256. ASTNode const* m_current_ast_node { nullptr };
  257. UnwindContext const* m_current_unwind_context { nullptr };
  258. Vector<NonnullOwnPtr<BasicBlock>> m_root_basic_blocks;
  259. NonnullOwnPtr<StringTable> m_string_table;
  260. NonnullOwnPtr<IdentifierTable> m_identifier_table;
  261. NonnullOwnPtr<RegexTable> m_regex_table;
  262. MarkedVector<Value> m_constants;
  263. u32 m_next_register { Register::reserved_register_count };
  264. u32 m_next_block { 1 };
  265. u32 m_next_property_lookup_cache { 0 };
  266. u32 m_next_global_variable_cache { 0 };
  267. u32 m_next_environment_variable_cache { 0 };
  268. FunctionKind m_enclosing_function_kind { FunctionKind::Normal };
  269. Vector<LabelableScope> m_continuable_scopes;
  270. Vector<LabelableScope> m_breakable_scopes;
  271. Vector<BlockBoundaryType> m_boundaries;
  272. Vector<Operand> m_home_objects;
  273. HashTable<u32> m_initialized_locals;
  274. };
  275. }