Generator.cpp 48 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135
  1. /*
  2. * Copyright (c) 2021-2024, Andreas Kling <kling@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/QuickSort.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/Op.h>
  13. #include <LibJS/Bytecode/Register.h>
  14. #include <LibJS/Runtime/ECMAScriptFunctionObject.h>
  15. #include <LibJS/Runtime/VM.h>
  16. namespace JS::Bytecode {
  17. Generator::Generator(VM& vm, MustPropagateCompletion must_propagate_completion)
  18. : m_vm(vm)
  19. , m_string_table(make<StringTable>())
  20. , m_identifier_table(make<IdentifierTable>())
  21. , m_regex_table(make<RegexTable>())
  22. , m_constants(vm.heap())
  23. , m_accumulator(*this, Operand(Register::accumulator()))
  24. , m_must_propagate_completion(must_propagate_completion == MustPropagateCompletion::Yes)
  25. {
  26. }
  27. CodeGenerationErrorOr<void> Generator::emit_function_declaration_instantiation(ECMAScriptFunctionObject const& function)
  28. {
  29. if (function.m_has_parameter_expressions) {
  30. emit<Op::CreateLexicalEnvironment>();
  31. }
  32. for (auto const& parameter_name : function.m_parameter_names) {
  33. if (parameter_name.value == ECMAScriptFunctionObject::ParameterIsLocal::No) {
  34. auto id = intern_identifier(parameter_name.key);
  35. emit<Op::CreateVariable>(id, Op::EnvironmentMode::Lexical, false);
  36. if (function.m_has_duplicates) {
  37. emit<Op::InitializeLexicalBinding>(id, add_constant(js_undefined()));
  38. }
  39. }
  40. }
  41. if (function.m_arguments_object_needed) {
  42. if (function.m_strict || !function.has_simple_parameter_list()) {
  43. emit<Op::CreateArguments>(Op::CreateArguments::Kind::Unmapped, function.m_strict);
  44. } else {
  45. emit<Op::CreateArguments>(Op::CreateArguments::Kind::Mapped, function.m_strict);
  46. }
  47. }
  48. auto const& formal_parameters = function.formal_parameters();
  49. for (u32 param_index = 0; param_index < formal_parameters.size(); ++param_index) {
  50. auto const& parameter = formal_parameters[param_index];
  51. if (parameter.is_rest) {
  52. auto argument_reg = allocate_register();
  53. emit<Op::CreateRestParams>(argument_reg.operand(), param_index);
  54. emit<Op::SetArgument>(param_index, argument_reg.operand());
  55. } else if (parameter.default_value) {
  56. auto& if_undefined_block = make_block();
  57. auto& if_not_undefined_block = make_block();
  58. auto argument_reg = allocate_register();
  59. emit<Op::GetArgument>(argument_reg.operand(), param_index);
  60. emit<Op::JumpUndefined>(
  61. argument_reg.operand(),
  62. Label { if_undefined_block },
  63. Label { if_not_undefined_block });
  64. switch_to_basic_block(if_undefined_block);
  65. auto operand = TRY(parameter.default_value->generate_bytecode(*this));
  66. emit<Op::SetArgument>(param_index, *operand);
  67. emit<Op::Jump>(Label { if_not_undefined_block });
  68. switch_to_basic_block(if_not_undefined_block);
  69. }
  70. if (auto const* identifier = parameter.binding.get_pointer<NonnullRefPtr<Identifier const>>(); identifier) {
  71. if ((*identifier)->is_local()) {
  72. auto local_variable_index = (*identifier)->local_variable_index();
  73. emit<Op::GetArgument>(local(local_variable_index), param_index);
  74. set_local_initialized((*identifier)->local_variable_index());
  75. } else {
  76. auto id = intern_identifier((*identifier)->string());
  77. auto argument_reg = allocate_register();
  78. emit<Op::GetArgument>(argument_reg.operand(), param_index);
  79. if (function.m_has_duplicates) {
  80. emit<Op::SetLexicalBinding>(id, argument_reg.operand());
  81. } else {
  82. emit<Op::InitializeLexicalBinding>(id, argument_reg.operand());
  83. }
  84. }
  85. } else if (auto const* binding_pattern = parameter.binding.get_pointer<NonnullRefPtr<BindingPattern const>>(); binding_pattern) {
  86. auto input_operand = allocate_register();
  87. emit<Op::GetArgument>(input_operand.operand(), param_index);
  88. auto init_mode = function.m_has_duplicates ? Op::BindingInitializationMode::Set : Bytecode::Op::BindingInitializationMode::Initialize;
  89. TRY((*binding_pattern)->generate_bytecode(*this, init_mode, input_operand, false));
  90. }
  91. }
  92. ScopeNode const* scope_body = nullptr;
  93. if (is<ScopeNode>(*function.m_ecmascript_code))
  94. scope_body = static_cast<ScopeNode const*>(function.m_ecmascript_code.ptr());
  95. if (!function.m_has_parameter_expressions) {
  96. if (scope_body) {
  97. for (auto const& variable_to_initialize : function.m_var_names_to_initialize_binding) {
  98. auto const& id = variable_to_initialize.identifier;
  99. if (id.is_local()) {
  100. emit<Op::Mov>(local(id.local_variable_index()), add_constant(js_undefined()));
  101. } else {
  102. auto intern_id = intern_identifier(id.string());
  103. emit<Op::CreateVariable>(intern_id, Op::EnvironmentMode::Var, false);
  104. emit<Op::InitializeVariableBinding>(intern_id, add_constant(js_undefined()));
  105. }
  106. }
  107. }
  108. } else {
  109. emit<Op::CreateVariableEnvironment>(function.m_var_environment_bindings_count);
  110. if (scope_body) {
  111. for (auto const& variable_to_initialize : function.m_var_names_to_initialize_binding) {
  112. auto const& id = variable_to_initialize.identifier;
  113. auto initial_value = allocate_register();
  114. if (!variable_to_initialize.parameter_binding || variable_to_initialize.function_name) {
  115. emit<Op::Mov>(initial_value, add_constant(js_undefined()));
  116. } else {
  117. if (id.is_local()) {
  118. emit<Op::Mov>(initial_value, local(id.local_variable_index()));
  119. } else {
  120. emit<Op::GetVariable>(initial_value, intern_identifier(id.string()));
  121. }
  122. }
  123. if (id.is_local()) {
  124. emit<Op::Mov>(local(id.local_variable_index()), initial_value);
  125. } else {
  126. auto intern_id = intern_identifier(id.string());
  127. emit<Op::CreateVariable>(intern_id, Op::EnvironmentMode::Var, false);
  128. emit<Op::InitializeVariableBinding>(intern_id, initial_value);
  129. }
  130. }
  131. }
  132. }
  133. if (!function.m_strict && scope_body) {
  134. for (auto const& function_name : function.m_function_names_to_initialize_binding) {
  135. auto intern_id = intern_identifier(function_name);
  136. emit<Op::CreateVariable>(intern_id, Op::EnvironmentMode::Var, false);
  137. emit<Op::InitializeVariableBinding>(intern_id, add_constant(js_undefined()));
  138. }
  139. }
  140. if (!function.m_strict) {
  141. bool can_elide_declarative_environment = !function.m_contains_direct_call_to_eval && (!scope_body || !scope_body->has_non_local_lexical_declarations());
  142. if (!can_elide_declarative_environment) {
  143. emit<Op::CreateLexicalEnvironment>(function.m_lex_environment_bindings_count);
  144. }
  145. }
  146. if (scope_body) {
  147. MUST(scope_body->for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  148. MUST(declaration.for_each_bound_identifier([&](auto const& id) {
  149. if (id.is_local()) {
  150. return;
  151. }
  152. emit<Op::CreateVariable>(intern_identifier(id.string()),
  153. Op::EnvironmentMode::Lexical,
  154. declaration.is_constant_declaration(),
  155. false,
  156. declaration.is_constant_declaration());
  157. }));
  158. }));
  159. }
  160. for (auto const& declaration : function.m_functions_to_initialize) {
  161. auto function = allocate_register();
  162. emit<Op::NewFunction>(function, declaration, OptionalNone {});
  163. if (declaration.name_identifier()->is_local()) {
  164. emit<Op::Mov>(local(declaration.name_identifier()->local_variable_index()), function);
  165. } else {
  166. emit<Op::SetVariableBinding>(intern_identifier(declaration.name()), function);
  167. }
  168. }
  169. return {};
  170. }
  171. CodeGenerationErrorOr<NonnullGCPtr<Executable>> Generator::emit_function_body_bytecode(VM& vm, ASTNode const& node, FunctionKind enclosing_function_kind, GCPtr<ECMAScriptFunctionObject const> function, MustPropagateCompletion must_propagate_completion)
  172. {
  173. Generator generator(vm, must_propagate_completion);
  174. generator.switch_to_basic_block(generator.make_block());
  175. SourceLocationScope scope(generator, node);
  176. generator.m_enclosing_function_kind = enclosing_function_kind;
  177. if (generator.is_in_async_function() && !generator.is_in_generator_function()) {
  178. // Immediately yield with no value.
  179. auto& start_block = generator.make_block();
  180. generator.emit<Bytecode::Op::Yield>(Label { start_block }, generator.add_constant(js_undefined()));
  181. generator.switch_to_basic_block(start_block);
  182. // NOTE: This doesn't have to handle received throw/return completions, as GeneratorObject::resume_abrupt
  183. // will not enter the generator from the SuspendedStart state and immediately completes the generator.
  184. }
  185. if (function)
  186. TRY(generator.emit_function_declaration_instantiation(*function));
  187. if (generator.is_in_generator_function()) {
  188. // Immediately yield with no value.
  189. auto& start_block = generator.make_block();
  190. generator.emit<Bytecode::Op::Yield>(Label { start_block }, generator.add_constant(js_undefined()));
  191. generator.switch_to_basic_block(start_block);
  192. // NOTE: This doesn't have to handle received throw/return completions, as GeneratorObject::resume_abrupt
  193. // will not enter the generator from the SuspendedStart state and immediately completes the generator.
  194. }
  195. auto last_value = TRY(node.generate_bytecode(generator));
  196. if (!generator.current_block().is_terminated() && last_value.has_value()) {
  197. generator.emit<Bytecode::Op::End>(last_value.value());
  198. }
  199. if (generator.is_in_generator_or_async_function()) {
  200. // Terminate all unterminated blocks with yield return
  201. for (auto& block : generator.m_root_basic_blocks) {
  202. if (block->is_terminated())
  203. continue;
  204. generator.switch_to_basic_block(*block);
  205. generator.emit<Bytecode::Op::Yield>(nullptr, generator.add_constant(js_undefined()));
  206. }
  207. }
  208. bool is_strict_mode = false;
  209. if (is<Program>(node))
  210. is_strict_mode = static_cast<Program const&>(node).is_strict_mode();
  211. else if (is<FunctionBody>(node))
  212. is_strict_mode = static_cast<FunctionBody const&>(node).in_strict_mode();
  213. else if (is<FunctionDeclaration>(node))
  214. is_strict_mode = static_cast<FunctionDeclaration const&>(node).is_strict_mode();
  215. size_t size_needed = 0;
  216. for (auto& block : generator.m_root_basic_blocks) {
  217. size_needed += block->size();
  218. }
  219. Vector<u8> bytecode;
  220. bytecode.ensure_capacity(size_needed);
  221. Vector<size_t> basic_block_start_offsets;
  222. basic_block_start_offsets.ensure_capacity(generator.m_root_basic_blocks.size());
  223. HashMap<BasicBlock const*, size_t> block_offsets;
  224. Vector<size_t> label_offsets;
  225. struct UnlinkedExceptionHandlers {
  226. size_t start_offset;
  227. size_t end_offset;
  228. BasicBlock const* handler;
  229. BasicBlock const* finalizer;
  230. };
  231. Vector<UnlinkedExceptionHandlers> unlinked_exception_handlers;
  232. HashMap<size_t, SourceRecord> source_map;
  233. for (auto& block : generator.m_root_basic_blocks) {
  234. if (!block->is_terminated()) {
  235. // NOTE: We must ensure that the "undefined" constant, which will be used by the not yet
  236. // emitted End instruction, is taken into account while shifting local operands by the
  237. // number of constants.
  238. (void)generator.add_constant(js_undefined());
  239. break;
  240. }
  241. }
  242. auto number_of_registers = generator.m_next_register;
  243. auto number_of_constants = generator.m_constants.size();
  244. for (auto& block : generator.m_root_basic_blocks) {
  245. basic_block_start_offsets.append(bytecode.size());
  246. if (block->handler() || block->finalizer()) {
  247. unlinked_exception_handlers.append({
  248. .start_offset = bytecode.size(),
  249. .end_offset = 0,
  250. .handler = block->handler(),
  251. .finalizer = block->finalizer(),
  252. });
  253. }
  254. block_offsets.set(block.ptr(), bytecode.size());
  255. for (auto& [offset, source_record] : block->source_map()) {
  256. source_map.set(bytecode.size() + offset, source_record);
  257. }
  258. Bytecode::InstructionStreamIterator it(block->instruction_stream());
  259. while (!it.at_end()) {
  260. auto& instruction = const_cast<Instruction&>(*it);
  261. instruction.visit_operands([number_of_registers, number_of_constants](Operand& operand) {
  262. switch (operand.type()) {
  263. case Operand::Type::Register:
  264. break;
  265. case Operand::Type::Local:
  266. operand.offset_index_by(number_of_registers + number_of_constants);
  267. break;
  268. case Operand::Type::Constant:
  269. operand.offset_index_by(number_of_registers);
  270. break;
  271. default:
  272. VERIFY_NOT_REACHED();
  273. }
  274. });
  275. // OPTIMIZATION: Don't emit jumps that just jump to the next block.
  276. if (instruction.type() == Instruction::Type::Jump) {
  277. auto& jump = static_cast<Bytecode::Op::Jump&>(instruction);
  278. if (jump.target().basic_block_index() == block->index() + 1) {
  279. if (basic_block_start_offsets.last() == bytecode.size()) {
  280. // This block is empty, just skip it.
  281. basic_block_start_offsets.take_last();
  282. }
  283. ++it;
  284. continue;
  285. }
  286. }
  287. // OPTIMIZATION: For `JumpIf` where one of the targets is the very next block,
  288. // we can emit a `JumpTrue` or `JumpFalse` (to the other block) instead.
  289. if (instruction.type() == Instruction::Type::JumpIf) {
  290. auto& jump = static_cast<Bytecode::Op::JumpIf&>(instruction);
  291. if (jump.true_target().basic_block_index() == block->index() + 1) {
  292. Op::JumpFalse jump_false(jump.condition(), Label { jump.false_target() });
  293. auto& label = jump_false.target();
  294. size_t label_offset = bytecode.size() + (bit_cast<FlatPtr>(&label) - bit_cast<FlatPtr>(&jump_false));
  295. label_offsets.append(label_offset);
  296. bytecode.append(reinterpret_cast<u8 const*>(&jump_false), jump_false.length());
  297. ++it;
  298. continue;
  299. }
  300. if (jump.false_target().basic_block_index() == block->index() + 1) {
  301. Op::JumpTrue jump_true(jump.condition(), Label { jump.true_target() });
  302. auto& label = jump_true.target();
  303. size_t label_offset = bytecode.size() + (bit_cast<FlatPtr>(&label) - bit_cast<FlatPtr>(&jump_true));
  304. label_offsets.append(label_offset);
  305. bytecode.append(reinterpret_cast<u8 const*>(&jump_true), jump_true.length());
  306. ++it;
  307. continue;
  308. }
  309. }
  310. instruction.visit_labels([&](Label& label) {
  311. size_t label_offset = bytecode.size() + (bit_cast<FlatPtr>(&label) - bit_cast<FlatPtr>(&instruction));
  312. label_offsets.append(label_offset);
  313. });
  314. bytecode.append(reinterpret_cast<u8 const*>(&instruction), instruction.length());
  315. ++it;
  316. }
  317. if (!block->is_terminated()) {
  318. Op::End end(generator.add_constant(js_undefined()));
  319. end.visit_operands([number_of_registers, number_of_constants](Operand& operand) {
  320. switch (operand.type()) {
  321. case Operand::Type::Register:
  322. break;
  323. case Operand::Type::Local:
  324. operand.offset_index_by(number_of_registers + number_of_constants);
  325. break;
  326. case Operand::Type::Constant:
  327. operand.offset_index_by(number_of_registers);
  328. break;
  329. default:
  330. VERIFY_NOT_REACHED();
  331. }
  332. });
  333. bytecode.append(reinterpret_cast<u8 const*>(&end), end.length());
  334. }
  335. if (block->handler() || block->finalizer()) {
  336. unlinked_exception_handlers.last().end_offset = bytecode.size();
  337. }
  338. }
  339. for (auto label_offset : label_offsets) {
  340. auto& label = *reinterpret_cast<Label*>(bytecode.data() + label_offset);
  341. auto* block = generator.m_root_basic_blocks[label.basic_block_index()].ptr();
  342. label.set_address(block_offsets.get(block).value());
  343. }
  344. auto executable = vm.heap().allocate_without_realm<Executable>(
  345. move(bytecode),
  346. move(generator.m_identifier_table),
  347. move(generator.m_string_table),
  348. move(generator.m_regex_table),
  349. move(generator.m_constants),
  350. node.source_code(),
  351. generator.m_next_property_lookup_cache,
  352. generator.m_next_global_variable_cache,
  353. generator.m_next_register,
  354. is_strict_mode);
  355. Vector<Executable::ExceptionHandlers> linked_exception_handlers;
  356. for (auto& unlinked_handler : unlinked_exception_handlers) {
  357. auto start_offset = unlinked_handler.start_offset;
  358. auto end_offset = unlinked_handler.end_offset;
  359. auto handler_offset = unlinked_handler.handler ? block_offsets.get(unlinked_handler.handler).value() : Optional<size_t> {};
  360. auto finalizer_offset = unlinked_handler.finalizer ? block_offsets.get(unlinked_handler.finalizer).value() : Optional<size_t> {};
  361. linked_exception_handlers.append({ start_offset, end_offset, handler_offset, finalizer_offset });
  362. }
  363. quick_sort(linked_exception_handlers, [](auto const& a, auto const& b) {
  364. return a.start_offset < b.start_offset;
  365. });
  366. executable->exception_handlers = move(linked_exception_handlers);
  367. executable->basic_block_start_offsets = move(basic_block_start_offsets);
  368. executable->source_map = move(source_map);
  369. generator.m_finished = true;
  370. return executable;
  371. }
  372. CodeGenerationErrorOr<NonnullGCPtr<Executable>> Generator::generate_from_ast_node(VM& vm, ASTNode const& node, FunctionKind enclosing_function_kind)
  373. {
  374. return emit_function_body_bytecode(vm, node, enclosing_function_kind, {});
  375. }
  376. CodeGenerationErrorOr<NonnullGCPtr<Executable>> Generator::generate_from_function(VM& vm, ECMAScriptFunctionObject const& function)
  377. {
  378. return emit_function_body_bytecode(vm, function.ecmascript_code(), function.kind(), &function, MustPropagateCompletion::No);
  379. }
  380. void Generator::grow(size_t additional_size)
  381. {
  382. VERIFY(m_current_basic_block);
  383. m_current_basic_block->grow(additional_size);
  384. }
  385. ScopedOperand Generator::allocate_register()
  386. {
  387. if (!m_free_registers.is_empty()) {
  388. return ScopedOperand { *this, Operand { m_free_registers.take_last() } };
  389. }
  390. VERIFY(m_next_register != NumericLimits<u32>::max());
  391. return ScopedOperand { *this, Operand { Register { m_next_register++ } } };
  392. }
  393. void Generator::free_register(Register reg)
  394. {
  395. m_free_registers.append(reg);
  396. }
  397. ScopedOperand Generator::local(u32 local_index)
  398. {
  399. return ScopedOperand { *this, Operand { Operand::Type::Local, static_cast<u32>(local_index) } };
  400. }
  401. Generator::SourceLocationScope::SourceLocationScope(Generator& generator, ASTNode const& node)
  402. : m_generator(generator)
  403. , m_previous_node(m_generator.m_current_ast_node)
  404. {
  405. m_generator.m_current_ast_node = &node;
  406. }
  407. Generator::SourceLocationScope::~SourceLocationScope()
  408. {
  409. m_generator.m_current_ast_node = m_previous_node;
  410. }
  411. Generator::UnwindContext::UnwindContext(Generator& generator, Optional<Label> finalizer)
  412. : m_generator(generator)
  413. , m_finalizer(finalizer)
  414. , m_previous_context(m_generator.m_current_unwind_context)
  415. {
  416. m_generator.m_current_unwind_context = this;
  417. }
  418. Generator::UnwindContext::~UnwindContext()
  419. {
  420. VERIFY(m_generator.m_current_unwind_context == this);
  421. m_generator.m_current_unwind_context = m_previous_context;
  422. }
  423. Label Generator::nearest_continuable_scope() const
  424. {
  425. return m_continuable_scopes.last().bytecode_target;
  426. }
  427. bool Generator::emit_block_declaration_instantiation(ScopeNode const& scope_node)
  428. {
  429. bool needs_block_declaration_instantiation = false;
  430. MUST(scope_node.for_each_lexically_scoped_declaration([&](Declaration const& declaration) {
  431. if (declaration.is_function_declaration()) {
  432. needs_block_declaration_instantiation = true;
  433. return;
  434. }
  435. MUST(declaration.for_each_bound_identifier([&](auto const& id) {
  436. if (!id.is_local())
  437. needs_block_declaration_instantiation = true;
  438. }));
  439. }));
  440. if (!needs_block_declaration_instantiation)
  441. return false;
  442. // FIXME: Generate the actual bytecode for block declaration instantiation
  443. // and get rid of the BlockDeclarationInstantiation instruction.
  444. start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
  445. emit<Bytecode::Op::BlockDeclarationInstantiation>(scope_node);
  446. return true;
  447. }
  448. void Generator::begin_variable_scope()
  449. {
  450. start_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
  451. emit<Bytecode::Op::CreateLexicalEnvironment>();
  452. }
  453. void Generator::end_variable_scope()
  454. {
  455. end_boundary(BlockBoundaryType::LeaveLexicalEnvironment);
  456. if (!m_current_basic_block->is_terminated()) {
  457. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  458. }
  459. }
  460. void Generator::begin_continuable_scope(Label continue_target, Vector<DeprecatedFlyString> const& language_label_set)
  461. {
  462. m_continuable_scopes.append({ continue_target, language_label_set });
  463. start_boundary(BlockBoundaryType::Continue);
  464. }
  465. void Generator::end_continuable_scope()
  466. {
  467. m_continuable_scopes.take_last();
  468. end_boundary(BlockBoundaryType::Continue);
  469. }
  470. Label Generator::nearest_breakable_scope() const
  471. {
  472. return m_breakable_scopes.last().bytecode_target;
  473. }
  474. void Generator::begin_breakable_scope(Label breakable_target, Vector<DeprecatedFlyString> const& language_label_set)
  475. {
  476. m_breakable_scopes.append({ breakable_target, language_label_set });
  477. start_boundary(BlockBoundaryType::Break);
  478. }
  479. void Generator::end_breakable_scope()
  480. {
  481. m_breakable_scopes.take_last();
  482. end_boundary(BlockBoundaryType::Break);
  483. }
  484. CodeGenerationErrorOr<Generator::ReferenceOperands> Generator::emit_super_reference(MemberExpression const& expression)
  485. {
  486. VERIFY(is<SuperExpression>(expression.object()));
  487. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  488. // 1. Let env be GetThisEnvironment().
  489. // 2. Let actualThis be ? env.GetThisBinding().
  490. auto actual_this = allocate_register();
  491. emit<Bytecode::Op::ResolveThisBinding>(actual_this);
  492. Optional<ScopedOperand> computed_property_value;
  493. if (expression.is_computed()) {
  494. // SuperProperty : super [ Expression ]
  495. // 3. Let propertyNameReference be ? Evaluation of Expression.
  496. // 4. Let propertyNameValue be ? GetValue(propertyNameReference).
  497. computed_property_value = TRY(expression.property().generate_bytecode(*this)).value();
  498. }
  499. // 5/7. Return ? MakeSuperPropertyReference(actualThis, propertyKey, strict).
  500. // https://tc39.es/ecma262/#sec-makesuperpropertyreference
  501. // 1. Let env be GetThisEnvironment().
  502. // 2. Assert: env.HasSuperBinding() is true.
  503. // 3. Let baseValue be ? env.GetSuperBase().
  504. auto base_value = allocate_register();
  505. emit<Bytecode::Op::ResolveSuperBase>(base_value);
  506. // 4. Return the Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }.
  507. return ReferenceOperands {
  508. .base = base_value,
  509. .referenced_name = computed_property_value,
  510. .this_value = actual_this,
  511. };
  512. }
  513. CodeGenerationErrorOr<Generator::ReferenceOperands> Generator::emit_load_from_reference(JS::ASTNode const& node, Optional<ScopedOperand> preferred_dst)
  514. {
  515. if (is<Identifier>(node)) {
  516. auto& identifier = static_cast<Identifier const&>(node);
  517. auto loaded_value = TRY(identifier.generate_bytecode(*this, preferred_dst)).value();
  518. return ReferenceOperands {
  519. .loaded_value = loaded_value,
  520. };
  521. }
  522. if (!is<MemberExpression>(node)) {
  523. return CodeGenerationError {
  524. &node,
  525. "Unimplemented/invalid node used as a reference"sv
  526. };
  527. }
  528. auto& expression = static_cast<MemberExpression const&>(node);
  529. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  530. if (is<SuperExpression>(expression.object())) {
  531. auto super_reference = TRY(emit_super_reference(expression));
  532. auto dst = preferred_dst.has_value() ? preferred_dst.value() : allocate_register();
  533. if (super_reference.referenced_name.has_value()) {
  534. // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
  535. // FIXME: This does ToPropertyKey out of order, which is observable by Symbol.toPrimitive!
  536. emit<Bytecode::Op::GetByValueWithThis>(dst, *super_reference.base, *super_reference.referenced_name, *super_reference.this_value);
  537. } else {
  538. // 3. Let propertyKey be StringValue of IdentifierName.
  539. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  540. emit_get_by_id_with_this(dst, *super_reference.base, identifier_table_ref, *super_reference.this_value);
  541. }
  542. super_reference.loaded_value = dst;
  543. return super_reference;
  544. }
  545. auto base = TRY(expression.object().generate_bytecode(*this)).value();
  546. auto base_identifier = intern_identifier_for_expression(expression.object());
  547. if (expression.is_computed()) {
  548. auto property = TRY(expression.property().generate_bytecode(*this)).value();
  549. auto saved_property = allocate_register();
  550. emit<Bytecode::Op::Mov>(saved_property, property);
  551. auto dst = preferred_dst.has_value() ? preferred_dst.value() : allocate_register();
  552. emit<Bytecode::Op::GetByValue>(dst, base, property, move(base_identifier));
  553. return ReferenceOperands {
  554. .base = base,
  555. .referenced_name = saved_property,
  556. .this_value = base,
  557. .loaded_value = dst,
  558. };
  559. }
  560. if (expression.property().is_identifier()) {
  561. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  562. auto dst = preferred_dst.has_value() ? preferred_dst.value() : allocate_register();
  563. emit_get_by_id(dst, base, identifier_table_ref, move(base_identifier));
  564. return ReferenceOperands {
  565. .base = base,
  566. .referenced_identifier = identifier_table_ref,
  567. .this_value = base,
  568. .loaded_value = dst,
  569. };
  570. }
  571. if (expression.property().is_private_identifier()) {
  572. auto identifier_table_ref = intern_identifier(verify_cast<PrivateIdentifier>(expression.property()).string());
  573. auto dst = preferred_dst.has_value() ? preferred_dst.value() : allocate_register();
  574. emit<Bytecode::Op::GetPrivateById>(dst, base, identifier_table_ref);
  575. return ReferenceOperands {
  576. .base = base,
  577. .referenced_private_identifier = identifier_table_ref,
  578. .this_value = base,
  579. .loaded_value = dst,
  580. };
  581. }
  582. return CodeGenerationError {
  583. &expression,
  584. "Unimplemented non-computed member expression"sv
  585. };
  586. }
  587. CodeGenerationErrorOr<void> Generator::emit_store_to_reference(JS::ASTNode const& node, ScopedOperand value)
  588. {
  589. if (is<Identifier>(node)) {
  590. auto& identifier = static_cast<Identifier const&>(node);
  591. emit_set_variable(identifier, value);
  592. return {};
  593. }
  594. if (is<MemberExpression>(node)) {
  595. auto& expression = static_cast<MemberExpression const&>(node);
  596. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  597. if (is<SuperExpression>(expression.object())) {
  598. auto super_reference = TRY(emit_super_reference(expression));
  599. // 4. Return the Reference Record { [[Base]]: baseValue, [[ReferencedName]]: propertyKey, [[Strict]]: strict, [[ThisValue]]: actualThis }.
  600. if (super_reference.referenced_name.has_value()) {
  601. // 5. Let propertyKey be ? ToPropertyKey(propertyNameValue).
  602. // FIXME: This does ToPropertyKey out of order, which is observable by Symbol.toPrimitive!
  603. emit<Bytecode::Op::PutByValueWithThis>(*super_reference.base, *super_reference.referenced_name, *super_reference.this_value, value);
  604. } else {
  605. // 3. Let propertyKey be StringValue of IdentifierName.
  606. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  607. emit<Bytecode::Op::PutByIdWithThis>(*super_reference.base, *super_reference.this_value, identifier_table_ref, value, Bytecode::Op::PropertyKind::KeyValue, next_property_lookup_cache());
  608. }
  609. } else {
  610. auto object = TRY(expression.object().generate_bytecode(*this)).value();
  611. if (expression.is_computed()) {
  612. auto property = TRY(expression.property().generate_bytecode(*this)).value();
  613. emit<Bytecode::Op::PutByValue>(object, property, value);
  614. } else if (expression.property().is_identifier()) {
  615. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  616. emit<Bytecode::Op::PutById>(object, identifier_table_ref, value, Bytecode::Op::PropertyKind::KeyValue, next_property_lookup_cache());
  617. } else if (expression.property().is_private_identifier()) {
  618. auto identifier_table_ref = intern_identifier(verify_cast<PrivateIdentifier>(expression.property()).string());
  619. emit<Bytecode::Op::PutPrivateById>(object, identifier_table_ref, value);
  620. } else {
  621. return CodeGenerationError {
  622. &expression,
  623. "Unimplemented non-computed member expression"sv
  624. };
  625. }
  626. }
  627. return {};
  628. }
  629. return CodeGenerationError {
  630. &node,
  631. "Unimplemented/invalid node used a reference"sv
  632. };
  633. }
  634. CodeGenerationErrorOr<void> Generator::emit_store_to_reference(ReferenceOperands const& reference, ScopedOperand value)
  635. {
  636. if (reference.referenced_private_identifier.has_value()) {
  637. emit<Bytecode::Op::PutPrivateById>(*reference.base, *reference.referenced_private_identifier, value);
  638. return {};
  639. }
  640. if (reference.referenced_identifier.has_value()) {
  641. if (reference.base == reference.this_value)
  642. emit<Bytecode::Op::PutById>(*reference.base, *reference.referenced_identifier, value, Bytecode::Op::PropertyKind::KeyValue, next_property_lookup_cache());
  643. else
  644. emit<Bytecode::Op::PutByIdWithThis>(*reference.base, *reference.this_value, *reference.referenced_identifier, value, Bytecode::Op::PropertyKind::KeyValue, next_property_lookup_cache());
  645. return {};
  646. }
  647. if (reference.base == reference.this_value)
  648. emit<Bytecode::Op::PutByValue>(*reference.base, *reference.referenced_name, value);
  649. else
  650. emit<Bytecode::Op::PutByValueWithThis>(*reference.base, *reference.referenced_name, *reference.this_value, value);
  651. return {};
  652. }
  653. CodeGenerationErrorOr<Optional<ScopedOperand>> Generator::emit_delete_reference(JS::ASTNode const& node)
  654. {
  655. if (is<Identifier>(node)) {
  656. auto& identifier = static_cast<Identifier const&>(node);
  657. if (identifier.is_local()) {
  658. return add_constant(Value(false));
  659. }
  660. auto dst = allocate_register();
  661. emit<Bytecode::Op::DeleteVariable>(dst, intern_identifier(identifier.string()));
  662. return dst;
  663. }
  664. if (is<MemberExpression>(node)) {
  665. auto& expression = static_cast<MemberExpression const&>(node);
  666. // https://tc39.es/ecma262/#sec-super-keyword-runtime-semantics-evaluation
  667. if (is<SuperExpression>(expression.object())) {
  668. auto super_reference = TRY(emit_super_reference(expression));
  669. auto dst = allocate_register();
  670. if (super_reference.referenced_name.has_value()) {
  671. emit<Bytecode::Op::DeleteByValueWithThis>(dst, *super_reference.base, *super_reference.this_value, *super_reference.referenced_name);
  672. } else {
  673. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  674. emit<Bytecode::Op::DeleteByIdWithThis>(dst, *super_reference.base, *super_reference.this_value, identifier_table_ref);
  675. }
  676. return Optional<ScopedOperand> {};
  677. }
  678. auto object = TRY(expression.object().generate_bytecode(*this)).value();
  679. auto dst = allocate_register();
  680. if (expression.is_computed()) {
  681. auto property = TRY(expression.property().generate_bytecode(*this)).value();
  682. emit<Bytecode::Op::DeleteByValue>(dst, object, property);
  683. } else if (expression.property().is_identifier()) {
  684. auto identifier_table_ref = intern_identifier(verify_cast<Identifier>(expression.property()).string());
  685. emit<Bytecode::Op::DeleteById>(dst, object, identifier_table_ref);
  686. } else {
  687. // NOTE: Trying to delete a private field generates a SyntaxError in the parser.
  688. return CodeGenerationError {
  689. &expression,
  690. "Unimplemented non-computed member expression"sv
  691. };
  692. }
  693. return dst;
  694. }
  695. // Though this will have no deletion effect, we still have to evaluate the node as it can have side effects.
  696. // For example: delete a(); delete ++c.b; etc.
  697. // 13.5.1.2 Runtime Semantics: Evaluation, https://tc39.es/ecma262/#sec-delete-operator-runtime-semantics-evaluation
  698. // 1. Let ref be the result of evaluating UnaryExpression.
  699. // 2. ReturnIfAbrupt(ref).
  700. (void)TRY(node.generate_bytecode(*this));
  701. // 3. If ref is not a Reference Record, return true.
  702. // NOTE: The rest of the steps are handled by Delete{Variable,ByValue,Id}.
  703. return add_constant(Value(true));
  704. }
  705. void Generator::emit_set_variable(JS::Identifier const& identifier, ScopedOperand value, Bytecode::Op::BindingInitializationMode initialization_mode, Bytecode::Op::EnvironmentMode environment_mode)
  706. {
  707. if (identifier.is_local()) {
  708. if (value.operand().is_local() && value.operand().index() == identifier.local_variable_index()) {
  709. // Moving a local to itself is a no-op.
  710. return;
  711. }
  712. emit<Bytecode::Op::Mov>(local(identifier.local_variable_index()), value);
  713. } else {
  714. auto identifier_index = intern_identifier(identifier.string());
  715. if (environment_mode == Bytecode::Op::EnvironmentMode::Lexical) {
  716. if (initialization_mode == Bytecode::Op::BindingInitializationMode::Initialize) {
  717. emit<Bytecode::Op::InitializeLexicalBinding>(identifier_index, value);
  718. } else if (initialization_mode == Bytecode::Op::BindingInitializationMode::Set) {
  719. emit<Bytecode::Op::SetLexicalBinding>(identifier_index, value);
  720. }
  721. } else if (environment_mode == Bytecode::Op::EnvironmentMode::Var) {
  722. if (initialization_mode == Bytecode::Op::BindingInitializationMode::Initialize) {
  723. emit<Bytecode::Op::InitializeVariableBinding>(identifier_index, value);
  724. } else if (initialization_mode == Bytecode::Op::BindingInitializationMode::Set) {
  725. emit<Bytecode::Op::SetVariableBinding>(identifier_index, value);
  726. }
  727. } else {
  728. VERIFY_NOT_REACHED();
  729. }
  730. }
  731. }
  732. static Optional<ByteString> expression_identifier(Expression const& expression)
  733. {
  734. if (expression.is_identifier()) {
  735. auto const& identifier = static_cast<Identifier const&>(expression);
  736. return identifier.string();
  737. }
  738. if (expression.is_numeric_literal()) {
  739. auto const& literal = static_cast<NumericLiteral const&>(expression);
  740. return literal.value().to_string_without_side_effects().to_byte_string();
  741. }
  742. if (expression.is_string_literal()) {
  743. auto const& literal = static_cast<StringLiteral const&>(expression);
  744. return ByteString::formatted("'{}'", literal.value());
  745. }
  746. if (expression.is_member_expression()) {
  747. auto const& member_expression = static_cast<MemberExpression const&>(expression);
  748. StringBuilder builder;
  749. if (auto identifer = expression_identifier(member_expression.object()); identifer.has_value())
  750. builder.append(*identifer);
  751. if (auto identifer = expression_identifier(member_expression.property()); identifer.has_value()) {
  752. if (member_expression.is_computed())
  753. builder.appendff("[{}]", *identifer);
  754. else
  755. builder.appendff(".{}", *identifer);
  756. }
  757. return builder.to_byte_string();
  758. }
  759. return {};
  760. }
  761. Optional<IdentifierTableIndex> Generator::intern_identifier_for_expression(Expression const& expression)
  762. {
  763. if (auto identifer = expression_identifier(expression); identifer.has_value())
  764. return intern_identifier(identifer.release_value());
  765. return {};
  766. }
  767. void Generator::generate_scoped_jump(JumpType type)
  768. {
  769. TemporaryChange temp { m_current_unwind_context, m_current_unwind_context };
  770. bool last_was_finally = false;
  771. for (size_t i = m_boundaries.size(); i > 0; --i) {
  772. auto boundary = m_boundaries[i - 1];
  773. using enum BlockBoundaryType;
  774. switch (boundary) {
  775. case Break:
  776. if (type == JumpType::Break) {
  777. emit<Op::Jump>(nearest_breakable_scope());
  778. return;
  779. }
  780. break;
  781. case Continue:
  782. if (type == JumpType::Continue) {
  783. emit<Op::Jump>(nearest_continuable_scope());
  784. return;
  785. }
  786. break;
  787. case Unwind:
  788. VERIFY(last_was_finally || !m_current_unwind_context->finalizer().has_value());
  789. if (!last_was_finally) {
  790. VERIFY(m_current_unwind_context && m_current_unwind_context->handler().has_value());
  791. emit<Bytecode::Op::LeaveUnwindContext>();
  792. m_current_unwind_context = m_current_unwind_context->previous();
  793. }
  794. last_was_finally = false;
  795. break;
  796. case LeaveLexicalEnvironment:
  797. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  798. break;
  799. case ReturnToFinally: {
  800. VERIFY(m_current_unwind_context->finalizer().has_value());
  801. m_current_unwind_context = m_current_unwind_context->previous();
  802. auto jump_type_name = type == JumpType::Break ? "break"sv : "continue"sv;
  803. auto block_name = MUST(String::formatted("{}.{}", current_block().name(), jump_type_name));
  804. auto& block = make_block(block_name);
  805. emit<Op::ScheduleJump>(Label { block });
  806. switch_to_basic_block(block);
  807. last_was_finally = true;
  808. break;
  809. }
  810. case LeaveFinally:
  811. emit<Op::LeaveFinally>();
  812. break;
  813. }
  814. }
  815. VERIFY_NOT_REACHED();
  816. }
  817. void Generator::generate_labelled_jump(JumpType type, DeprecatedFlyString const& label)
  818. {
  819. TemporaryChange temp { m_current_unwind_context, m_current_unwind_context };
  820. size_t current_boundary = m_boundaries.size();
  821. bool last_was_finally = false;
  822. auto const& jumpable_scopes = type == JumpType::Continue ? m_continuable_scopes : m_breakable_scopes;
  823. for (auto const& jumpable_scope : jumpable_scopes.in_reverse()) {
  824. for (; current_boundary > 0; --current_boundary) {
  825. auto boundary = m_boundaries[current_boundary - 1];
  826. if (boundary == BlockBoundaryType::Unwind) {
  827. VERIFY(last_was_finally || !m_current_unwind_context->finalizer().has_value());
  828. if (!last_was_finally) {
  829. VERIFY(m_current_unwind_context && m_current_unwind_context->handler().has_value());
  830. emit<Bytecode::Op::LeaveUnwindContext>();
  831. m_current_unwind_context = m_current_unwind_context->previous();
  832. }
  833. last_was_finally = false;
  834. } else if (boundary == BlockBoundaryType::LeaveLexicalEnvironment) {
  835. emit<Bytecode::Op::LeaveLexicalEnvironment>();
  836. } else if (boundary == BlockBoundaryType::ReturnToFinally) {
  837. VERIFY(m_current_unwind_context->finalizer().has_value());
  838. m_current_unwind_context = m_current_unwind_context->previous();
  839. auto jump_type_name = type == JumpType::Break ? "break"sv : "continue"sv;
  840. auto block_name = MUST(String::formatted("{}.{}", current_block().name(), jump_type_name));
  841. auto& block = make_block(block_name);
  842. emit<Op::ScheduleJump>(Label { block });
  843. switch_to_basic_block(block);
  844. last_was_finally = true;
  845. } else if ((type == JumpType::Continue && boundary == BlockBoundaryType::Continue) || (type == JumpType::Break && boundary == BlockBoundaryType::Break)) {
  846. // Make sure we don't process this boundary twice if the current jumpable scope doesn't contain the target label.
  847. --current_boundary;
  848. break;
  849. }
  850. }
  851. if (jumpable_scope.language_label_set.contains_slow(label)) {
  852. emit<Op::Jump>(jumpable_scope.bytecode_target);
  853. return;
  854. }
  855. }
  856. // We must have a jumpable scope available that contains the label, as this should be enforced by the parser.
  857. VERIFY_NOT_REACHED();
  858. }
  859. void Generator::generate_break()
  860. {
  861. generate_scoped_jump(JumpType::Break);
  862. }
  863. void Generator::generate_break(DeprecatedFlyString const& break_label)
  864. {
  865. generate_labelled_jump(JumpType::Break, break_label);
  866. }
  867. void Generator::generate_continue()
  868. {
  869. generate_scoped_jump(JumpType::Continue);
  870. }
  871. void Generator::generate_continue(DeprecatedFlyString const& continue_label)
  872. {
  873. generate_labelled_jump(JumpType::Continue, continue_label);
  874. }
  875. void Generator::push_home_object(ScopedOperand object)
  876. {
  877. m_home_objects.append(object);
  878. }
  879. void Generator::pop_home_object()
  880. {
  881. m_home_objects.take_last();
  882. }
  883. void Generator::emit_new_function(ScopedOperand dst, FunctionExpression const& function_node, Optional<IdentifierTableIndex> lhs_name)
  884. {
  885. if (m_home_objects.is_empty()) {
  886. emit<Op::NewFunction>(dst, function_node, lhs_name);
  887. } else {
  888. emit<Op::NewFunction>(dst, function_node, lhs_name, m_home_objects.last());
  889. }
  890. }
  891. CodeGenerationErrorOr<Optional<ScopedOperand>> Generator::emit_named_evaluation_if_anonymous_function(Expression const& expression, Optional<IdentifierTableIndex> lhs_name, Optional<ScopedOperand> preferred_dst)
  892. {
  893. if (is<FunctionExpression>(expression)) {
  894. auto const& function_expression = static_cast<FunctionExpression const&>(expression);
  895. if (!function_expression.has_name()) {
  896. return TRY(function_expression.generate_bytecode_with_lhs_name(*this, move(lhs_name), preferred_dst)).value();
  897. }
  898. }
  899. if (is<ClassExpression>(expression)) {
  900. auto const& class_expression = static_cast<ClassExpression const&>(expression);
  901. if (!class_expression.has_name()) {
  902. return TRY(class_expression.generate_bytecode_with_lhs_name(*this, move(lhs_name), preferred_dst)).value();
  903. }
  904. }
  905. return expression.generate_bytecode(*this, preferred_dst);
  906. }
  907. void Generator::emit_get_by_id(ScopedOperand dst, ScopedOperand base, IdentifierTableIndex property_identifier, Optional<IdentifierTableIndex> base_identifier)
  908. {
  909. emit<Op::GetById>(dst, base, property_identifier, move(base_identifier), m_next_property_lookup_cache++);
  910. }
  911. void Generator::emit_get_by_id_with_this(ScopedOperand dst, ScopedOperand base, IdentifierTableIndex id, ScopedOperand this_value)
  912. {
  913. emit<Op::GetByIdWithThis>(dst, base, id, this_value, m_next_property_lookup_cache++);
  914. }
  915. void Generator::emit_iterator_value(ScopedOperand dst, ScopedOperand result)
  916. {
  917. emit_get_by_id(dst, result, intern_identifier("value"sv));
  918. }
  919. void Generator::emit_iterator_complete(ScopedOperand dst, ScopedOperand result)
  920. {
  921. emit_get_by_id(dst, result, intern_identifier("done"sv));
  922. }
  923. bool Generator::is_local_initialized(u32 local_index) const
  924. {
  925. return m_initialized_locals.find(local_index) != m_initialized_locals.end();
  926. }
  927. void Generator::set_local_initialized(u32 local_index)
  928. {
  929. m_initialized_locals.set(local_index);
  930. }
  931. ScopedOperand Generator::get_this(Optional<ScopedOperand> preferred_dst)
  932. {
  933. if (m_current_basic_block->this_().has_value())
  934. return m_current_basic_block->this_().value();
  935. if (m_root_basic_blocks[0]->this_().has_value()) {
  936. m_current_basic_block->set_this(m_root_basic_blocks[0]->this_().value());
  937. return m_root_basic_blocks[0]->this_().value();
  938. }
  939. auto dst = preferred_dst.has_value() ? preferred_dst.value() : allocate_register();
  940. emit<Bytecode::Op::ResolveThisBinding>(dst);
  941. m_current_basic_block->set_this(dst);
  942. return dst;
  943. }
  944. ScopedOperand Generator::accumulator()
  945. {
  946. return m_accumulator;
  947. }
  948. bool Generator::fuse_compare_and_jump(ScopedOperand const& condition, Label true_target, Label false_target)
  949. {
  950. auto& last_instruction = *reinterpret_cast<Instruction const*>(m_current_basic_block->data() + m_current_basic_block->last_instruction_start_offset());
  951. #define HANDLE_COMPARISON_OP(op_TitleCase, op_snake_case, numeric_operator) \
  952. if (last_instruction.type() == Instruction::Type::op_TitleCase) { \
  953. auto& comparison = static_cast<Op::op_TitleCase const&>(last_instruction); \
  954. VERIFY(comparison.dst() == condition); \
  955. auto lhs = comparison.lhs(); \
  956. auto rhs = comparison.rhs(); \
  957. m_current_basic_block->rewind(); \
  958. emit<Op::Jump##op_TitleCase>(lhs, rhs, true_target, false_target); \
  959. return true; \
  960. }
  961. JS_ENUMERATE_COMPARISON_OPS(HANDLE_COMPARISON_OP);
  962. #undef HANDLE_COMPARISON_OP
  963. return false;
  964. }
  965. void Generator::emit_jump_if(ScopedOperand const& condition, Label true_target, Label false_target)
  966. {
  967. if (condition.operand().is_constant()) {
  968. auto value = m_constants[condition.operand().index()];
  969. if (value.is_boolean()) {
  970. if (value.as_bool()) {
  971. emit<Op::Jump>(true_target);
  972. } else {
  973. emit<Op::Jump>(false_target);
  974. }
  975. return;
  976. }
  977. }
  978. // NOTE: It's only safe to fuse compare-and-jump if the condition is a temporary with no other dependents.
  979. if (condition.operand().is_register()
  980. && condition.ref_count() == 1
  981. && m_current_basic_block->size() > 0) {
  982. if (fuse_compare_and_jump(condition, true_target, false_target))
  983. return;
  984. }
  985. emit<Op::JumpIf>(condition, true_target, false_target);
  986. }
  987. }