Interpreter.cpp 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479
  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/AST.h>
  9. #include <LibJS/Bytecode/BasicBlock.h>
  10. #include <LibJS/Bytecode/Generator.h>
  11. #include <LibJS/Bytecode/Instruction.h>
  12. #include <LibJS/Bytecode/Interpreter.h>
  13. #include <LibJS/Bytecode/Op.h>
  14. #include <LibJS/Bytecode/PassManager.h>
  15. #include <LibJS/Interpreter.h>
  16. #include <LibJS/Runtime/GlobalEnvironment.h>
  17. #include <LibJS/Runtime/GlobalObject.h>
  18. #include <LibJS/Runtime/Realm.h>
  19. namespace JS::Bytecode {
  20. static bool s_bytecode_interpreter_enabled = false;
  21. bool Interpreter::enabled()
  22. {
  23. return s_bytecode_interpreter_enabled;
  24. }
  25. void Interpreter::set_enabled(bool enabled)
  26. {
  27. s_bytecode_interpreter_enabled = enabled;
  28. }
  29. static bool s_optimizations_enabled = false;
  30. void Interpreter::set_optimizations_enabled(bool enabled)
  31. {
  32. s_optimizations_enabled = enabled;
  33. }
  34. bool g_dump_bytecode = false;
  35. Interpreter::Interpreter(VM& vm)
  36. : m_vm(vm)
  37. {
  38. }
  39. Interpreter::~Interpreter()
  40. {
  41. }
  42. void Interpreter::visit_edges(Cell::Visitor& visitor)
  43. {
  44. if (m_return_value.has_value())
  45. visitor.visit(*m_return_value);
  46. if (m_saved_return_value.has_value())
  47. visitor.visit(*m_saved_return_value);
  48. if (m_saved_exception.has_value())
  49. visitor.visit(*m_saved_exception);
  50. for (auto& window : m_register_windows) {
  51. window.visit([&](auto& value) { value->visit_edges(visitor); });
  52. }
  53. }
  54. // 16.1.6 ScriptEvaluation ( scriptRecord ), https://tc39.es/ecma262/#sec-runtime-semantics-scriptevaluation
  55. ThrowCompletionOr<Value> Interpreter::run(Script& script_record, JS::GCPtr<Environment> lexical_environment_override)
  56. {
  57. auto& vm = this->vm();
  58. // 1. Let globalEnv be scriptRecord.[[Realm]].[[GlobalEnv]].
  59. auto& global_environment = script_record.realm().global_environment();
  60. // 2. Let scriptContext be a new ECMAScript code execution context.
  61. ExecutionContext script_context(vm.heap());
  62. // 3. Set the Function of scriptContext to null.
  63. // NOTE: This was done during execution context construction.
  64. // 4. Set the Realm of scriptContext to scriptRecord.[[Realm]].
  65. script_context.realm = &script_record.realm();
  66. // 5. Set the ScriptOrModule of scriptContext to scriptRecord.
  67. script_context.script_or_module = NonnullGCPtr<Script>(script_record);
  68. // 6. Set the VariableEnvironment of scriptContext to globalEnv.
  69. script_context.variable_environment = &global_environment;
  70. // 7. Set the LexicalEnvironment of scriptContext to globalEnv.
  71. script_context.lexical_environment = &global_environment;
  72. // Non-standard: Override the lexical environment if requested.
  73. if (lexical_environment_override)
  74. script_context.lexical_environment = lexical_environment_override;
  75. // 8. Set the PrivateEnvironment of scriptContext to null.
  76. // NOTE: This isn't in the spec, but we require it.
  77. script_context.is_strict_mode = script_record.parse_node().is_strict_mode();
  78. // FIXME: 9. Suspend the currently running execution context.
  79. // 10. Push scriptContext onto the execution context stack; scriptContext is now the running execution context.
  80. TRY(vm.push_execution_context(script_context, {}));
  81. // 11. Let script be scriptRecord.[[ECMAScriptCode]].
  82. auto& script = script_record.parse_node();
  83. // 12. Let result be Completion(GlobalDeclarationInstantiation(script, globalEnv)).
  84. auto instantiation_result = script.global_declaration_instantiation(vm, global_environment);
  85. Completion result = instantiation_result.is_throw_completion() ? instantiation_result.throw_completion() : normal_completion({});
  86. // 13. If result.[[Type]] is normal, then
  87. if (result.type() == Completion::Type::Normal) {
  88. auto executable_result = JS::Bytecode::Generator::generate(script);
  89. if (executable_result.is_error()) {
  90. if (auto error_string = executable_result.error().to_string(); error_string.is_error())
  91. result = vm.template throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory));
  92. else if (error_string = String::formatted("TODO({})", error_string.value()); error_string.is_error())
  93. result = vm.template throw_completion<JS::InternalError>(vm.error_message(JS::VM::ErrorMessage::OutOfMemory));
  94. else
  95. result = JS::throw_completion(JS::InternalError::create(realm(), error_string.release_value()));
  96. } else {
  97. auto executable = executable_result.release_value();
  98. if (s_optimizations_enabled) {
  99. auto& passes = optimization_pipeline();
  100. passes.perform(*executable);
  101. }
  102. if (g_dump_bytecode)
  103. executable->dump();
  104. // a. Set result to the result of evaluating script.
  105. auto result_or_error = run_and_return_frame(script_record.realm(), *executable, nullptr);
  106. if (result_or_error.value.is_error())
  107. result = result_or_error.value.release_error();
  108. else
  109. result = result_or_error.frame->registers[0];
  110. }
  111. }
  112. // 14. If result.[[Type]] is normal and result.[[Value]] is empty, then
  113. if (result.type() == Completion::Type::Normal && !result.value().has_value()) {
  114. // a. Set result to NormalCompletion(undefined).
  115. result = normal_completion(js_undefined());
  116. }
  117. // FIXME: 15. Suspend scriptContext and remove it from the execution context stack.
  118. vm.pop_execution_context();
  119. // 16. Assert: The execution context stack is not empty.
  120. VERIFY(!vm.execution_context_stack().is_empty());
  121. // FIXME: 17. Resume the context that is now on the top of the execution context stack as the running execution context.
  122. // At this point we may have already run any queued promise jobs via on_call_stack_emptied,
  123. // in which case this is a no-op.
  124. // FIXME: These three should be moved out of Interpreter::run and give the host an option to run these, as it's up to the host when these get run.
  125. // https://tc39.es/ecma262/#sec-jobs for jobs and https://tc39.es/ecma262/#_ref_3508 for ClearKeptObjects
  126. // finish_execution_generation is particularly an issue for LibWeb, as the HTML spec wants to run it specifically after performing a microtask checkpoint.
  127. // The promise and registry cleanup queues don't cause LibWeb an issue, as LibWeb overrides the hooks that push onto these queues.
  128. vm.run_queued_promise_jobs();
  129. vm.run_queued_finalization_registry_cleanup_jobs();
  130. vm.finish_execution_generation();
  131. // 18. Return ? result.
  132. if (result.is_abrupt()) {
  133. VERIFY(result.type() == Completion::Type::Throw);
  134. return result.release_error();
  135. }
  136. VERIFY(result.value().has_value());
  137. return *result.value();
  138. }
  139. ThrowCompletionOr<Value> Interpreter::run(SourceTextModule& module)
  140. {
  141. // FIXME: This is not a entry point as defined in the spec, but is convenient.
  142. // To avoid work we use link_and_eval_module however that can already be
  143. // dangerous if the vm loaded other modules.
  144. auto& vm = this->vm();
  145. TRY(vm.link_and_eval_module(Badge<Bytecode::Interpreter> {}, module));
  146. vm.run_queued_promise_jobs();
  147. vm.run_queued_finalization_registry_cleanup_jobs();
  148. return js_undefined();
  149. }
  150. Interpreter::ValueAndFrame Interpreter::run_and_return_frame(Realm& realm, Executable& executable, BasicBlock const* entry_point, RegisterWindow* in_frame)
  151. {
  152. dbgln_if(JS_BYTECODE_DEBUG, "Bytecode::Interpreter will run unit {:p}", &executable);
  153. TemporaryChange restore_executable { m_current_executable, &executable };
  154. TemporaryChange restore_saved_jump { m_scheduled_jump, static_cast<BasicBlock const*>(nullptr) };
  155. TemporaryChange restore_saved_exception { m_saved_exception, {} };
  156. bool pushed_execution_context = false;
  157. ExecutionContext execution_context(vm().heap());
  158. if (vm().execution_context_stack().is_empty() || !vm().running_execution_context().lexical_environment) {
  159. // The "normal" interpreter pushes an execution context without environment so in that case we also want to push one.
  160. execution_context.this_value = &realm.global_object();
  161. static DeprecatedFlyString global_execution_context_name = "(*BC* global execution context)";
  162. execution_context.function_name = global_execution_context_name;
  163. execution_context.lexical_environment = &realm.global_environment();
  164. execution_context.variable_environment = &realm.global_environment();
  165. execution_context.realm = realm;
  166. execution_context.is_strict_mode = executable.is_strict_mode;
  167. vm().push_execution_context(execution_context);
  168. pushed_execution_context = true;
  169. }
  170. TemporaryChange restore_current_block { m_current_block, entry_point ?: executable.basic_blocks.first() };
  171. if (in_frame)
  172. push_register_window(in_frame, executable.number_of_registers);
  173. else
  174. push_register_window(make<RegisterWindow>(), executable.number_of_registers);
  175. for (;;) {
  176. Bytecode::InstructionStreamIterator pc(m_current_block->instruction_stream());
  177. TemporaryChange temp_change { m_pc, &pc };
  178. // FIXME: This is getting kinda spaghetti-y
  179. bool will_jump = false;
  180. bool will_return = false;
  181. bool will_yield = false;
  182. while (!pc.at_end()) {
  183. auto& instruction = *pc;
  184. auto ran_or_error = instruction.execute(*this);
  185. if (ran_or_error.is_error()) {
  186. auto exception_value = *ran_or_error.throw_completion().value();
  187. m_saved_exception = exception_value;
  188. if (unwind_contexts().is_empty())
  189. break;
  190. auto& unwind_context = unwind_contexts().last();
  191. if (unwind_context.executable != m_current_executable)
  192. break;
  193. if (unwind_context.handler && !unwind_context.handler_called) {
  194. vm().running_execution_context().lexical_environment = unwind_context.lexical_environment;
  195. m_current_block = unwind_context.handler;
  196. unwind_context.handler_called = true;
  197. accumulator() = exception_value;
  198. m_saved_exception = {};
  199. will_jump = true;
  200. break;
  201. }
  202. if (unwind_context.finalizer) {
  203. m_current_block = unwind_context.finalizer;
  204. // If an exception was thrown inside the corresponding `catch` block, we need to rethrow it
  205. // from the `finally` block. But if the exception is from the `try` block, and has already been
  206. // handled by `catch`, we swallow it.
  207. if (!unwind_context.handler_called)
  208. m_saved_exception = {};
  209. will_jump = true;
  210. break;
  211. }
  212. // 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.
  213. // If you run into this, you probably forgot to remove the current unwind_context somewhere.
  214. VERIFY_NOT_REACHED();
  215. }
  216. if (m_pending_jump.has_value()) {
  217. m_current_block = m_pending_jump.release_value();
  218. will_jump = true;
  219. break;
  220. }
  221. if (m_return_value.has_value()) {
  222. will_return = true;
  223. // Note: A `yield` statement will not go through a finally statement,
  224. // hence we need to set a flag to not do so,
  225. // but we generate a Yield Operation in the case of returns in
  226. // generators as well, so we need to check if it will actually
  227. // continue or is a `return` in disguise
  228. will_yield = (instruction.type() == Instruction::Type::Yield && static_cast<Op::Yield const&>(instruction).continuation().has_value()) || instruction.type() == Instruction::Type::Await;
  229. break;
  230. }
  231. ++pc;
  232. }
  233. if (will_jump)
  234. continue;
  235. if (!unwind_contexts().is_empty() && !will_yield) {
  236. auto& unwind_context = unwind_contexts().last();
  237. if (unwind_context.executable == m_current_executable && unwind_context.finalizer) {
  238. m_saved_return_value = m_return_value;
  239. m_return_value = {};
  240. m_current_block = unwind_context.finalizer;
  241. // the unwind_context will be pop'ed when entering the finally block
  242. continue;
  243. }
  244. }
  245. if (pc.at_end())
  246. break;
  247. if (m_saved_exception.has_value())
  248. break;
  249. if (will_return)
  250. break;
  251. }
  252. dbgln_if(JS_BYTECODE_DEBUG, "Bytecode::Interpreter did run unit {:p}", &executable);
  253. if constexpr (JS_BYTECODE_DEBUG) {
  254. for (size_t i = 0; i < registers().size(); ++i) {
  255. String value_string;
  256. if (registers()[i].is_empty())
  257. value_string = MUST("(empty)"_string);
  258. else
  259. value_string = MUST(registers()[i].to_string_without_side_effects());
  260. dbgln("[{:3}] {}", i, value_string);
  261. }
  262. }
  263. auto frame = pop_register_window();
  264. Value return_value = js_undefined();
  265. if (m_return_value.has_value()) {
  266. return_value = m_return_value.release_value();
  267. } else if (m_saved_return_value.has_value() && !m_saved_exception.has_value()) {
  268. return_value = m_saved_return_value.release_value();
  269. }
  270. // NOTE: The return value from a called function is put into $0 in the caller context.
  271. if (!m_register_windows.is_empty())
  272. window().registers[0] = return_value;
  273. // At this point we may have already run any queued promise jobs via on_call_stack_emptied,
  274. // in which case this is a no-op.
  275. vm().run_queued_promise_jobs();
  276. if (pushed_execution_context) {
  277. VERIFY(&vm().running_execution_context() == &execution_context);
  278. vm().pop_execution_context();
  279. }
  280. vm().finish_execution_generation();
  281. if (m_saved_exception.has_value()) {
  282. Value thrown_value = m_saved_exception.value();
  283. m_saved_exception = {};
  284. m_saved_return_value = {};
  285. if (auto* register_window = frame.get_pointer<NonnullOwnPtr<RegisterWindow>>())
  286. return { throw_completion(thrown_value), move(*register_window) };
  287. return { throw_completion(thrown_value), nullptr };
  288. }
  289. if (auto* register_window = frame.get_pointer<NonnullOwnPtr<RegisterWindow>>())
  290. return { return_value, move(*register_window) };
  291. return { return_value, nullptr };
  292. }
  293. void Interpreter::enter_unwind_context(Optional<Label> handler_target, Optional<Label> finalizer_target)
  294. {
  295. unwind_contexts().empend(
  296. m_current_executable,
  297. handler_target.has_value() ? &handler_target->block() : nullptr,
  298. finalizer_target.has_value() ? &finalizer_target->block() : nullptr,
  299. vm().running_execution_context().lexical_environment);
  300. }
  301. void Interpreter::leave_unwind_context()
  302. {
  303. unwind_contexts().take_last();
  304. }
  305. ThrowCompletionOr<void> Interpreter::continue_pending_unwind(Label const& resume_label)
  306. {
  307. if (m_saved_exception.has_value()) {
  308. return throw_completion(m_saved_exception.release_value());
  309. }
  310. if (m_saved_return_value.has_value()) {
  311. do_return(m_saved_return_value.release_value());
  312. return {};
  313. }
  314. if (m_scheduled_jump) {
  315. // FIXME: If we `break` or `continue` in the finally, we need to clear
  316. // this field
  317. jump(Label { *m_scheduled_jump });
  318. m_scheduled_jump = nullptr;
  319. } else {
  320. jump(resume_label);
  321. }
  322. return {};
  323. }
  324. VM::InterpreterExecutionScope Interpreter::ast_interpreter_scope(Realm& realm)
  325. {
  326. if (!m_ast_interpreter)
  327. m_ast_interpreter = JS::Interpreter::create_with_existing_realm(realm);
  328. return { *m_ast_interpreter };
  329. }
  330. Bytecode::PassManager& Interpreter::optimization_pipeline()
  331. {
  332. static auto s_optimization_pipeline = [] {
  333. auto pm = make<Bytecode::PassManager>();
  334. pm->add<Passes::GenerateCFG>();
  335. pm->add<Passes::UnifySameBlocks>();
  336. pm->add<Passes::GenerateCFG>();
  337. pm->add<Passes::MergeBlocks>();
  338. pm->add<Passes::GenerateCFG>();
  339. pm->add<Passes::UnifySameBlocks>();
  340. pm->add<Passes::GenerateCFG>();
  341. pm->add<Passes::MergeBlocks>();
  342. pm->add<Passes::GenerateCFG>();
  343. pm->add<Passes::PlaceBlocks>();
  344. pm->add<Passes::EliminateLoads>();
  345. return pm;
  346. }();
  347. return *s_optimization_pipeline;
  348. }
  349. size_t Interpreter::pc() const
  350. {
  351. return m_pc ? m_pc->offset() : 0;
  352. }
  353. DeprecatedString Interpreter::debug_position() const
  354. {
  355. return DeprecatedString::formatted("{}:{:2}:{:4x}", m_current_executable->name, m_current_block->name(), pc());
  356. }
  357. ThrowCompletionOr<NonnullOwnPtr<Bytecode::Executable>> compile(VM& vm, ASTNode const& node, FunctionKind kind, DeprecatedFlyString const& name)
  358. {
  359. auto executable_result = Bytecode::Generator::generate(node, kind);
  360. if (executable_result.is_error())
  361. return vm.throw_completion<InternalError>(ErrorType::NotImplemented, TRY_OR_THROW_OOM(vm, executable_result.error().to_string()));
  362. auto bytecode_executable = executable_result.release_value();
  363. bytecode_executable->name = name;
  364. if (s_optimizations_enabled) {
  365. auto& passes = Bytecode::Interpreter::optimization_pipeline();
  366. passes.perform(*bytecode_executable);
  367. if constexpr (JS_BYTECODE_DEBUG) {
  368. dbgln("Optimisation passes took {}us", passes.elapsed());
  369. dbgln("Compiled Bytecode::Block for function '{}':", name);
  370. }
  371. }
  372. if (Bytecode::g_dump_bytecode)
  373. bytecode_executable->dump();
  374. return bytecode_executable;
  375. }
  376. Realm& Interpreter::realm()
  377. {
  378. return *m_vm.current_realm();
  379. }
  380. void Interpreter::push_register_window(Variant<NonnullOwnPtr<RegisterWindow>, RegisterWindow*> window, size_t register_count)
  381. {
  382. m_register_windows.append(move(window));
  383. this->window().registers.resize(register_count);
  384. m_current_register_window = this->window().registers;
  385. }
  386. Variant<NonnullOwnPtr<RegisterWindow>, RegisterWindow*> Interpreter::pop_register_window()
  387. {
  388. auto window = m_register_windows.take_last();
  389. m_current_register_window = m_register_windows.is_empty() ? Span<Value> {} : this->window().registers;
  390. return window;
  391. }
  392. }