Generator.cpp 45 KB

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