RegexOptimizer.cpp 40 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977
  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. for (state.instruction_position = repeated_block.start; state.instruction_position < repeated_block.end;) {
  275. auto& opcode = bytecode.get_opcode(state);
  276. switch (opcode.opcode_id()) {
  277. case OpCodeId::Compare: {
  278. auto compares = static_cast<OpCode_Compare const&>(opcode).flat_compares();
  279. if (repeated_values.is_empty() && any_of(compares, [](auto& compare) { return compare.type == CharacterCompareType::AnyChar; }))
  280. return AtomicRewritePreconditionResult::NotSatisfied;
  281. repeated_values.append(move(compares));
  282. break;
  283. }
  284. case OpCodeId::CheckBegin:
  285. case OpCodeId::CheckEnd:
  286. if (repeated_values.is_empty())
  287. return AtomicRewritePreconditionResult::SatisfiedWithProperHeader;
  288. break;
  289. case OpCodeId::CheckBoundary:
  290. // FIXME: What should we do with these? for now, let's fail.
  291. return AtomicRewritePreconditionResult::NotSatisfied;
  292. case OpCodeId::Restore:
  293. case OpCodeId::GoBack:
  294. return AtomicRewritePreconditionResult::NotSatisfied;
  295. case OpCodeId::SaveRightCaptureGroup:
  296. active_capture_groups.set(static_cast<OpCode_SaveRightCaptureGroup const&>(opcode).id());
  297. break;
  298. case OpCodeId::SaveLeftCaptureGroup:
  299. active_capture_groups.set(static_cast<OpCode_SaveLeftCaptureGroup const&>(opcode).id());
  300. break;
  301. default:
  302. break;
  303. }
  304. state.instruction_position += opcode.size();
  305. }
  306. dbgln_if(REGEX_DEBUG, "Found {} entries in reference", repeated_values.size());
  307. dbgln_if(REGEX_DEBUG, "Found {} active capture groups", active_capture_groups.size());
  308. bool following_block_has_at_least_one_compare = false;
  309. // Find the first compare in the following block, it must NOT match any of the values in `repeated_values'.
  310. for (state.instruction_position = following_block.start; state.instruction_position < following_block.end;) {
  311. auto& opcode = bytecode.get_opcode(state);
  312. switch (opcode.opcode_id()) {
  313. // Note: These have to exist since we're effectively repeating the following block as well
  314. case OpCodeId::SaveRightCaptureGroup:
  315. active_capture_groups.set(static_cast<OpCode_SaveRightCaptureGroup const&>(opcode).id());
  316. break;
  317. case OpCodeId::SaveLeftCaptureGroup:
  318. active_capture_groups.set(static_cast<OpCode_SaveLeftCaptureGroup const&>(opcode).id());
  319. break;
  320. case OpCodeId::Compare: {
  321. following_block_has_at_least_one_compare = true;
  322. // We found a compare, let's see what it has.
  323. auto compares = static_cast<OpCode_Compare const&>(opcode).flat_compares();
  324. if (compares.is_empty())
  325. break;
  326. if (any_of(compares, [&](auto& compare) {
  327. return compare.type == CharacterCompareType::AnyChar
  328. || (compare.type == CharacterCompareType::Reference && active_capture_groups.contains(compare.value));
  329. }))
  330. return AtomicRewritePreconditionResult::NotSatisfied;
  331. if (any_of(repeated_values, [&](auto& repeated_value) { return has_overlap(compares, repeated_value); }))
  332. return AtomicRewritePreconditionResult::NotSatisfied;
  333. return AtomicRewritePreconditionResult::SatisfiedWithProperHeader;
  334. }
  335. case OpCodeId::CheckBegin:
  336. case OpCodeId::CheckEnd:
  337. return AtomicRewritePreconditionResult::SatisfiedWithProperHeader; // Nothing can match the end!
  338. case OpCodeId::CheckBoundary:
  339. // FIXME: What should we do with these? For now, consider them a failure.
  340. return AtomicRewritePreconditionResult::NotSatisfied;
  341. default:
  342. break;
  343. }
  344. state.instruction_position += opcode.size();
  345. }
  346. if (following_block_has_at_least_one_compare)
  347. return AtomicRewritePreconditionResult::SatisfiedWithProperHeader;
  348. return AtomicRewritePreconditionResult::SatisfiedWithEmptyHeader;
  349. }
  350. template<typename Parser>
  351. void Regex<Parser>::attempt_rewrite_loops_as_atomic_groups(BasicBlockList const& basic_blocks)
  352. {
  353. auto& bytecode = parser_result.bytecode;
  354. if constexpr (REGEX_DEBUG) {
  355. RegexDebug dbg;
  356. dbg.print_bytecode(*this);
  357. for (auto const& block : basic_blocks)
  358. dbgln("block from {} to {}", block.start, block.end);
  359. }
  360. // A pattern such as:
  361. // bb0 | RE0
  362. // | ForkX bb0
  363. // -------------------------
  364. // bb1 | RE1
  365. // can be rewritten as:
  366. // -------------------------
  367. // bb0 | RE0
  368. // | ForkReplaceX bb0
  369. // -------------------------
  370. // bb1 | RE1
  371. // provided that first(RE1) not-in end(RE0), which is to say
  372. // that RE1 cannot start with whatever RE0 has matched (ever).
  373. //
  374. // Alternatively, a second form of this pattern can also occur:
  375. // bb0 | *
  376. // | ForkX bb2
  377. // ------------------------
  378. // bb1 | RE0
  379. // | Jump bb0
  380. // ------------------------
  381. // bb2 | RE1
  382. // which can be transformed (with the same preconditions) to:
  383. // bb0 | *
  384. // | ForkReplaceX bb2
  385. // ------------------------
  386. // bb1 | RE0
  387. // | Jump bb0
  388. // ------------------------
  389. // bb2 | RE1
  390. enum class AlternateForm {
  391. DirectLoopWithoutHeader, // loop without proper header, a block forking to itself. i.e. the first form.
  392. DirectLoopWithoutHeaderAndEmptyFollow, // loop without proper header, a block forking to itself. i.e. the first form but with RE1 being empty.
  393. DirectLoopWithHeader, // loop with proper header, i.e. the second form.
  394. };
  395. struct CandidateBlock {
  396. Block forking_block;
  397. Optional<Block> new_target_block;
  398. AlternateForm form;
  399. };
  400. Vector<CandidateBlock> candidate_blocks;
  401. auto is_an_eligible_jump = [](OpCode const& opcode, size_t ip, size_t block_start, AlternateForm alternate_form) {
  402. switch (opcode.opcode_id()) {
  403. case OpCodeId::JumpNonEmpty: {
  404. auto const& op = static_cast<OpCode_JumpNonEmpty const&>(opcode);
  405. auto form = op.form();
  406. if (form != OpCodeId::Jump && alternate_form == AlternateForm::DirectLoopWithHeader)
  407. return false;
  408. if (form != OpCodeId::ForkJump && form != OpCodeId::ForkStay && alternate_form == AlternateForm::DirectLoopWithoutHeader)
  409. return false;
  410. return op.offset() + ip + opcode.size() == block_start;
  411. }
  412. case OpCodeId::ForkJump:
  413. if (alternate_form == AlternateForm::DirectLoopWithHeader)
  414. return false;
  415. return static_cast<OpCode_ForkJump const&>(opcode).offset() + ip + opcode.size() == block_start;
  416. case OpCodeId::ForkStay:
  417. if (alternate_form == AlternateForm::DirectLoopWithHeader)
  418. return false;
  419. return static_cast<OpCode_ForkStay const&>(opcode).offset() + ip + opcode.size() == block_start;
  420. case OpCodeId::Jump:
  421. // Infinite loop does *not* produce forks.
  422. if (alternate_form == AlternateForm::DirectLoopWithoutHeader)
  423. return false;
  424. if (alternate_form == AlternateForm::DirectLoopWithHeader)
  425. return static_cast<OpCode_Jump const&>(opcode).offset() + ip + opcode.size() == block_start;
  426. VERIFY_NOT_REACHED();
  427. default:
  428. return false;
  429. }
  430. };
  431. for (size_t i = 0; i < basic_blocks.size(); ++i) {
  432. auto forking_block = basic_blocks[i];
  433. Optional<Block> fork_fallback_block;
  434. if (i + 1 < basic_blocks.size())
  435. fork_fallback_block = basic_blocks[i + 1];
  436. MatchState state;
  437. // Check if the last instruction in this block is a jump to the block itself:
  438. {
  439. state.instruction_position = forking_block.end;
  440. auto& opcode = bytecode.get_opcode(state);
  441. if (is_an_eligible_jump(opcode, state.instruction_position, forking_block.start, AlternateForm::DirectLoopWithoutHeader)) {
  442. // We've found RE0 (and RE1 is just the following block, if any), let's see if the precondition applies.
  443. // if RE1 is empty, there's no first(RE1), so this is an automatic pass.
  444. if (!fork_fallback_block.has_value() || fork_fallback_block->end == fork_fallback_block->start) {
  445. candidate_blocks.append({ forking_block, fork_fallback_block, AlternateForm::DirectLoopWithoutHeader });
  446. break;
  447. }
  448. auto precondition = block_satisfies_atomic_rewrite_precondition(bytecode, forking_block, *fork_fallback_block);
  449. if (precondition == AtomicRewritePreconditionResult::SatisfiedWithProperHeader) {
  450. candidate_blocks.append({ forking_block, fork_fallback_block, AlternateForm::DirectLoopWithoutHeader });
  451. break;
  452. }
  453. if (precondition == AtomicRewritePreconditionResult::SatisfiedWithEmptyHeader) {
  454. candidate_blocks.append({ forking_block, fork_fallback_block, AlternateForm::DirectLoopWithoutHeaderAndEmptyFollow });
  455. break;
  456. }
  457. }
  458. }
  459. // Check if the last instruction in the last block is a direct jump to this block
  460. if (fork_fallback_block.has_value()) {
  461. state.instruction_position = fork_fallback_block->end;
  462. auto& opcode = bytecode.get_opcode(state);
  463. if (is_an_eligible_jump(opcode, state.instruction_position, forking_block.start, AlternateForm::DirectLoopWithHeader)) {
  464. // We've found bb1 and bb0, let's just make sure that bb0 forks to bb2.
  465. state.instruction_position = forking_block.end;
  466. auto& opcode = bytecode.get_opcode(state);
  467. if (opcode.opcode_id() == OpCodeId::ForkJump || opcode.opcode_id() == OpCodeId::ForkStay) {
  468. Optional<Block> block_following_fork_fallback;
  469. if (i + 2 < basic_blocks.size())
  470. block_following_fork_fallback = basic_blocks[i + 2];
  471. if (!block_following_fork_fallback.has_value()
  472. || block_satisfies_atomic_rewrite_precondition(bytecode, *fork_fallback_block, *block_following_fork_fallback) != AtomicRewritePreconditionResult::NotSatisfied) {
  473. candidate_blocks.append({ forking_block, {}, AlternateForm::DirectLoopWithHeader });
  474. break;
  475. }
  476. }
  477. }
  478. }
  479. }
  480. dbgln_if(REGEX_DEBUG, "Found {} candidate blocks", candidate_blocks.size());
  481. if (candidate_blocks.is_empty()) {
  482. dbgln_if(REGEX_DEBUG, "Failed to find anything for {}", pattern_value);
  483. return;
  484. }
  485. RedBlackTree<size_t, size_t> needed_patches;
  486. // Reverse the blocks, so we can patch the bytecode without messing with the latter patches.
  487. quick_sort(candidate_blocks, [](auto& a, auto& b) { return b.forking_block.start > a.forking_block.start; });
  488. for (auto& candidate : candidate_blocks) {
  489. // Note that both forms share a ForkReplace patch in forking_block.
  490. // Patch the ForkX in forking_block to be a ForkReplaceX instead.
  491. auto& opcode_id = bytecode[candidate.forking_block.end];
  492. if (opcode_id == (ByteCodeValueType)OpCodeId::ForkStay) {
  493. opcode_id = (ByteCodeValueType)OpCodeId::ForkReplaceStay;
  494. } else if (opcode_id == (ByteCodeValueType)OpCodeId::ForkJump) {
  495. opcode_id = (ByteCodeValueType)OpCodeId::ForkReplaceJump;
  496. } else if (opcode_id == (ByteCodeValueType)OpCodeId::JumpNonEmpty) {
  497. auto& jump_opcode_id = bytecode[candidate.forking_block.end + 3];
  498. if (jump_opcode_id == (ByteCodeValueType)OpCodeId::ForkStay)
  499. jump_opcode_id = (ByteCodeValueType)OpCodeId::ForkReplaceStay;
  500. else if (jump_opcode_id == (ByteCodeValueType)OpCodeId::ForkJump)
  501. jump_opcode_id = (ByteCodeValueType)OpCodeId::ForkReplaceJump;
  502. else
  503. VERIFY_NOT_REACHED();
  504. } else {
  505. VERIFY_NOT_REACHED();
  506. }
  507. }
  508. if (!needed_patches.is_empty()) {
  509. MatchState state;
  510. auto bytecode_size = bytecode.size();
  511. state.instruction_position = 0;
  512. struct Patch {
  513. ssize_t value;
  514. size_t offset;
  515. bool should_negate { false };
  516. };
  517. for (;;) {
  518. if (state.instruction_position >= bytecode_size)
  519. break;
  520. auto& opcode = bytecode.get_opcode(state);
  521. Stack<Patch, 2> patch_points;
  522. switch (opcode.opcode_id()) {
  523. case OpCodeId::Jump:
  524. patch_points.push({ static_cast<OpCode_Jump const&>(opcode).offset(), state.instruction_position + 1 });
  525. break;
  526. case OpCodeId::JumpNonEmpty:
  527. patch_points.push({ static_cast<OpCode_JumpNonEmpty const&>(opcode).offset(), state.instruction_position + 1 });
  528. patch_points.push({ static_cast<OpCode_JumpNonEmpty const&>(opcode).checkpoint(), state.instruction_position + 2 });
  529. break;
  530. case OpCodeId::ForkJump:
  531. patch_points.push({ static_cast<OpCode_ForkJump const&>(opcode).offset(), state.instruction_position + 1 });
  532. break;
  533. case OpCodeId::ForkStay:
  534. patch_points.push({ static_cast<OpCode_ForkStay const&>(opcode).offset(), state.instruction_position + 1 });
  535. break;
  536. case OpCodeId::Repeat:
  537. patch_points.push({ -(ssize_t) static_cast<OpCode_Repeat const&>(opcode).offset(), state.instruction_position + 1, true });
  538. break;
  539. default:
  540. break;
  541. }
  542. while (!patch_points.is_empty()) {
  543. auto& patch_point = patch_points.top();
  544. auto target_offset = patch_point.value + state.instruction_position + opcode.size();
  545. constexpr auto do_patch = [](auto& patch_it, auto& patch_point, auto& target_offset, auto& bytecode, auto ip) {
  546. if (patch_it.key() == ip)
  547. return;
  548. if (patch_point.value < 0 && target_offset <= patch_it.key() && ip > patch_it.key())
  549. bytecode[patch_point.offset] += (patch_point.should_negate ? 1 : -1) * (*patch_it);
  550. else if (patch_point.value > 0 && target_offset >= patch_it.key() && ip < patch_it.key())
  551. bytecode[patch_point.offset] += (patch_point.should_negate ? -1 : 1) * (*patch_it);
  552. };
  553. if (auto patch_it = needed_patches.find_largest_not_above_iterator(target_offset); !patch_it.is_end())
  554. do_patch(patch_it, patch_point, target_offset, bytecode, state.instruction_position);
  555. else if (auto patch_it = needed_patches.find_largest_not_above_iterator(state.instruction_position); !patch_it.is_end())
  556. do_patch(patch_it, patch_point, target_offset, bytecode, state.instruction_position);
  557. patch_points.pop();
  558. }
  559. state.instruction_position += opcode.size();
  560. }
  561. }
  562. if constexpr (REGEX_DEBUG) {
  563. warnln("Transformed to:");
  564. RegexDebug dbg;
  565. dbg.print_bytecode(*this);
  566. }
  567. }
  568. void Optimizer::append_alternation(ByteCode& target, ByteCode&& left, ByteCode&& right)
  569. {
  570. Array<ByteCode, 2> alternatives;
  571. alternatives[0] = move(left);
  572. alternatives[1] = move(right);
  573. append_alternation(target, alternatives);
  574. }
  575. void Optimizer::append_alternation(ByteCode& target, Span<ByteCode> alternatives)
  576. {
  577. if (alternatives.size() == 0)
  578. return;
  579. if (alternatives.size() == 1)
  580. return target.extend(move(alternatives[0]));
  581. if (all_of(alternatives, [](auto& x) { return x.is_empty(); }))
  582. return;
  583. for (auto& entry : alternatives)
  584. entry.flatten();
  585. #if REGEX_DEBUG
  586. ScopeLogger<true> log;
  587. warnln("Alternations:");
  588. RegexDebug dbg;
  589. for (auto& entry : alternatives) {
  590. warnln("----------");
  591. dbg.print_bytecode(entry);
  592. }
  593. ScopeGuard print_at_end {
  594. [&] {
  595. warnln("======================");
  596. RegexDebug dbg;
  597. dbg.print_bytecode(target);
  598. }
  599. };
  600. #endif
  601. Vector<Vector<Detail::Block>> basic_blocks;
  602. basic_blocks.ensure_capacity(alternatives.size());
  603. for (auto& entry : alternatives)
  604. basic_blocks.append(Regex<PosixBasicParser>::split_basic_blocks(entry));
  605. size_t left_skip = 0;
  606. size_t shared_block_count = basic_blocks.first().size();
  607. for (auto& entry : basic_blocks)
  608. shared_block_count = min(shared_block_count, entry.size());
  609. MatchState state;
  610. for (size_t block_index = 0; block_index < shared_block_count; block_index++) {
  611. auto& left_block = basic_blocks.first()[block_index];
  612. auto left_end = block_index + 1 == basic_blocks.first().size() ? left_block.end : basic_blocks.first()[block_index + 1].start;
  613. auto can_continue = true;
  614. for (size_t i = 1; i < alternatives.size(); ++i) {
  615. auto& right_blocks = basic_blocks[i];
  616. auto& right_block = right_blocks[block_index];
  617. auto right_end = block_index + 1 == right_blocks.size() ? right_block.end : right_blocks[block_index + 1].start;
  618. if (left_end - left_block.start != right_end - right_block.start) {
  619. can_continue = false;
  620. break;
  621. }
  622. 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)) {
  623. can_continue = false;
  624. break;
  625. }
  626. }
  627. if (!can_continue)
  628. break;
  629. size_t i = 0;
  630. for (auto& entry : alternatives) {
  631. auto& blocks = basic_blocks[i];
  632. auto& block = blocks[block_index];
  633. auto end = block_index + 1 == blocks.size() ? block.end : blocks[block_index + 1].start;
  634. state.instruction_position = block.start;
  635. size_t skip = 0;
  636. while (state.instruction_position < end) {
  637. auto& opcode = entry.get_opcode(state);
  638. state.instruction_position += opcode.size();
  639. skip = state.instruction_position;
  640. }
  641. left_skip = min(skip, left_skip);
  642. }
  643. }
  644. dbgln_if(REGEX_DEBUG, "Skipping {}/{} bytecode entries from {}", left_skip, 0, alternatives[0].size());
  645. if (left_skip > 0) {
  646. target.extend(alternatives[0].release_slice(basic_blocks.first().first().start, left_skip));
  647. auto first = true;
  648. for (auto& entry : alternatives) {
  649. if (first) {
  650. first = false;
  651. continue;
  652. }
  653. entry = entry.release_slice(left_skip);
  654. }
  655. }
  656. if (all_of(alternatives, [](auto& entry) { return entry.is_empty(); }))
  657. return;
  658. size_t patch_start = target.size();
  659. for (size_t i = 1; i < alternatives.size(); ++i) {
  660. target.empend(static_cast<ByteCodeValueType>(OpCodeId::ForkJump));
  661. target.empend(0u); // To be filled later.
  662. }
  663. size_t size_to_jump = 0;
  664. bool seen_one_empty = false;
  665. for (size_t i = alternatives.size(); i > 0; --i) {
  666. auto& entry = alternatives[i - 1];
  667. if (entry.is_empty()) {
  668. if (seen_one_empty)
  669. continue;
  670. seen_one_empty = true;
  671. }
  672. auto is_first = i == 1;
  673. auto instruction_size = entry.size() + (is_first ? 0 : 2); // Jump; -> +2
  674. size_to_jump += instruction_size;
  675. if (!is_first)
  676. target[patch_start + (i - 2) * 2 + 1] = size_to_jump + (alternatives.size() - i) * 2;
  677. dbgln_if(REGEX_DEBUG, "{} size = {}, cum={}", i - 1, instruction_size, size_to_jump);
  678. }
  679. seen_one_empty = false;
  680. for (size_t i = alternatives.size(); i > 0; --i) {
  681. auto& chunk = alternatives[i - 1];
  682. if (chunk.is_empty()) {
  683. if (seen_one_empty)
  684. continue;
  685. seen_one_empty = true;
  686. }
  687. ByteCode* previous_chunk = nullptr;
  688. size_t j = i - 1;
  689. auto seen_one_empty_before = chunk.is_empty();
  690. while (j >= 1) {
  691. --j;
  692. auto& candidate_chunk = alternatives[j];
  693. if (candidate_chunk.is_empty()) {
  694. if (seen_one_empty_before)
  695. continue;
  696. }
  697. previous_chunk = &candidate_chunk;
  698. break;
  699. }
  700. size_to_jump -= chunk.size() + (previous_chunk ? 2 : 0);
  701. target.extend(move(chunk));
  702. target.empend(static_cast<ByteCodeValueType>(OpCodeId::Jump));
  703. target.empend(size_to_jump); // Jump to the _END label
  704. }
  705. }
  706. enum class LookupTableInsertionOutcome {
  707. Successful,
  708. ReplaceWithAnyChar,
  709. TemporaryInversionNeeded,
  710. PermanentInversionNeeded,
  711. FlushOnInsertion,
  712. FinishFlushOnInsertion,
  713. CannotPlaceInTable,
  714. };
  715. static LookupTableInsertionOutcome insert_into_lookup_table(RedBlackTree<ByteCodeValueType, CharRange>& table, CompareTypeAndValuePair pair)
  716. {
  717. switch (pair.type) {
  718. case CharacterCompareType::Inverse:
  719. return LookupTableInsertionOutcome::PermanentInversionNeeded;
  720. case CharacterCompareType::TemporaryInverse:
  721. return LookupTableInsertionOutcome::TemporaryInversionNeeded;
  722. case CharacterCompareType::AnyChar:
  723. return LookupTableInsertionOutcome::ReplaceWithAnyChar;
  724. case CharacterCompareType::CharClass:
  725. return LookupTableInsertionOutcome::CannotPlaceInTable;
  726. case CharacterCompareType::Char:
  727. table.insert(pair.value, { (u32)pair.value, (u32)pair.value });
  728. break;
  729. case CharacterCompareType::CharRange: {
  730. CharRange range { pair.value };
  731. table.insert(range.from, range);
  732. break;
  733. }
  734. case CharacterCompareType::EndAndOr:
  735. return LookupTableInsertionOutcome::FinishFlushOnInsertion;
  736. case CharacterCompareType::And:
  737. return LookupTableInsertionOutcome::FlushOnInsertion;
  738. case CharacterCompareType::Reference:
  739. case CharacterCompareType::Property:
  740. case CharacterCompareType::GeneralCategory:
  741. case CharacterCompareType::Script:
  742. case CharacterCompareType::ScriptExtension:
  743. case CharacterCompareType::Or:
  744. return LookupTableInsertionOutcome::CannotPlaceInTable;
  745. case CharacterCompareType::Undefined:
  746. case CharacterCompareType::RangeExpressionDummy:
  747. case CharacterCompareType::String:
  748. case CharacterCompareType::LookupTable:
  749. VERIFY_NOT_REACHED();
  750. }
  751. return LookupTableInsertionOutcome::Successful;
  752. }
  753. void Optimizer::append_character_class(ByteCode& target, Vector<CompareTypeAndValuePair>&& pairs)
  754. {
  755. ByteCode arguments;
  756. size_t argument_count = 0;
  757. if (pairs.size() <= 1) {
  758. for (auto& pair : pairs) {
  759. arguments.append(to_underlying(pair.type));
  760. if (pair.type != CharacterCompareType::AnyChar
  761. && pair.type != CharacterCompareType::TemporaryInverse
  762. && pair.type != CharacterCompareType::Inverse
  763. && pair.type != CharacterCompareType::And
  764. && pair.type != CharacterCompareType::Or
  765. && pair.type != CharacterCompareType::EndAndOr)
  766. arguments.append(pair.value);
  767. ++argument_count;
  768. }
  769. } else {
  770. RedBlackTree<ByteCodeValueType, CharRange> table;
  771. RedBlackTree<ByteCodeValueType, CharRange> inverted_table;
  772. auto* current_table = &table;
  773. auto* current_inverted_table = &inverted_table;
  774. bool invert_for_next_iteration = false;
  775. bool is_currently_inverted = false;
  776. auto flush_tables = [&] {
  777. auto append_table = [&](auto& table) {
  778. ++argument_count;
  779. arguments.append(to_underlying(CharacterCompareType::LookupTable));
  780. auto size_index = arguments.size();
  781. arguments.append(0);
  782. Optional<CharRange> active_range;
  783. size_t range_count = 0;
  784. for (auto& range : table) {
  785. if (!active_range.has_value()) {
  786. active_range = range;
  787. continue;
  788. }
  789. if (range.from <= active_range->to + 1 && range.to + 1 >= active_range->from) {
  790. active_range = CharRange { min(range.from, active_range->from), max(range.to, active_range->to) };
  791. } else {
  792. ++range_count;
  793. arguments.append(active_range.release_value());
  794. active_range = range;
  795. }
  796. }
  797. if (active_range.has_value()) {
  798. ++range_count;
  799. arguments.append(active_range.release_value());
  800. }
  801. arguments[size_index] = range_count;
  802. };
  803. auto contains_regular_table = !table.is_empty();
  804. auto contains_inverted_table = !inverted_table.is_empty();
  805. if (contains_regular_table)
  806. append_table(table);
  807. if (contains_inverted_table) {
  808. ++argument_count;
  809. arguments.append(to_underlying(CharacterCompareType::TemporaryInverse));
  810. append_table(inverted_table);
  811. }
  812. table.clear();
  813. inverted_table.clear();
  814. };
  815. auto flush_on_every_insertion = false;
  816. for (auto& value : pairs) {
  817. auto should_invert_after_this_iteration = invert_for_next_iteration;
  818. invert_for_next_iteration = false;
  819. auto insertion_result = insert_into_lookup_table(*current_table, value);
  820. switch (insertion_result) {
  821. case LookupTableInsertionOutcome::Successful:
  822. if (flush_on_every_insertion)
  823. flush_tables();
  824. break;
  825. case LookupTableInsertionOutcome::ReplaceWithAnyChar: {
  826. table.clear();
  827. inverted_table.clear();
  828. arguments.append(to_underlying(CharacterCompareType::AnyChar));
  829. ++argument_count;
  830. break;
  831. }
  832. case LookupTableInsertionOutcome::TemporaryInversionNeeded:
  833. swap(current_table, current_inverted_table);
  834. invert_for_next_iteration = true;
  835. is_currently_inverted = !is_currently_inverted;
  836. break;
  837. case LookupTableInsertionOutcome::PermanentInversionNeeded:
  838. flush_tables();
  839. arguments.append(to_underlying(CharacterCompareType::Inverse));
  840. ++argument_count;
  841. break;
  842. case LookupTableInsertionOutcome::FlushOnInsertion:
  843. case LookupTableInsertionOutcome::FinishFlushOnInsertion:
  844. flush_tables();
  845. flush_on_every_insertion = insertion_result == LookupTableInsertionOutcome::FlushOnInsertion;
  846. [[fallthrough]];
  847. case LookupTableInsertionOutcome::CannotPlaceInTable:
  848. if (is_currently_inverted) {
  849. arguments.append(to_underlying(CharacterCompareType::TemporaryInverse));
  850. ++argument_count;
  851. }
  852. arguments.append(to_underlying(value.type));
  853. if (value.type != CharacterCompareType::AnyChar
  854. && value.type != CharacterCompareType::TemporaryInverse
  855. && value.type != CharacterCompareType::Inverse
  856. && value.type != CharacterCompareType::And
  857. && value.type != CharacterCompareType::Or
  858. && value.type != CharacterCompareType::EndAndOr)
  859. arguments.append(value.value);
  860. ++argument_count;
  861. break;
  862. }
  863. if (should_invert_after_this_iteration) {
  864. swap(current_table, current_inverted_table);
  865. is_currently_inverted = !is_currently_inverted;
  866. }
  867. }
  868. flush_tables();
  869. }
  870. target.empend(static_cast<ByteCodeValueType>(OpCodeId::Compare));
  871. target.empend(argument_count); // number of arguments
  872. target.empend(arguments.size()); // size of arguments
  873. target.extend(move(arguments));
  874. }
  875. template void Regex<PosixBasicParser>::run_optimization_passes();
  876. template void Regex<PosixExtendedParser>::run_optimization_passes();
  877. template void Regex<ECMA262Parser>::run_optimization_passes();
  878. }