Generator.cpp 48 KB

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