RegexOptimizer.cpp 41 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995
  1. /*
  2. * Copyright (c) 2021, Ali Mohammad Pur <mpfard@serenityos.org>
  3. *
  4. * SPDX-License-Identifier: BSD-2-Clause
  5. */
  6. #include <AK/Debug.h>
  7. #include <AK/QuickSort.h>
  8. #include <AK/RedBlackTree.h>
  9. #include <AK/Stack.h>
  10. #include <LibRegex/Regex.h>
  11. #include <LibRegex/RegexBytecodeStreamOptimizer.h>
  12. #if REGEX_DEBUG
  13. # include <AK/ScopeGuard.h>
  14. # include <AK/ScopeLogger.h>
  15. #endif
  16. namespace regex {
  17. using Detail::Block;
  18. template<typename Parser>
  19. void Regex<Parser>::run_optimization_passes()
  20. {
  21. parser_result.bytecode.flatten();
  22. // Rewrite fork loops as atomic groups
  23. // e.g. a*b -> (ATOMIC a*)b
  24. attempt_rewrite_loops_as_atomic_groups(split_basic_blocks(parser_result.bytecode));
  25. parser_result.bytecode.flatten();
  26. }
  27. template<typename Parser>
  28. typename Regex<Parser>::BasicBlockList Regex<Parser>::split_basic_blocks(ByteCode const& bytecode)
  29. {
  30. BasicBlockList block_boundaries;
  31. size_t end_of_last_block = 0;
  32. auto bytecode_size = bytecode.size();
  33. MatchState state;
  34. state.instruction_position = 0;
  35. auto check_jump = [&]<typename T>(OpCode const& opcode) {
  36. auto& op = static_cast<T const&>(opcode);
  37. ssize_t jump_offset = op.size() + op.offset();
  38. if (jump_offset >= 0) {
  39. block_boundaries.append({ end_of_last_block, state.instruction_position });
  40. end_of_last_block = state.instruction_position + opcode.size();
  41. } else {
  42. // This op jumps back, see if that's within this "block".
  43. if (jump_offset + state.instruction_position > end_of_last_block) {
  44. // Split the block!
  45. block_boundaries.append({ end_of_last_block, jump_offset + state.instruction_position });
  46. block_boundaries.append({ jump_offset + state.instruction_position, state.instruction_position });
  47. end_of_last_block = state.instruction_position + opcode.size();
  48. } else {
  49. // Nope, it's just a jump to another block
  50. block_boundaries.append({ end_of_last_block, state.instruction_position });
  51. end_of_last_block = state.instruction_position + opcode.size();
  52. }
  53. }
  54. };
  55. for (;;) {
  56. auto& opcode = bytecode.get_opcode(state);
  57. switch (opcode.opcode_id()) {
  58. case OpCodeId::Jump:
  59. check_jump.template operator()<OpCode_Jump>(opcode);
  60. break;
  61. case OpCodeId::JumpNonEmpty:
  62. check_jump.template operator()<OpCode_JumpNonEmpty>(opcode);
  63. break;
  64. case OpCodeId::ForkJump:
  65. check_jump.template operator()<OpCode_ForkJump>(opcode);
  66. break;
  67. case OpCodeId::ForkStay:
  68. check_jump.template operator()<OpCode_ForkStay>(opcode);
  69. break;
  70. case OpCodeId::FailForks:
  71. block_boundaries.append({ end_of_last_block, state.instruction_position });
  72. end_of_last_block = state.instruction_position + opcode.size();
  73. break;
  74. case OpCodeId::Repeat: {
  75. // Repeat produces two blocks, one containing its repeated expr, and one after that.
  76. auto repeat_start = state.instruction_position - static_cast<OpCode_Repeat const&>(opcode).offset();
  77. if (repeat_start > end_of_last_block)
  78. block_boundaries.append({ end_of_last_block, repeat_start });
  79. block_boundaries.append({ repeat_start, state.instruction_position });
  80. end_of_last_block = state.instruction_position + opcode.size();
  81. break;
  82. }
  83. default:
  84. break;
  85. }
  86. auto next_ip = state.instruction_position + opcode.size();
  87. if (next_ip < bytecode_size)
  88. state.instruction_position = next_ip;
  89. else
  90. break;
  91. }
  92. if (end_of_last_block < bytecode_size)
  93. block_boundaries.append({ end_of_last_block, bytecode_size });
  94. quick_sort(block_boundaries, [](auto& a, auto& b) { return a.start < b.start; });
  95. return block_boundaries;
  96. }
  97. static bool has_overlap(Vector<CompareTypeAndValuePair> const& lhs, Vector<CompareTypeAndValuePair> const& rhs)
  98. {
  99. // We have to fully interpret the two sequences to determine if they overlap (that is, keep track of inversion state and what ranges they cover).
  100. bool inverse { false };
  101. bool temporary_inverse { false };
  102. bool reset_temporary_inverse { false };
  103. auto current_lhs_inversion_state = [&]() -> bool { return temporary_inverse ^ inverse; };
  104. RedBlackTree<u32, u32> lhs_ranges;
  105. RedBlackTree<u32, u32> lhs_negated_ranges;
  106. HashTable<CharClass> lhs_char_classes;
  107. HashTable<CharClass> lhs_negated_char_classes;
  108. auto range_contains = [&]<typename T>(T& value) -> bool {
  109. u32 start;
  110. u32 end;
  111. if constexpr (IsSame<T, CharRange>) {
  112. start = value.from;
  113. end = value.to;
  114. } else {
  115. start = value;
  116. end = value;
  117. }
  118. auto* max = lhs_ranges.find_smallest_not_below(start);
  119. return max && *max <= end;
  120. };
  121. auto char_class_contains = [&](CharClass const& value) -> bool {
  122. if (lhs_char_classes.contains(value))
  123. return true;
  124. if (lhs_negated_char_classes.contains(value))
  125. return false;
  126. // This char class might match something in the ranges we have, and checking that is far too expensive, so just bail out.
  127. return true;
  128. };
  129. for (auto const& pair : lhs) {
  130. if (reset_temporary_inverse) {
  131. reset_temporary_inverse = false;
  132. temporary_inverse = false;
  133. } else {
  134. reset_temporary_inverse = true;
  135. }
  136. switch (pair.type) {
  137. case CharacterCompareType::Inverse:
  138. inverse = !inverse;
  139. break;
  140. case CharacterCompareType::TemporaryInverse:
  141. temporary_inverse = true;
  142. reset_temporary_inverse = true;
  143. break;
  144. case CharacterCompareType::AnyChar:
  145. // Special case: if not inverted, AnyChar is always in the range.
  146. if (!current_lhs_inversion_state())
  147. return true;
  148. break;
  149. case CharacterCompareType::Char:
  150. if (!current_lhs_inversion_state())
  151. lhs_ranges.insert(pair.value, pair.value);
  152. else
  153. lhs_negated_ranges.insert(pair.value, pair.value);
  154. break;
  155. case CharacterCompareType::String:
  156. // FIXME: We just need to look at the last character of this string, but we only have the first character here.
  157. // Just bail out to avoid false positives.
  158. return true;
  159. case CharacterCompareType::CharClass:
  160. if (!current_lhs_inversion_state())
  161. lhs_char_classes.set(static_cast<CharClass>(pair.value));
  162. else
  163. lhs_negated_char_classes.set(static_cast<CharClass>(pair.value));
  164. break;
  165. case CharacterCompareType::CharRange: {
  166. auto range = CharRange(pair.value);
  167. if (!current_lhs_inversion_state())
  168. lhs_ranges.insert(range.from, range.to);
  169. else
  170. lhs_negated_ranges.insert(range.from, range.to);
  171. break;
  172. }
  173. case CharacterCompareType::LookupTable:
  174. // We've transformed this into a series of ranges in flat_compares(), so bail out if we see it.
  175. return true;
  176. case CharacterCompareType::Reference:
  177. // We've handled this before coming here.
  178. break;
  179. case CharacterCompareType::Property:
  180. case CharacterCompareType::GeneralCategory:
  181. case CharacterCompareType::Script:
  182. case CharacterCompareType::ScriptExtension:
  183. case CharacterCompareType::And:
  184. case CharacterCompareType::Or:
  185. case CharacterCompareType::EndAndOr:
  186. // FIXME: These are too difficult to handle, so bail out.
  187. return true;
  188. case CharacterCompareType::Undefined:
  189. case CharacterCompareType::RangeExpressionDummy:
  190. // These do not occur in valid bytecode.
  191. VERIFY_NOT_REACHED();
  192. }
  193. }
  194. if constexpr (REGEX_DEBUG) {
  195. dbgln("lhs ranges:");
  196. for (auto it = lhs_ranges.begin(); it != lhs_ranges.end(); ++it)
  197. dbgln(" {}..{}", it.key(), *it);
  198. dbgln("lhs negated ranges:");
  199. for (auto it = lhs_negated_ranges.begin(); it != lhs_negated_ranges.end(); ++it)
  200. dbgln(" {}..{}", it.key(), *it);
  201. }
  202. for (auto const& pair : rhs) {
  203. if (reset_temporary_inverse) {
  204. reset_temporary_inverse = false;
  205. temporary_inverse = false;
  206. } else {
  207. reset_temporary_inverse = true;
  208. }
  209. dbgln_if(REGEX_DEBUG, "check {} ({})...", character_compare_type_name(pair.type), pair.value);
  210. switch (pair.type) {
  211. case CharacterCompareType::Inverse:
  212. inverse = !inverse;
  213. break;
  214. case CharacterCompareType::TemporaryInverse:
  215. temporary_inverse = true;
  216. reset_temporary_inverse = true;
  217. break;
  218. case CharacterCompareType::AnyChar:
  219. // Special case: if not inverted, AnyChar is always in the range.
  220. if (!current_lhs_inversion_state())
  221. return true;
  222. break;
  223. case CharacterCompareType::Char:
  224. if (current_lhs_inversion_state() ^ range_contains(pair.value))
  225. return true;
  226. break;
  227. case CharacterCompareType::String:
  228. // FIXME: We just need to look at the last character of this string, but we only have the first character here.
  229. // Just bail out to avoid false positives.
  230. return true;
  231. case CharacterCompareType::CharClass:
  232. if (current_lhs_inversion_state() ^ char_class_contains(static_cast<CharClass>(pair.value)))
  233. return true;
  234. break;
  235. case CharacterCompareType::CharRange: {
  236. auto range = CharRange(pair.value);
  237. if (current_lhs_inversion_state() ^ range_contains(range))
  238. return true;
  239. break;
  240. }
  241. case CharacterCompareType::LookupTable:
  242. // We've transformed this into a series of ranges in flat_compares(), so bail out if we see it.
  243. return true;
  244. case CharacterCompareType::Reference:
  245. // We've handled this before coming here.
  246. break;
  247. case CharacterCompareType::Property:
  248. case CharacterCompareType::GeneralCategory:
  249. case CharacterCompareType::Script:
  250. case CharacterCompareType::ScriptExtension:
  251. case CharacterCompareType::And:
  252. case CharacterCompareType::Or:
  253. case CharacterCompareType::EndAndOr:
  254. // FIXME: These are too difficult to handle, so bail out.
  255. return true;
  256. case CharacterCompareType::Undefined:
  257. case CharacterCompareType::RangeExpressionDummy:
  258. // These do not occur in valid bytecode.
  259. VERIFY_NOT_REACHED();
  260. }
  261. }
  262. return false;
  263. }
  264. enum class AtomicRewritePreconditionResult {
  265. SatisfiedWithProperHeader,
  266. SatisfiedWithEmptyHeader,
  267. NotSatisfied,
  268. };
  269. static AtomicRewritePreconditionResult block_satisfies_atomic_rewrite_precondition(ByteCode const& bytecode, Block const& repeated_block, Block const& following_block)
  270. {
  271. Vector<Vector<CompareTypeAndValuePair>> repeated_values;
  272. HashTable<size_t> active_capture_groups;
  273. MatchState state;
  274. auto has_seen_actionable_opcode = false;
  275. for (state.instruction_position = repeated_block.start; state.instruction_position < repeated_block.end;) {
  276. auto& opcode = bytecode.get_opcode(state);
  277. switch (opcode.opcode_id()) {
  278. case OpCodeId::Compare: {
  279. has_seen_actionable_opcode = true;
  280. auto compares = static_cast<OpCode_Compare const&>(opcode).flat_compares();
  281. if (repeated_values.is_empty() && any_of(compares, [](auto& compare) { return compare.type == CharacterCompareType::AnyChar; }))
  282. return AtomicRewritePreconditionResult::NotSatisfied;
  283. repeated_values.append(move(compares));
  284. break;
  285. }
  286. case OpCodeId::CheckBegin:
  287. case OpCodeId::CheckEnd:
  288. has_seen_actionable_opcode = true;
  289. if (repeated_values.is_empty())
  290. return AtomicRewritePreconditionResult::SatisfiedWithProperHeader;
  291. break;
  292. case OpCodeId::CheckBoundary:
  293. // FIXME: What should we do with these? for now, let's fail.
  294. return AtomicRewritePreconditionResult::NotSatisfied;
  295. case OpCodeId::Restore:
  296. case OpCodeId::GoBack:
  297. return AtomicRewritePreconditionResult::NotSatisfied;
  298. case OpCodeId::SaveRightCaptureGroup:
  299. active_capture_groups.set(static_cast<OpCode_SaveRightCaptureGroup const&>(opcode).id());
  300. break;
  301. case OpCodeId::SaveLeftCaptureGroup:
  302. active_capture_groups.set(static_cast<OpCode_SaveLeftCaptureGroup const&>(opcode).id());
  303. break;
  304. case OpCodeId::ForkJump:
  305. case OpCodeId::ForkReplaceJump:
  306. case OpCodeId::JumpNonEmpty:
  307. // We could attempt to recursively resolve the follow set, but pretending that this just goes nowhere is faster.
  308. if (!has_seen_actionable_opcode)
  309. return AtomicRewritePreconditionResult::NotSatisfied;
  310. break;
  311. default:
  312. break;
  313. }
  314. state.instruction_position += opcode.size();
  315. }
  316. dbgln_if(REGEX_DEBUG, "Found {} entries in reference", repeated_values.size());
  317. dbgln_if(REGEX_DEBUG, "Found {} active capture groups", active_capture_groups.size());
  318. bool following_block_has_at_least_one_compare = false;
  319. // Find the first compare in the following block, it must NOT match any of the values in `repeated_values'.
  320. for (state.instruction_position = following_block.start; state.instruction_position < following_block.end;) {
  321. auto& opcode = bytecode.get_opcode(state);
  322. switch (opcode.opcode_id()) {
  323. // Note: These have to exist since we're effectively repeating the following block as well
  324. case OpCodeId::SaveRightCaptureGroup:
  325. active_capture_groups.set(static_cast<OpCode_SaveRightCaptureGroup const&>(opcode).id());
  326. break;
  327. case OpCodeId::SaveLeftCaptureGroup:
  328. active_capture_groups.set(static_cast<OpCode_SaveLeftCaptureGroup const&>(opcode).id());
  329. break;
  330. case OpCodeId::Compare: {
  331. following_block_has_at_least_one_compare = true;
  332. // We found a compare, let's see what it has.
  333. auto compares = static_cast<OpCode_Compare const&>(opcode).flat_compares();
  334. if (compares.is_empty())
  335. break;
  336. if (any_of(compares, [&](auto& compare) {
  337. return compare.type == CharacterCompareType::AnyChar
  338. || (compare.type == CharacterCompareType::Reference && active_capture_groups.contains(compare.value));
  339. }))
  340. return AtomicRewritePreconditionResult::NotSatisfied;
  341. if (any_of(repeated_values, [&](auto& repeated_value) { return has_overlap(compares, repeated_value); }))
  342. return AtomicRewritePreconditionResult::NotSatisfied;
  343. return AtomicRewritePreconditionResult::SatisfiedWithProperHeader;
  344. }
  345. case OpCodeId::CheckBegin:
  346. case OpCodeId::CheckEnd:
  347. return AtomicRewritePreconditionResult::SatisfiedWithProperHeader; // Nothing can match the end!
  348. case OpCodeId::CheckBoundary:
  349. // FIXME: What should we do with these? For now, consider them a failure.
  350. return AtomicRewritePreconditionResult::NotSatisfied;
  351. case OpCodeId::ForkJump:
  352. case OpCodeId::ForkReplaceJump:
  353. case OpCodeId::JumpNonEmpty:
  354. // See note in the previous switch, same cases.
  355. if (!following_block_has_at_least_one_compare)
  356. return AtomicRewritePreconditionResult::NotSatisfied;
  357. break;
  358. default:
  359. break;
  360. }
  361. state.instruction_position += opcode.size();
  362. }
  363. if (following_block_has_at_least_one_compare)
  364. return AtomicRewritePreconditionResult::SatisfiedWithProperHeader;
  365. return AtomicRewritePreconditionResult::SatisfiedWithEmptyHeader;
  366. }
  367. template<typename Parser>
  368. void Regex<Parser>::attempt_rewrite_loops_as_atomic_groups(BasicBlockList const& basic_blocks)
  369. {
  370. auto& bytecode = parser_result.bytecode;
  371. if constexpr (REGEX_DEBUG) {
  372. RegexDebug dbg;
  373. dbg.print_bytecode(*this);
  374. for (auto const& block : basic_blocks)
  375. dbgln("block from {} to {}", block.start, block.end);
  376. }
  377. // A pattern such as:
  378. // bb0 | RE0
  379. // | ForkX bb0
  380. // -------------------------
  381. // bb1 | RE1
  382. // can be rewritten as:
  383. // -------------------------
  384. // bb0 | RE0
  385. // | ForkReplaceX bb0
  386. // -------------------------
  387. // bb1 | RE1
  388. // provided that first(RE1) not-in end(RE0), which is to say
  389. // that RE1 cannot start with whatever RE0 has matched (ever).
  390. //
  391. // Alternatively, a second form of this pattern can also occur:
  392. // bb0 | *
  393. // | ForkX bb2
  394. // ------------------------
  395. // bb1 | RE0
  396. // | Jump bb0
  397. // ------------------------
  398. // bb2 | RE1
  399. // which can be transformed (with the same preconditions) to:
  400. // bb0 | *
  401. // | ForkReplaceX bb2
  402. // ------------------------
  403. // bb1 | RE0
  404. // | Jump bb0
  405. // ------------------------
  406. // bb2 | RE1
  407. enum class AlternateForm {
  408. DirectLoopWithoutHeader, // loop without proper header, a block forking to itself. i.e. the first form.
  409. DirectLoopWithoutHeaderAndEmptyFollow, // loop without proper header, a block forking to itself. i.e. the first form but with RE1 being empty.
  410. DirectLoopWithHeader, // loop with proper header, i.e. the second form.
  411. };
  412. struct CandidateBlock {
  413. Block forking_block;
  414. Optional<Block> new_target_block;
  415. AlternateForm form;
  416. };
  417. Vector<CandidateBlock> candidate_blocks;
  418. auto is_an_eligible_jump = [](OpCode const& opcode, size_t ip, size_t block_start, AlternateForm alternate_form) {
  419. switch (opcode.opcode_id()) {
  420. case OpCodeId::JumpNonEmpty: {
  421. auto const& op = static_cast<OpCode_JumpNonEmpty const&>(opcode);
  422. auto form = op.form();
  423. if (form != OpCodeId::Jump && alternate_form == AlternateForm::DirectLoopWithHeader)
  424. return false;
  425. if (form != OpCodeId::ForkJump && form != OpCodeId::ForkStay && alternate_form == AlternateForm::DirectLoopWithoutHeader)
  426. return false;
  427. return op.offset() + ip + opcode.size() == block_start;
  428. }
  429. case OpCodeId::ForkJump:
  430. if (alternate_form == AlternateForm::DirectLoopWithHeader)
  431. return false;
  432. return static_cast<OpCode_ForkJump const&>(opcode).offset() + ip + opcode.size() == block_start;
  433. case OpCodeId::ForkStay:
  434. if (alternate_form == AlternateForm::DirectLoopWithHeader)
  435. return false;
  436. return static_cast<OpCode_ForkStay const&>(opcode).offset() + ip + opcode.size() == block_start;
  437. case OpCodeId::Jump:
  438. // Infinite loop does *not* produce forks.
  439. if (alternate_form == AlternateForm::DirectLoopWithoutHeader)
  440. return false;
  441. if (alternate_form == AlternateForm::DirectLoopWithHeader)
  442. return static_cast<OpCode_Jump const&>(opcode).offset() + ip + opcode.size() == block_start;
  443. VERIFY_NOT_REACHED();
  444. default:
  445. return false;
  446. }
  447. };
  448. for (size_t i = 0; i < basic_blocks.size(); ++i) {
  449. auto forking_block = basic_blocks[i];
  450. Optional<Block> fork_fallback_block;
  451. if (i + 1 < basic_blocks.size())
  452. fork_fallback_block = basic_blocks[i + 1];
  453. MatchState state;
  454. // Check if the last instruction in this block is a jump to the block itself:
  455. {
  456. state.instruction_position = forking_block.end;
  457. auto& opcode = bytecode.get_opcode(state);
  458. if (is_an_eligible_jump(opcode, state.instruction_position, forking_block.start, AlternateForm::DirectLoopWithoutHeader)) {
  459. // We've found RE0 (and RE1 is just the following block, if any), let's see if the precondition applies.
  460. // if RE1 is empty, there's no first(RE1), so this is an automatic pass.
  461. if (!fork_fallback_block.has_value()
  462. || (fork_fallback_block->end == fork_fallback_block->start && block_satisfies_atomic_rewrite_precondition(bytecode, forking_block, *fork_fallback_block) != AtomicRewritePreconditionResult::NotSatisfied)) {
  463. candidate_blocks.append({ forking_block, fork_fallback_block, AlternateForm::DirectLoopWithoutHeader });
  464. break;
  465. }
  466. auto precondition = block_satisfies_atomic_rewrite_precondition(bytecode, forking_block, *fork_fallback_block);
  467. if (precondition == AtomicRewritePreconditionResult::SatisfiedWithProperHeader) {
  468. candidate_blocks.append({ forking_block, fork_fallback_block, AlternateForm::DirectLoopWithoutHeader });
  469. break;
  470. }
  471. if (precondition == AtomicRewritePreconditionResult::SatisfiedWithEmptyHeader) {
  472. candidate_blocks.append({ forking_block, fork_fallback_block, AlternateForm::DirectLoopWithoutHeaderAndEmptyFollow });
  473. break;
  474. }
  475. }
  476. }
  477. // Check if the last instruction in the last block is a direct jump to this block
  478. if (fork_fallback_block.has_value()) {
  479. state.instruction_position = fork_fallback_block->end;
  480. auto& opcode = bytecode.get_opcode(state);
  481. if (is_an_eligible_jump(opcode, state.instruction_position, forking_block.start, AlternateForm::DirectLoopWithHeader)) {
  482. // We've found bb1 and bb0, let's just make sure that bb0 forks to bb2.
  483. state.instruction_position = forking_block.end;
  484. auto& opcode = bytecode.get_opcode(state);
  485. if (opcode.opcode_id() == OpCodeId::ForkJump || opcode.opcode_id() == OpCodeId::ForkStay) {
  486. Optional<Block> block_following_fork_fallback;
  487. if (i + 2 < basic_blocks.size())
  488. block_following_fork_fallback = basic_blocks[i + 2];
  489. if (!block_following_fork_fallback.has_value()
  490. || block_satisfies_atomic_rewrite_precondition(bytecode, *fork_fallback_block, *block_following_fork_fallback) != AtomicRewritePreconditionResult::NotSatisfied) {
  491. candidate_blocks.append({ forking_block, {}, AlternateForm::DirectLoopWithHeader });
  492. break;
  493. }
  494. }
  495. }
  496. }
  497. }
  498. dbgln_if(REGEX_DEBUG, "Found {} candidate blocks", candidate_blocks.size());
  499. if (candidate_blocks.is_empty()) {
  500. dbgln_if(REGEX_DEBUG, "Failed to find anything for {}", pattern_value);
  501. return;
  502. }
  503. RedBlackTree<size_t, size_t> needed_patches;
  504. // Reverse the blocks, so we can patch the bytecode without messing with the latter patches.
  505. quick_sort(candidate_blocks, [](auto& a, auto& b) { return b.forking_block.start > a.forking_block.start; });
  506. for (auto& candidate : candidate_blocks) {
  507. // Note that both forms share a ForkReplace patch in forking_block.
  508. // Patch the ForkX in forking_block to be a ForkReplaceX instead.
  509. auto& opcode_id = bytecode[candidate.forking_block.end];
  510. if (opcode_id == (ByteCodeValueType)OpCodeId::ForkStay) {
  511. opcode_id = (ByteCodeValueType)OpCodeId::ForkReplaceStay;
  512. } else if (opcode_id == (ByteCodeValueType)OpCodeId::ForkJump) {
  513. opcode_id = (ByteCodeValueType)OpCodeId::ForkReplaceJump;
  514. } else if (opcode_id == (ByteCodeValueType)OpCodeId::JumpNonEmpty) {
  515. auto& jump_opcode_id = bytecode[candidate.forking_block.end + 3];
  516. if (jump_opcode_id == (ByteCodeValueType)OpCodeId::ForkStay)
  517. jump_opcode_id = (ByteCodeValueType)OpCodeId::ForkReplaceStay;
  518. else if (jump_opcode_id == (ByteCodeValueType)OpCodeId::ForkJump)
  519. jump_opcode_id = (ByteCodeValueType)OpCodeId::ForkReplaceJump;
  520. else
  521. VERIFY_NOT_REACHED();
  522. } else {
  523. VERIFY_NOT_REACHED();
  524. }
  525. }
  526. if (!needed_patches.is_empty()) {
  527. MatchState state;
  528. auto bytecode_size = bytecode.size();
  529. state.instruction_position = 0;
  530. struct Patch {
  531. ssize_t value;
  532. size_t offset;
  533. bool should_negate { false };
  534. };
  535. for (;;) {
  536. if (state.instruction_position >= bytecode_size)
  537. break;
  538. auto& opcode = bytecode.get_opcode(state);
  539. Stack<Patch, 2> patch_points;
  540. switch (opcode.opcode_id()) {
  541. case OpCodeId::Jump:
  542. patch_points.push({ static_cast<OpCode_Jump const&>(opcode).offset(), state.instruction_position + 1 });
  543. break;
  544. case OpCodeId::JumpNonEmpty:
  545. patch_points.push({ static_cast<OpCode_JumpNonEmpty const&>(opcode).offset(), state.instruction_position + 1 });
  546. patch_points.push({ static_cast<OpCode_JumpNonEmpty const&>(opcode).checkpoint(), state.instruction_position + 2 });
  547. break;
  548. case OpCodeId::ForkJump:
  549. patch_points.push({ static_cast<OpCode_ForkJump const&>(opcode).offset(), state.instruction_position + 1 });
  550. break;
  551. case OpCodeId::ForkStay:
  552. patch_points.push({ static_cast<OpCode_ForkStay const&>(opcode).offset(), state.instruction_position + 1 });
  553. break;
  554. case OpCodeId::Repeat:
  555. patch_points.push({ -(ssize_t) static_cast<OpCode_Repeat const&>(opcode).offset(), state.instruction_position + 1, true });
  556. break;
  557. default:
  558. break;
  559. }
  560. while (!patch_points.is_empty()) {
  561. auto& patch_point = patch_points.top();
  562. auto target_offset = patch_point.value + state.instruction_position + opcode.size();
  563. constexpr auto do_patch = [](auto& patch_it, auto& patch_point, auto& target_offset, auto& bytecode, auto ip) {
  564. if (patch_it.key() == ip)
  565. return;
  566. if (patch_point.value < 0 && target_offset <= patch_it.key() && ip > patch_it.key())
  567. bytecode[patch_point.offset] += (patch_point.should_negate ? 1 : -1) * (*patch_it);
  568. else if (patch_point.value > 0 && target_offset >= patch_it.key() && ip < patch_it.key())
  569. bytecode[patch_point.offset] += (patch_point.should_negate ? -1 : 1) * (*patch_it);
  570. };
  571. if (auto patch_it = needed_patches.find_largest_not_above_iterator(target_offset); !patch_it.is_end())
  572. do_patch(patch_it, patch_point, target_offset, bytecode, state.instruction_position);
  573. else if (auto patch_it = needed_patches.find_largest_not_above_iterator(state.instruction_position); !patch_it.is_end())
  574. do_patch(patch_it, patch_point, target_offset, bytecode, state.instruction_position);
  575. patch_points.pop();
  576. }
  577. state.instruction_position += opcode.size();
  578. }
  579. }
  580. if constexpr (REGEX_DEBUG) {
  581. warnln("Transformed to:");
  582. RegexDebug dbg;
  583. dbg.print_bytecode(*this);
  584. }
  585. }
  586. void Optimizer::append_alternation(ByteCode& target, ByteCode&& left, ByteCode&& right)
  587. {
  588. Array<ByteCode, 2> alternatives;
  589. alternatives[0] = move(left);
  590. alternatives[1] = move(right);
  591. append_alternation(target, alternatives);
  592. }
  593. void Optimizer::append_alternation(ByteCode& target, Span<ByteCode> alternatives)
  594. {
  595. if (alternatives.size() == 0)
  596. return;
  597. if (alternatives.size() == 1)
  598. return target.extend(move(alternatives[0]));
  599. if (all_of(alternatives, [](auto& x) { return x.is_empty(); }))
  600. return;
  601. for (auto& entry : alternatives)
  602. entry.flatten();
  603. #if REGEX_DEBUG
  604. ScopeLogger<true> log;
  605. warnln("Alternations:");
  606. RegexDebug dbg;
  607. for (auto& entry : alternatives) {
  608. warnln("----------");
  609. dbg.print_bytecode(entry);
  610. }
  611. ScopeGuard print_at_end {
  612. [&] {
  613. warnln("======================");
  614. RegexDebug dbg;
  615. dbg.print_bytecode(target);
  616. }
  617. };
  618. #endif
  619. Vector<Vector<Detail::Block>> basic_blocks;
  620. basic_blocks.ensure_capacity(alternatives.size());
  621. for (auto& entry : alternatives)
  622. basic_blocks.append(Regex<PosixBasicParser>::split_basic_blocks(entry));
  623. size_t left_skip = 0;
  624. size_t shared_block_count = basic_blocks.first().size();
  625. for (auto& entry : basic_blocks)
  626. shared_block_count = min(shared_block_count, entry.size());
  627. MatchState state;
  628. for (size_t block_index = 0; block_index < shared_block_count; block_index++) {
  629. auto& left_block = basic_blocks.first()[block_index];
  630. auto left_end = block_index + 1 == basic_blocks.first().size() ? left_block.end : basic_blocks.first()[block_index + 1].start;
  631. auto can_continue = true;
  632. for (size_t i = 1; i < alternatives.size(); ++i) {
  633. auto& right_blocks = basic_blocks[i];
  634. auto& right_block = right_blocks[block_index];
  635. auto right_end = block_index + 1 == right_blocks.size() ? right_block.end : right_blocks[block_index + 1].start;
  636. if (left_end - left_block.start != right_end - right_block.start) {
  637. can_continue = false;
  638. break;
  639. }
  640. if (alternatives[0].spans().slice(left_block.start, left_end - left_block.start) != alternatives[i].spans().slice(right_block.start, right_end - right_block.start)) {
  641. can_continue = false;
  642. break;
  643. }
  644. }
  645. if (!can_continue)
  646. break;
  647. size_t i = 0;
  648. for (auto& entry : alternatives) {
  649. auto& blocks = basic_blocks[i];
  650. auto& block = blocks[block_index];
  651. auto end = block_index + 1 == blocks.size() ? block.end : blocks[block_index + 1].start;
  652. state.instruction_position = block.start;
  653. size_t skip = 0;
  654. while (state.instruction_position < end) {
  655. auto& opcode = entry.get_opcode(state);
  656. state.instruction_position += opcode.size();
  657. skip = state.instruction_position;
  658. }
  659. left_skip = min(skip, left_skip);
  660. }
  661. }
  662. dbgln_if(REGEX_DEBUG, "Skipping {}/{} bytecode entries from {}", left_skip, 0, alternatives[0].size());
  663. if (left_skip > 0) {
  664. target.extend(alternatives[0].release_slice(basic_blocks.first().first().start, left_skip));
  665. auto first = true;
  666. for (auto& entry : alternatives) {
  667. if (first) {
  668. first = false;
  669. continue;
  670. }
  671. entry = entry.release_slice(left_skip);
  672. }
  673. }
  674. if (all_of(alternatives, [](auto& entry) { return entry.is_empty(); }))
  675. return;
  676. size_t patch_start = target.size();
  677. for (size_t i = 1; i < alternatives.size(); ++i) {
  678. target.empend(static_cast<ByteCodeValueType>(OpCodeId::ForkJump));
  679. target.empend(0u); // To be filled later.
  680. }
  681. size_t size_to_jump = 0;
  682. bool seen_one_empty = false;
  683. for (size_t i = alternatives.size(); i > 0; --i) {
  684. auto& entry = alternatives[i - 1];
  685. if (entry.is_empty()) {
  686. if (seen_one_empty)
  687. continue;
  688. seen_one_empty = true;
  689. }
  690. auto is_first = i == 1;
  691. auto instruction_size = entry.size() + (is_first ? 0 : 2); // Jump; -> +2
  692. size_to_jump += instruction_size;
  693. if (!is_first)
  694. target[patch_start + (i - 2) * 2 + 1] = size_to_jump + (alternatives.size() - i) * 2;
  695. dbgln_if(REGEX_DEBUG, "{} size = {}, cum={}", i - 1, instruction_size, size_to_jump);
  696. }
  697. seen_one_empty = false;
  698. for (size_t i = alternatives.size(); i > 0; --i) {
  699. auto& chunk = alternatives[i - 1];
  700. if (chunk.is_empty()) {
  701. if (seen_one_empty)
  702. continue;
  703. seen_one_empty = true;
  704. }
  705. ByteCode* previous_chunk = nullptr;
  706. size_t j = i - 1;
  707. auto seen_one_empty_before = chunk.is_empty();
  708. while (j >= 1) {
  709. --j;
  710. auto& candidate_chunk = alternatives[j];
  711. if (candidate_chunk.is_empty()) {
  712. if (seen_one_empty_before)
  713. continue;
  714. }
  715. previous_chunk = &candidate_chunk;
  716. break;
  717. }
  718. size_to_jump -= chunk.size() + (previous_chunk ? 2 : 0);
  719. target.extend(move(chunk));
  720. target.empend(static_cast<ByteCodeValueType>(OpCodeId::Jump));
  721. target.empend(size_to_jump); // Jump to the _END label
  722. }
  723. }
  724. enum class LookupTableInsertionOutcome {
  725. Successful,
  726. ReplaceWithAnyChar,
  727. TemporaryInversionNeeded,
  728. PermanentInversionNeeded,
  729. FlushOnInsertion,
  730. FinishFlushOnInsertion,
  731. CannotPlaceInTable,
  732. };
  733. static LookupTableInsertionOutcome insert_into_lookup_table(RedBlackTree<ByteCodeValueType, CharRange>& table, CompareTypeAndValuePair pair)
  734. {
  735. switch (pair.type) {
  736. case CharacterCompareType::Inverse:
  737. return LookupTableInsertionOutcome::PermanentInversionNeeded;
  738. case CharacterCompareType::TemporaryInverse:
  739. return LookupTableInsertionOutcome::TemporaryInversionNeeded;
  740. case CharacterCompareType::AnyChar:
  741. return LookupTableInsertionOutcome::ReplaceWithAnyChar;
  742. case CharacterCompareType::CharClass:
  743. return LookupTableInsertionOutcome::CannotPlaceInTable;
  744. case CharacterCompareType::Char:
  745. table.insert(pair.value, { (u32)pair.value, (u32)pair.value });
  746. break;
  747. case CharacterCompareType::CharRange: {
  748. CharRange range { pair.value };
  749. table.insert(range.from, range);
  750. break;
  751. }
  752. case CharacterCompareType::EndAndOr:
  753. return LookupTableInsertionOutcome::FinishFlushOnInsertion;
  754. case CharacterCompareType::And:
  755. return LookupTableInsertionOutcome::FlushOnInsertion;
  756. case CharacterCompareType::Reference:
  757. case CharacterCompareType::Property:
  758. case CharacterCompareType::GeneralCategory:
  759. case CharacterCompareType::Script:
  760. case CharacterCompareType::ScriptExtension:
  761. case CharacterCompareType::Or:
  762. return LookupTableInsertionOutcome::CannotPlaceInTable;
  763. case CharacterCompareType::Undefined:
  764. case CharacterCompareType::RangeExpressionDummy:
  765. case CharacterCompareType::String:
  766. case CharacterCompareType::LookupTable:
  767. VERIFY_NOT_REACHED();
  768. }
  769. return LookupTableInsertionOutcome::Successful;
  770. }
  771. void Optimizer::append_character_class(ByteCode& target, Vector<CompareTypeAndValuePair>&& pairs)
  772. {
  773. ByteCode arguments;
  774. size_t argument_count = 0;
  775. if (pairs.size() <= 1) {
  776. for (auto& pair : pairs) {
  777. arguments.append(to_underlying(pair.type));
  778. if (pair.type != CharacterCompareType::AnyChar
  779. && pair.type != CharacterCompareType::TemporaryInverse
  780. && pair.type != CharacterCompareType::Inverse
  781. && pair.type != CharacterCompareType::And
  782. && pair.type != CharacterCompareType::Or
  783. && pair.type != CharacterCompareType::EndAndOr)
  784. arguments.append(pair.value);
  785. ++argument_count;
  786. }
  787. } else {
  788. RedBlackTree<ByteCodeValueType, CharRange> table;
  789. RedBlackTree<ByteCodeValueType, CharRange> inverted_table;
  790. auto* current_table = &table;
  791. auto* current_inverted_table = &inverted_table;
  792. bool invert_for_next_iteration = false;
  793. bool is_currently_inverted = false;
  794. auto flush_tables = [&] {
  795. auto append_table = [&](auto& table) {
  796. ++argument_count;
  797. arguments.append(to_underlying(CharacterCompareType::LookupTable));
  798. auto size_index = arguments.size();
  799. arguments.append(0);
  800. Optional<CharRange> active_range;
  801. size_t range_count = 0;
  802. for (auto& range : table) {
  803. if (!active_range.has_value()) {
  804. active_range = range;
  805. continue;
  806. }
  807. if (range.from <= active_range->to + 1 && range.to + 1 >= active_range->from) {
  808. active_range = CharRange { min(range.from, active_range->from), max(range.to, active_range->to) };
  809. } else {
  810. ++range_count;
  811. arguments.append(active_range.release_value());
  812. active_range = range;
  813. }
  814. }
  815. if (active_range.has_value()) {
  816. ++range_count;
  817. arguments.append(active_range.release_value());
  818. }
  819. arguments[size_index] = range_count;
  820. };
  821. auto contains_regular_table = !table.is_empty();
  822. auto contains_inverted_table = !inverted_table.is_empty();
  823. if (contains_regular_table)
  824. append_table(table);
  825. if (contains_inverted_table) {
  826. ++argument_count;
  827. arguments.append(to_underlying(CharacterCompareType::TemporaryInverse));
  828. append_table(inverted_table);
  829. }
  830. table.clear();
  831. inverted_table.clear();
  832. };
  833. auto flush_on_every_insertion = false;
  834. for (auto& value : pairs) {
  835. auto should_invert_after_this_iteration = invert_for_next_iteration;
  836. invert_for_next_iteration = false;
  837. auto insertion_result = insert_into_lookup_table(*current_table, value);
  838. switch (insertion_result) {
  839. case LookupTableInsertionOutcome::Successful:
  840. if (flush_on_every_insertion)
  841. flush_tables();
  842. break;
  843. case LookupTableInsertionOutcome::ReplaceWithAnyChar: {
  844. table.clear();
  845. inverted_table.clear();
  846. arguments.append(to_underlying(CharacterCompareType::AnyChar));
  847. ++argument_count;
  848. break;
  849. }
  850. case LookupTableInsertionOutcome::TemporaryInversionNeeded:
  851. swap(current_table, current_inverted_table);
  852. invert_for_next_iteration = true;
  853. is_currently_inverted = !is_currently_inverted;
  854. break;
  855. case LookupTableInsertionOutcome::PermanentInversionNeeded:
  856. flush_tables();
  857. arguments.append(to_underlying(CharacterCompareType::Inverse));
  858. ++argument_count;
  859. break;
  860. case LookupTableInsertionOutcome::FlushOnInsertion:
  861. case LookupTableInsertionOutcome::FinishFlushOnInsertion:
  862. flush_tables();
  863. flush_on_every_insertion = insertion_result == LookupTableInsertionOutcome::FlushOnInsertion;
  864. [[fallthrough]];
  865. case LookupTableInsertionOutcome::CannotPlaceInTable:
  866. if (is_currently_inverted) {
  867. arguments.append(to_underlying(CharacterCompareType::TemporaryInverse));
  868. ++argument_count;
  869. }
  870. arguments.append(to_underlying(value.type));
  871. if (value.type != CharacterCompareType::AnyChar
  872. && value.type != CharacterCompareType::TemporaryInverse
  873. && value.type != CharacterCompareType::Inverse
  874. && value.type != CharacterCompareType::And
  875. && value.type != CharacterCompareType::Or
  876. && value.type != CharacterCompareType::EndAndOr)
  877. arguments.append(value.value);
  878. ++argument_count;
  879. break;
  880. }
  881. if (should_invert_after_this_iteration) {
  882. swap(current_table, current_inverted_table);
  883. is_currently_inverted = !is_currently_inverted;
  884. }
  885. }
  886. flush_tables();
  887. }
  888. target.empend(static_cast<ByteCodeValueType>(OpCodeId::Compare));
  889. target.empend(argument_count); // number of arguments
  890. target.empend(arguments.size()); // size of arguments
  891. target.extend(move(arguments));
  892. }
  893. template void Regex<PosixBasicParser>::run_optimization_passes();
  894. template void Regex<PosixExtendedParser>::run_optimization_passes();
  895. template void Regex<ECMA262Parser>::run_optimization_passes();
  896. }