UnifySameBlocks.cpp 2.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  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. if (equal_blocks.contains(&*candidate_block))
  22. continue;
  23. // FIXME: This can probably be relaxed a bit...
  24. if (candidate_block->size() != block->size())
  25. continue;
  26. auto candidate_bytes = candidate_block->instruction_stream();
  27. // FIXME: NewBigInt's value is not correctly reflected by its encoding in memory,
  28. // this will yield false negatives for blocks containing that
  29. if (memcmp(candidate_bytes.data(), block_bytes.data(), candidate_block->size()) == 0)
  30. equal_blocks.set(candidate_block.ptr(), block);
  31. }
  32. }
  33. auto replace_blocks = [&](auto& match, auto& replacement) {
  34. Optional<size_t> first_successor_position;
  35. auto it = executable.executable.basic_blocks.find_if([match](auto& block) { return match == block; });
  36. VERIFY(!it.is_end());
  37. executable.executable.basic_blocks.remove(it.index());
  38. if (!first_successor_position.has_value())
  39. first_successor_position = it.index();
  40. for (auto& block : executable.executable.basic_blocks) {
  41. InstructionStreamIterator it { block->instruction_stream() };
  42. while (!it.at_end()) {
  43. auto& instruction = *it;
  44. ++it;
  45. const_cast<Instruction&>(instruction).replace_references(*match, replacement);
  46. }
  47. }
  48. return first_successor_position;
  49. };
  50. for (auto& entry : equal_blocks)
  51. (void)replace_blocks(entry.key, *entry.value);
  52. finished();
  53. }
  54. }