Interpreter.cpp 17 KB

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