Interpreter.cpp 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243
  1. /*
  2. * Copyright (c) 2021, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/TemporaryChange.h>
  8. #include <LibJS/Bytecode/BasicBlock.h>
  9. #include <LibJS/Bytecode/Instruction.h>
  10. #include <LibJS/Bytecode/Interpreter.h>
  11. #include <LibJS/Bytecode/Op.h>
  12. #include <LibJS/Interpreter.h>
  13. #include <LibJS/Runtime/GlobalEnvironment.h>
  14. #include <LibJS/Runtime/GlobalObject.h>
  15. #include <LibJS/Runtime/Realm.h>
  16. namespace JS::Bytecode {
  17. static Interpreter* s_current;
  18. bool g_dump_bytecode = false;
  19. Interpreter* Interpreter::current()
  20. {
  21. return s_current;
  22. }
  23. Interpreter::Interpreter(GlobalObject& global_object, Realm& realm)
  24. : m_vm(global_object.vm())
  25. , m_global_object(global_object)
  26. , m_realm(realm)
  27. {
  28. VERIFY(!s_current);
  29. s_current = this;
  30. }
  31. Interpreter::~Interpreter()
  32. {
  33. VERIFY(s_current == this);
  34. s_current = nullptr;
  35. }
  36. Interpreter::ValueAndFrame Interpreter::run_and_return_frame(Executable const& executable, BasicBlock const* entry_point, RegisterWindow* in_frame)
  37. {
  38. dbgln_if(JS_BYTECODE_DEBUG, "Bytecode::Interpreter will run unit {:p}", &executable);
  39. TemporaryChange restore_executable { m_current_executable, &executable };
  40. VERIFY(m_saved_exception.is_null());
  41. bool pushed_execution_context = false;
  42. ExecutionContext execution_context(vm().heap());
  43. if (vm().execution_context_stack().is_empty() || !vm().running_execution_context().lexical_environment) {
  44. // The "normal" interpreter pushes an execution context without environment so in that case we also want to push one.
  45. execution_context.this_value = &global_object();
  46. static FlyString global_execution_context_name = "(*BC* global execution context)";
  47. execution_context.function_name = global_execution_context_name;
  48. execution_context.lexical_environment = &m_realm.global_environment();
  49. execution_context.variable_environment = &m_realm.global_environment();
  50. execution_context.realm = &m_realm;
  51. execution_context.is_strict_mode = executable.is_strict_mode;
  52. vm().push_execution_context(execution_context);
  53. pushed_execution_context = true;
  54. }
  55. auto block = entry_point ?: &executable.basic_blocks.first();
  56. if (in_frame)
  57. m_register_windows.append(in_frame);
  58. else
  59. m_register_windows.append(make<RegisterWindow>(MarkedVector<Value>(vm().heap()), MarkedVector<Environment*>(vm().heap()), MarkedVector<Environment*>(vm().heap())));
  60. registers().resize(executable.number_of_registers);
  61. registers()[Register::global_object_index] = Value(&global_object());
  62. for (;;) {
  63. Bytecode::InstructionStreamIterator pc(block->instruction_stream());
  64. bool will_jump = false;
  65. bool will_return = false;
  66. while (!pc.at_end()) {
  67. auto& instruction = *pc;
  68. auto ran_or_error = instruction.execute(*this);
  69. if (ran_or_error.is_error()) {
  70. auto exception_value = *ran_or_error.throw_completion().value();
  71. m_saved_exception = make_handle(exception_value);
  72. if (m_unwind_contexts.is_empty())
  73. break;
  74. auto& unwind_context = m_unwind_contexts.last();
  75. if (unwind_context.executable != m_current_executable)
  76. break;
  77. if (unwind_context.handler) {
  78. block = unwind_context.handler;
  79. unwind_context.handler = nullptr;
  80. // If there's no finalizer, there's nowhere for the handler block to unwind to, so the unwind context is no longer needed.
  81. if (!unwind_context.finalizer)
  82. m_unwind_contexts.take_last();
  83. accumulator() = exception_value;
  84. m_saved_exception = {};
  85. will_jump = true;
  86. break;
  87. }
  88. if (unwind_context.finalizer) {
  89. block = unwind_context.finalizer;
  90. m_unwind_contexts.take_last();
  91. will_jump = true;
  92. break;
  93. }
  94. // An unwind context with no handler or finalizer? We have nowhere to jump, and continuing on will make us crash on the next `Call` to a non-native function if there's an exception! So let's crash here instead.
  95. // If you run into this, you probably forgot to remove the current unwind_context somewhere.
  96. VERIFY_NOT_REACHED();
  97. }
  98. if (m_pending_jump.has_value()) {
  99. block = m_pending_jump.release_value();
  100. will_jump = true;
  101. break;
  102. }
  103. if (!m_return_value.is_empty()) {
  104. will_return = true;
  105. break;
  106. }
  107. ++pc;
  108. }
  109. if (will_return)
  110. break;
  111. if (pc.at_end() && !will_jump)
  112. break;
  113. if (!m_saved_exception.is_null())
  114. break;
  115. }
  116. dbgln_if(JS_BYTECODE_DEBUG, "Bytecode::Interpreter did run unit {:p}", &executable);
  117. if constexpr (JS_BYTECODE_DEBUG) {
  118. for (size_t i = 0; i < registers().size(); ++i) {
  119. String value_string;
  120. if (registers()[i].is_empty())
  121. value_string = "(empty)";
  122. else
  123. value_string = registers()[i].to_string_without_side_effects();
  124. dbgln("[{:3}] {}", i, value_string);
  125. }
  126. }
  127. auto frame = m_register_windows.take_last();
  128. auto return_value = m_return_value.value_or(js_undefined());
  129. m_return_value = {};
  130. // NOTE: The return value from a called function is put into $0 in the caller context.
  131. if (!m_register_windows.is_empty())
  132. window().registers[0] = return_value;
  133. // At this point we may have already run any queued promise jobs via on_call_stack_emptied,
  134. // in which case this is a no-op.
  135. vm().run_queued_promise_jobs();
  136. if (pushed_execution_context) {
  137. VERIFY(&vm().running_execution_context() == &execution_context);
  138. vm().pop_execution_context();
  139. }
  140. vm().finish_execution_generation();
  141. if (!m_saved_exception.is_null()) {
  142. Value thrown_value = m_saved_exception.value();
  143. m_saved_exception = {};
  144. if (auto* register_window = frame.get_pointer<NonnullOwnPtr<RegisterWindow>>())
  145. return { throw_completion(thrown_value), move(*register_window) };
  146. return { throw_completion(thrown_value), nullptr };
  147. }
  148. if (auto register_window = frame.get_pointer<NonnullOwnPtr<RegisterWindow>>())
  149. return { return_value, move(*register_window) };
  150. return { return_value, nullptr };
  151. }
  152. void Interpreter::enter_unwind_context(Optional<Label> handler_target, Optional<Label> finalizer_target)
  153. {
  154. m_unwind_contexts.empend(m_current_executable, handler_target.has_value() ? &handler_target->block() : nullptr, finalizer_target.has_value() ? &finalizer_target->block() : nullptr);
  155. }
  156. void Interpreter::leave_unwind_context()
  157. {
  158. m_unwind_contexts.take_last();
  159. }
  160. ThrowCompletionOr<void> Interpreter::continue_pending_unwind(Label const& resume_label)
  161. {
  162. if (!m_saved_exception.is_null()) {
  163. auto result = throw_completion(m_saved_exception.value());
  164. m_saved_exception = {};
  165. return result;
  166. }
  167. jump(resume_label);
  168. return {};
  169. }
  170. VM::InterpreterExecutionScope Interpreter::ast_interpreter_scope()
  171. {
  172. if (!m_ast_interpreter)
  173. m_ast_interpreter = JS::Interpreter::create_with_existing_realm(m_realm);
  174. return { *m_ast_interpreter };
  175. }
  176. AK::Array<OwnPtr<PassManager>, static_cast<UnderlyingType<Interpreter::OptimizationLevel>>(Interpreter::OptimizationLevel::__Count)> Interpreter::s_optimization_pipelines {};
  177. Bytecode::PassManager& Interpreter::optimization_pipeline(Interpreter::OptimizationLevel level)
  178. {
  179. auto underlying_level = to_underlying(level);
  180. VERIFY(underlying_level <= to_underlying(Interpreter::OptimizationLevel::__Count));
  181. auto& entry = s_optimization_pipelines[underlying_level];
  182. if (entry)
  183. return *entry;
  184. auto pm = make<PassManager>();
  185. if (level == OptimizationLevel::Default) {
  186. pm->add<Passes::GenerateCFG>();
  187. pm->add<Passes::UnifySameBlocks>();
  188. pm->add<Passes::GenerateCFG>();
  189. pm->add<Passes::MergeBlocks>();
  190. pm->add<Passes::GenerateCFG>();
  191. pm->add<Passes::UnifySameBlocks>();
  192. pm->add<Passes::GenerateCFG>();
  193. pm->add<Passes::MergeBlocks>();
  194. pm->add<Passes::GenerateCFG>();
  195. pm->add<Passes::PlaceBlocks>();
  196. } else {
  197. VERIFY_NOT_REACHED();
  198. }
  199. auto& passes = *pm;
  200. entry = move(pm);
  201. return passes;
  202. }
  203. }