UnifySameBlocks.cpp 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <LibJS/Bytecode/PassManager.h>
  7. #include <string.h>
  8. namespace JS::Bytecode::Passes {
  9. void UnifySameBlocks::perform(PassPipelineExecutable& executable)
  10. {
  11. started();
  12. VERIFY(executable.cfg.has_value());
  13. VERIFY(executable.inverted_cfg.has_value());
  14. auto cfg = executable.cfg.release_value();
  15. auto inverted_cfg = executable.inverted_cfg.release_value();
  16. HashMap<BasicBlock const*, BasicBlock const*> equal_blocks;
  17. for (size_t i = 0; i < executable.executable.basic_blocks.size(); ++i) {
  18. auto& block = executable.executable.basic_blocks[i];
  19. auto block_bytes = block.instruction_stream();
  20. for (auto& candidate_block : executable.executable.basic_blocks.span().slice(i + 1)) {
  21. // FIXME: This can probably be relaxed a bit...
  22. if (candidate_block->size() != block.size())
  23. continue;
  24. auto candidate_bytes = candidate_block->instruction_stream();
  25. if (memcmp(candidate_bytes.data(), block_bytes.data(), candidate_block->size()) == 0)
  26. equal_blocks.set(&*candidate_block, &block);
  27. }
  28. }
  29. auto replace_blocks = [&](auto& match, auto& replacement) {
  30. Optional<size_t> first_successor_position;
  31. auto it = executable.executable.basic_blocks.find_if([match](auto& block) { return match == block; });
  32. VERIFY(!it.is_end());
  33. executable.executable.basic_blocks.remove(it.index());
  34. if (!first_successor_position.has_value())
  35. first_successor_position = it.index();
  36. for (auto& block : executable.executable.basic_blocks) {
  37. InstructionStreamIterator it { block.instruction_stream() };
  38. while (!it.at_end()) {
  39. auto& instruction = *it;
  40. ++it;
  41. const_cast<Instruction&>(instruction).replace_references(*match, replacement);
  42. }
  43. }
  44. return first_successor_position;
  45. };
  46. for (auto& entry : equal_blocks)
  47. (void)replace_blocks(entry.key, *entry.value);
  48. finished();
  49. }
  50. }