Interpreter.cpp 18 KB

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