PageRenderTime 94ms CodeModel.GetById 21ms RepoModel.GetById 0ms app.codeStats 2ms

/deps/v8/src/jsregexp.cc

https://gitlab.com/GeekSir/node
C++ | 6113 lines | 4598 code | 684 blank | 831 comment | 1004 complexity | aef8ad3ebb01bc84c3cbdd8aea488a1e MD5 | raw file
Possible License(s): 0BSD, Apache-2.0, MPL-2.0-no-copyleft-exception, JSON, WTFPL, CC-BY-SA-3.0, Unlicense, ISC, BSD-3-Clause, MIT, AGPL-3.0
  1. // Copyright 2012 the V8 project authors. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be
  3. // found in the LICENSE file.
  4. #include "src/v8.h"
  5. #include "src/ast.h"
  6. #include "src/base/platform/platform.h"
  7. #include "src/compilation-cache.h"
  8. #include "src/compiler.h"
  9. #include "src/execution.h"
  10. #include "src/factory.h"
  11. #include "src/jsregexp-inl.h"
  12. #include "src/jsregexp.h"
  13. #include "src/ostreams.h"
  14. #include "src/parser.h"
  15. #include "src/regexp-macro-assembler.h"
  16. #include "src/regexp-macro-assembler-irregexp.h"
  17. #include "src/regexp-macro-assembler-tracer.h"
  18. #include "src/regexp-stack.h"
  19. #include "src/runtime.h"
  20. #include "src/string-search.h"
  21. #ifndef V8_INTERPRETED_REGEXP
  22. #if V8_TARGET_ARCH_IA32
  23. #include "src/ia32/regexp-macro-assembler-ia32.h" // NOLINT
  24. #elif V8_TARGET_ARCH_X64
  25. #include "src/x64/regexp-macro-assembler-x64.h" // NOLINT
  26. #elif V8_TARGET_ARCH_ARM64
  27. #include "src/arm64/regexp-macro-assembler-arm64.h" // NOLINT
  28. #elif V8_TARGET_ARCH_ARM
  29. #include "src/arm/regexp-macro-assembler-arm.h" // NOLINT
  30. #elif V8_TARGET_ARCH_MIPS
  31. #include "src/mips/regexp-macro-assembler-mips.h" // NOLINT
  32. #elif V8_TARGET_ARCH_MIPS64
  33. #include "src/mips64/regexp-macro-assembler-mips64.h" // NOLINT
  34. #elif V8_TARGET_ARCH_X87
  35. #include "src/x87/regexp-macro-assembler-x87.h" // NOLINT
  36. #else
  37. #error Unsupported target architecture.
  38. #endif
  39. #endif
  40. #include "src/interpreter-irregexp.h"
  41. namespace v8 {
  42. namespace internal {
  43. MaybeHandle<Object> RegExpImpl::CreateRegExpLiteral(
  44. Handle<JSFunction> constructor,
  45. Handle<String> pattern,
  46. Handle<String> flags) {
  47. // Call the construct code with 2 arguments.
  48. Handle<Object> argv[] = { pattern, flags };
  49. return Execution::New(constructor, ARRAY_SIZE(argv), argv);
  50. }
  51. static JSRegExp::Flags RegExpFlagsFromString(Handle<String> str) {
  52. int flags = JSRegExp::NONE;
  53. for (int i = 0; i < str->length(); i++) {
  54. switch (str->Get(i)) {
  55. case 'i':
  56. flags |= JSRegExp::IGNORE_CASE;
  57. break;
  58. case 'g':
  59. flags |= JSRegExp::GLOBAL;
  60. break;
  61. case 'm':
  62. flags |= JSRegExp::MULTILINE;
  63. break;
  64. }
  65. }
  66. return JSRegExp::Flags(flags);
  67. }
  68. MUST_USE_RESULT
  69. static inline MaybeHandle<Object> ThrowRegExpException(
  70. Handle<JSRegExp> re,
  71. Handle<String> pattern,
  72. Handle<String> error_text,
  73. const char* message) {
  74. Isolate* isolate = re->GetIsolate();
  75. Factory* factory = isolate->factory();
  76. Handle<FixedArray> elements = factory->NewFixedArray(2);
  77. elements->set(0, *pattern);
  78. elements->set(1, *error_text);
  79. Handle<JSArray> array = factory->NewJSArrayWithElements(elements);
  80. Handle<Object> regexp_err = factory->NewSyntaxError(message, array);
  81. return isolate->Throw<Object>(regexp_err);
  82. }
  83. ContainedInLattice AddRange(ContainedInLattice containment,
  84. const int* ranges,
  85. int ranges_length,
  86. Interval new_range) {
  87. DCHECK((ranges_length & 1) == 1);
  88. DCHECK(ranges[ranges_length - 1] == String::kMaxUtf16CodeUnit + 1);
  89. if (containment == kLatticeUnknown) return containment;
  90. bool inside = false;
  91. int last = 0;
  92. for (int i = 0; i < ranges_length; inside = !inside, last = ranges[i], i++) {
  93. // Consider the range from last to ranges[i].
  94. // We haven't got to the new range yet.
  95. if (ranges[i] <= new_range.from()) continue;
  96. // New range is wholly inside last-ranges[i]. Note that new_range.to() is
  97. // inclusive, but the values in ranges are not.
  98. if (last <= new_range.from() && new_range.to() < ranges[i]) {
  99. return Combine(containment, inside ? kLatticeIn : kLatticeOut);
  100. }
  101. return kLatticeUnknown;
  102. }
  103. return containment;
  104. }
  105. // More makes code generation slower, less makes V8 benchmark score lower.
  106. const int kMaxLookaheadForBoyerMoore = 8;
  107. // In a 3-character pattern you can maximally step forwards 3 characters
  108. // at a time, which is not always enough to pay for the extra logic.
  109. const int kPatternTooShortForBoyerMoore = 2;
  110. // Identifies the sort of regexps where the regexp engine is faster
  111. // than the code used for atom matches.
  112. static bool HasFewDifferentCharacters(Handle<String> pattern) {
  113. int length = Min(kMaxLookaheadForBoyerMoore, pattern->length());
  114. if (length <= kPatternTooShortForBoyerMoore) return false;
  115. const int kMod = 128;
  116. bool character_found[kMod];
  117. int different = 0;
  118. memset(&character_found[0], 0, sizeof(character_found));
  119. for (int i = 0; i < length; i++) {
  120. int ch = (pattern->Get(i) & (kMod - 1));
  121. if (!character_found[ch]) {
  122. character_found[ch] = true;
  123. different++;
  124. // We declare a regexp low-alphabet if it has at least 3 times as many
  125. // characters as it has different characters.
  126. if (different * 3 > length) return false;
  127. }
  128. }
  129. return true;
  130. }
  131. // Generic RegExp methods. Dispatches to implementation specific methods.
  132. MaybeHandle<Object> RegExpImpl::Compile(Handle<JSRegExp> re,
  133. Handle<String> pattern,
  134. Handle<String> flag_str) {
  135. Isolate* isolate = re->GetIsolate();
  136. Zone zone(isolate);
  137. JSRegExp::Flags flags = RegExpFlagsFromString(flag_str);
  138. CompilationCache* compilation_cache = isolate->compilation_cache();
  139. MaybeHandle<FixedArray> maybe_cached =
  140. compilation_cache->LookupRegExp(pattern, flags);
  141. Handle<FixedArray> cached;
  142. bool in_cache = maybe_cached.ToHandle(&cached);
  143. LOG(isolate, RegExpCompileEvent(re, in_cache));
  144. Handle<Object> result;
  145. if (in_cache) {
  146. re->set_data(*cached);
  147. return re;
  148. }
  149. pattern = String::Flatten(pattern);
  150. PostponeInterruptsScope postpone(isolate);
  151. RegExpCompileData parse_result;
  152. FlatStringReader reader(isolate, pattern);
  153. if (!RegExpParser::ParseRegExp(&reader, flags.is_multiline(),
  154. &parse_result, &zone)) {
  155. // Throw an exception if we fail to parse the pattern.
  156. return ThrowRegExpException(re,
  157. pattern,
  158. parse_result.error,
  159. "malformed_regexp");
  160. }
  161. bool has_been_compiled = false;
  162. if (parse_result.simple &&
  163. !flags.is_ignore_case() &&
  164. !HasFewDifferentCharacters(pattern)) {
  165. // Parse-tree is a single atom that is equal to the pattern.
  166. AtomCompile(re, pattern, flags, pattern);
  167. has_been_compiled = true;
  168. } else if (parse_result.tree->IsAtom() &&
  169. !flags.is_ignore_case() &&
  170. parse_result.capture_count == 0) {
  171. RegExpAtom* atom = parse_result.tree->AsAtom();
  172. Vector<const uc16> atom_pattern = atom->data();
  173. Handle<String> atom_string;
  174. ASSIGN_RETURN_ON_EXCEPTION(
  175. isolate, atom_string,
  176. isolate->factory()->NewStringFromTwoByte(atom_pattern),
  177. Object);
  178. if (!HasFewDifferentCharacters(atom_string)) {
  179. AtomCompile(re, pattern, flags, atom_string);
  180. has_been_compiled = true;
  181. }
  182. }
  183. if (!has_been_compiled) {
  184. IrregexpInitialize(re, pattern, flags, parse_result.capture_count);
  185. }
  186. DCHECK(re->data()->IsFixedArray());
  187. // Compilation succeeded so the data is set on the regexp
  188. // and we can store it in the cache.
  189. Handle<FixedArray> data(FixedArray::cast(re->data()));
  190. compilation_cache->PutRegExp(pattern, flags, data);
  191. return re;
  192. }
  193. MaybeHandle<Object> RegExpImpl::Exec(Handle<JSRegExp> regexp,
  194. Handle<String> subject,
  195. int index,
  196. Handle<JSArray> last_match_info) {
  197. switch (regexp->TypeTag()) {
  198. case JSRegExp::ATOM:
  199. return AtomExec(regexp, subject, index, last_match_info);
  200. case JSRegExp::IRREGEXP: {
  201. return IrregexpExec(regexp, subject, index, last_match_info);
  202. }
  203. default:
  204. UNREACHABLE();
  205. return MaybeHandle<Object>();
  206. }
  207. }
  208. // RegExp Atom implementation: Simple string search using indexOf.
  209. void RegExpImpl::AtomCompile(Handle<JSRegExp> re,
  210. Handle<String> pattern,
  211. JSRegExp::Flags flags,
  212. Handle<String> match_pattern) {
  213. re->GetIsolate()->factory()->SetRegExpAtomData(re,
  214. JSRegExp::ATOM,
  215. pattern,
  216. flags,
  217. match_pattern);
  218. }
  219. static void SetAtomLastCapture(FixedArray* array,
  220. String* subject,
  221. int from,
  222. int to) {
  223. SealHandleScope shs(array->GetIsolate());
  224. RegExpImpl::SetLastCaptureCount(array, 2);
  225. RegExpImpl::SetLastSubject(array, subject);
  226. RegExpImpl::SetLastInput(array, subject);
  227. RegExpImpl::SetCapture(array, 0, from);
  228. RegExpImpl::SetCapture(array, 1, to);
  229. }
  230. int RegExpImpl::AtomExecRaw(Handle<JSRegExp> regexp,
  231. Handle<String> subject,
  232. int index,
  233. int32_t* output,
  234. int output_size) {
  235. Isolate* isolate = regexp->GetIsolate();
  236. DCHECK(0 <= index);
  237. DCHECK(index <= subject->length());
  238. subject = String::Flatten(subject);
  239. DisallowHeapAllocation no_gc; // ensure vectors stay valid
  240. String* needle = String::cast(regexp->DataAt(JSRegExp::kAtomPatternIndex));
  241. int needle_len = needle->length();
  242. DCHECK(needle->IsFlat());
  243. DCHECK_LT(0, needle_len);
  244. if (index + needle_len > subject->length()) {
  245. return RegExpImpl::RE_FAILURE;
  246. }
  247. for (int i = 0; i < output_size; i += 2) {
  248. String::FlatContent needle_content = needle->GetFlatContent();
  249. String::FlatContent subject_content = subject->GetFlatContent();
  250. DCHECK(needle_content.IsFlat());
  251. DCHECK(subject_content.IsFlat());
  252. // dispatch on type of strings
  253. index = (needle_content.IsAscii()
  254. ? (subject_content.IsAscii()
  255. ? SearchString(isolate,
  256. subject_content.ToOneByteVector(),
  257. needle_content.ToOneByteVector(),
  258. index)
  259. : SearchString(isolate,
  260. subject_content.ToUC16Vector(),
  261. needle_content.ToOneByteVector(),
  262. index))
  263. : (subject_content.IsAscii()
  264. ? SearchString(isolate,
  265. subject_content.ToOneByteVector(),
  266. needle_content.ToUC16Vector(),
  267. index)
  268. : SearchString(isolate,
  269. subject_content.ToUC16Vector(),
  270. needle_content.ToUC16Vector(),
  271. index)));
  272. if (index == -1) {
  273. return i / 2; // Return number of matches.
  274. } else {
  275. output[i] = index;
  276. output[i+1] = index + needle_len;
  277. index += needle_len;
  278. }
  279. }
  280. return output_size / 2;
  281. }
  282. Handle<Object> RegExpImpl::AtomExec(Handle<JSRegExp> re,
  283. Handle<String> subject,
  284. int index,
  285. Handle<JSArray> last_match_info) {
  286. Isolate* isolate = re->GetIsolate();
  287. static const int kNumRegisters = 2;
  288. STATIC_ASSERT(kNumRegisters <= Isolate::kJSRegexpStaticOffsetsVectorSize);
  289. int32_t* output_registers = isolate->jsregexp_static_offsets_vector();
  290. int res = AtomExecRaw(re, subject, index, output_registers, kNumRegisters);
  291. if (res == RegExpImpl::RE_FAILURE) return isolate->factory()->null_value();
  292. DCHECK_EQ(res, RegExpImpl::RE_SUCCESS);
  293. SealHandleScope shs(isolate);
  294. FixedArray* array = FixedArray::cast(last_match_info->elements());
  295. SetAtomLastCapture(array, *subject, output_registers[0], output_registers[1]);
  296. return last_match_info;
  297. }
  298. // Irregexp implementation.
  299. // Ensures that the regexp object contains a compiled version of the
  300. // source for either ASCII or non-ASCII strings.
  301. // If the compiled version doesn't already exist, it is compiled
  302. // from the source pattern.
  303. // If compilation fails, an exception is thrown and this function
  304. // returns false.
  305. bool RegExpImpl::EnsureCompiledIrregexp(
  306. Handle<JSRegExp> re, Handle<String> sample_subject, bool is_ascii) {
  307. Object* compiled_code = re->DataAt(JSRegExp::code_index(is_ascii));
  308. #ifdef V8_INTERPRETED_REGEXP
  309. if (compiled_code->IsByteArray()) return true;
  310. #else // V8_INTERPRETED_REGEXP (RegExp native code)
  311. if (compiled_code->IsCode()) return true;
  312. #endif
  313. // We could potentially have marked this as flushable, but have kept
  314. // a saved version if we did not flush it yet.
  315. Object* saved_code = re->DataAt(JSRegExp::saved_code_index(is_ascii));
  316. if (saved_code->IsCode()) {
  317. // Reinstate the code in the original place.
  318. re->SetDataAt(JSRegExp::code_index(is_ascii), saved_code);
  319. DCHECK(compiled_code->IsSmi());
  320. return true;
  321. }
  322. return CompileIrregexp(re, sample_subject, is_ascii);
  323. }
  324. static bool CreateRegExpErrorObjectAndThrow(Handle<JSRegExp> re,
  325. bool is_ascii,
  326. Handle<String> error_message,
  327. Isolate* isolate) {
  328. Factory* factory = isolate->factory();
  329. Handle<FixedArray> elements = factory->NewFixedArray(2);
  330. elements->set(0, re->Pattern());
  331. elements->set(1, *error_message);
  332. Handle<JSArray> array = factory->NewJSArrayWithElements(elements);
  333. Handle<Object> regexp_err =
  334. factory->NewSyntaxError("malformed_regexp", array);
  335. isolate->Throw(*regexp_err);
  336. return false;
  337. }
  338. bool RegExpImpl::CompileIrregexp(Handle<JSRegExp> re,
  339. Handle<String> sample_subject,
  340. bool is_ascii) {
  341. // Compile the RegExp.
  342. Isolate* isolate = re->GetIsolate();
  343. Zone zone(isolate);
  344. PostponeInterruptsScope postpone(isolate);
  345. // If we had a compilation error the last time this is saved at the
  346. // saved code index.
  347. Object* entry = re->DataAt(JSRegExp::code_index(is_ascii));
  348. // When arriving here entry can only be a smi, either representing an
  349. // uncompiled regexp, a previous compilation error, or code that has
  350. // been flushed.
  351. DCHECK(entry->IsSmi());
  352. int entry_value = Smi::cast(entry)->value();
  353. DCHECK(entry_value == JSRegExp::kUninitializedValue ||
  354. entry_value == JSRegExp::kCompilationErrorValue ||
  355. (entry_value < JSRegExp::kCodeAgeMask && entry_value >= 0));
  356. if (entry_value == JSRegExp::kCompilationErrorValue) {
  357. // A previous compilation failed and threw an error which we store in
  358. // the saved code index (we store the error message, not the actual
  359. // error). Recreate the error object and throw it.
  360. Object* error_string = re->DataAt(JSRegExp::saved_code_index(is_ascii));
  361. DCHECK(error_string->IsString());
  362. Handle<String> error_message(String::cast(error_string));
  363. CreateRegExpErrorObjectAndThrow(re, is_ascii, error_message, isolate);
  364. return false;
  365. }
  366. JSRegExp::Flags flags = re->GetFlags();
  367. Handle<String> pattern(re->Pattern());
  368. pattern = String::Flatten(pattern);
  369. RegExpCompileData compile_data;
  370. FlatStringReader reader(isolate, pattern);
  371. if (!RegExpParser::ParseRegExp(&reader, flags.is_multiline(),
  372. &compile_data,
  373. &zone)) {
  374. // Throw an exception if we fail to parse the pattern.
  375. // THIS SHOULD NOT HAPPEN. We already pre-parsed it successfully once.
  376. USE(ThrowRegExpException(re,
  377. pattern,
  378. compile_data.error,
  379. "malformed_regexp"));
  380. return false;
  381. }
  382. RegExpEngine::CompilationResult result =
  383. RegExpEngine::Compile(&compile_data,
  384. flags.is_ignore_case(),
  385. flags.is_global(),
  386. flags.is_multiline(),
  387. pattern,
  388. sample_subject,
  389. is_ascii,
  390. &zone);
  391. if (result.error_message != NULL) {
  392. // Unable to compile regexp.
  393. Handle<String> error_message = isolate->factory()->NewStringFromUtf8(
  394. CStrVector(result.error_message)).ToHandleChecked();
  395. CreateRegExpErrorObjectAndThrow(re, is_ascii, error_message, isolate);
  396. return false;
  397. }
  398. Handle<FixedArray> data = Handle<FixedArray>(FixedArray::cast(re->data()));
  399. data->set(JSRegExp::code_index(is_ascii), result.code);
  400. int register_max = IrregexpMaxRegisterCount(*data);
  401. if (result.num_registers > register_max) {
  402. SetIrregexpMaxRegisterCount(*data, result.num_registers);
  403. }
  404. return true;
  405. }
  406. int RegExpImpl::IrregexpMaxRegisterCount(FixedArray* re) {
  407. return Smi::cast(
  408. re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
  409. }
  410. void RegExpImpl::SetIrregexpMaxRegisterCount(FixedArray* re, int value) {
  411. re->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(value));
  412. }
  413. int RegExpImpl::IrregexpNumberOfCaptures(FixedArray* re) {
  414. return Smi::cast(re->get(JSRegExp::kIrregexpCaptureCountIndex))->value();
  415. }
  416. int RegExpImpl::IrregexpNumberOfRegisters(FixedArray* re) {
  417. return Smi::cast(re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
  418. }
  419. ByteArray* RegExpImpl::IrregexpByteCode(FixedArray* re, bool is_ascii) {
  420. return ByteArray::cast(re->get(JSRegExp::code_index(is_ascii)));
  421. }
  422. Code* RegExpImpl::IrregexpNativeCode(FixedArray* re, bool is_ascii) {
  423. return Code::cast(re->get(JSRegExp::code_index(is_ascii)));
  424. }
  425. void RegExpImpl::IrregexpInitialize(Handle<JSRegExp> re,
  426. Handle<String> pattern,
  427. JSRegExp::Flags flags,
  428. int capture_count) {
  429. // Initialize compiled code entries to null.
  430. re->GetIsolate()->factory()->SetRegExpIrregexpData(re,
  431. JSRegExp::IRREGEXP,
  432. pattern,
  433. flags,
  434. capture_count);
  435. }
  436. int RegExpImpl::IrregexpPrepare(Handle<JSRegExp> regexp,
  437. Handle<String> subject) {
  438. subject = String::Flatten(subject);
  439. // Check the asciiness of the underlying storage.
  440. bool is_ascii = subject->IsOneByteRepresentationUnderneath();
  441. if (!EnsureCompiledIrregexp(regexp, subject, is_ascii)) return -1;
  442. #ifdef V8_INTERPRETED_REGEXP
  443. // Byte-code regexp needs space allocated for all its registers.
  444. // The result captures are copied to the start of the registers array
  445. // if the match succeeds. This way those registers are not clobbered
  446. // when we set the last match info from last successful match.
  447. return IrregexpNumberOfRegisters(FixedArray::cast(regexp->data())) +
  448. (IrregexpNumberOfCaptures(FixedArray::cast(regexp->data())) + 1) * 2;
  449. #else // V8_INTERPRETED_REGEXP
  450. // Native regexp only needs room to output captures. Registers are handled
  451. // internally.
  452. return (IrregexpNumberOfCaptures(FixedArray::cast(regexp->data())) + 1) * 2;
  453. #endif // V8_INTERPRETED_REGEXP
  454. }
  455. int RegExpImpl::IrregexpExecRaw(Handle<JSRegExp> regexp,
  456. Handle<String> subject,
  457. int index,
  458. int32_t* output,
  459. int output_size) {
  460. Isolate* isolate = regexp->GetIsolate();
  461. Handle<FixedArray> irregexp(FixedArray::cast(regexp->data()), isolate);
  462. DCHECK(index >= 0);
  463. DCHECK(index <= subject->length());
  464. DCHECK(subject->IsFlat());
  465. bool is_ascii = subject->IsOneByteRepresentationUnderneath();
  466. #ifndef V8_INTERPRETED_REGEXP
  467. DCHECK(output_size >= (IrregexpNumberOfCaptures(*irregexp) + 1) * 2);
  468. do {
  469. EnsureCompiledIrregexp(regexp, subject, is_ascii);
  470. Handle<Code> code(IrregexpNativeCode(*irregexp, is_ascii), isolate);
  471. // The stack is used to allocate registers for the compiled regexp code.
  472. // This means that in case of failure, the output registers array is left
  473. // untouched and contains the capture results from the previous successful
  474. // match. We can use that to set the last match info lazily.
  475. NativeRegExpMacroAssembler::Result res =
  476. NativeRegExpMacroAssembler::Match(code,
  477. subject,
  478. output,
  479. output_size,
  480. index,
  481. isolate);
  482. if (res != NativeRegExpMacroAssembler::RETRY) {
  483. DCHECK(res != NativeRegExpMacroAssembler::EXCEPTION ||
  484. isolate->has_pending_exception());
  485. STATIC_ASSERT(
  486. static_cast<int>(NativeRegExpMacroAssembler::SUCCESS) == RE_SUCCESS);
  487. STATIC_ASSERT(
  488. static_cast<int>(NativeRegExpMacroAssembler::FAILURE) == RE_FAILURE);
  489. STATIC_ASSERT(static_cast<int>(NativeRegExpMacroAssembler::EXCEPTION)
  490. == RE_EXCEPTION);
  491. return static_cast<IrregexpResult>(res);
  492. }
  493. // If result is RETRY, the string has changed representation, and we
  494. // must restart from scratch.
  495. // In this case, it means we must make sure we are prepared to handle
  496. // the, potentially, different subject (the string can switch between
  497. // being internal and external, and even between being ASCII and UC16,
  498. // but the characters are always the same).
  499. IrregexpPrepare(regexp, subject);
  500. is_ascii = subject->IsOneByteRepresentationUnderneath();
  501. } while (true);
  502. UNREACHABLE();
  503. return RE_EXCEPTION;
  504. #else // V8_INTERPRETED_REGEXP
  505. DCHECK(output_size >= IrregexpNumberOfRegisters(*irregexp));
  506. // We must have done EnsureCompiledIrregexp, so we can get the number of
  507. // registers.
  508. int number_of_capture_registers =
  509. (IrregexpNumberOfCaptures(*irregexp) + 1) * 2;
  510. int32_t* raw_output = &output[number_of_capture_registers];
  511. // We do not touch the actual capture result registers until we know there
  512. // has been a match so that we can use those capture results to set the
  513. // last match info.
  514. for (int i = number_of_capture_registers - 1; i >= 0; i--) {
  515. raw_output[i] = -1;
  516. }
  517. Handle<ByteArray> byte_codes(IrregexpByteCode(*irregexp, is_ascii), isolate);
  518. IrregexpResult result = IrregexpInterpreter::Match(isolate,
  519. byte_codes,
  520. subject,
  521. raw_output,
  522. index);
  523. if (result == RE_SUCCESS) {
  524. // Copy capture results to the start of the registers array.
  525. MemCopy(output, raw_output, number_of_capture_registers * sizeof(int32_t));
  526. }
  527. if (result == RE_EXCEPTION) {
  528. DCHECK(!isolate->has_pending_exception());
  529. isolate->StackOverflow();
  530. }
  531. return result;
  532. #endif // V8_INTERPRETED_REGEXP
  533. }
  534. MaybeHandle<Object> RegExpImpl::IrregexpExec(Handle<JSRegExp> regexp,
  535. Handle<String> subject,
  536. int previous_index,
  537. Handle<JSArray> last_match_info) {
  538. Isolate* isolate = regexp->GetIsolate();
  539. DCHECK_EQ(regexp->TypeTag(), JSRegExp::IRREGEXP);
  540. // Prepare space for the return values.
  541. #if defined(V8_INTERPRETED_REGEXP) && defined(DEBUG)
  542. if (FLAG_trace_regexp_bytecodes) {
  543. String* pattern = regexp->Pattern();
  544. PrintF("\n\nRegexp match: /%s/\n\n", pattern->ToCString().get());
  545. PrintF("\n\nSubject string: '%s'\n\n", subject->ToCString().get());
  546. }
  547. #endif
  548. int required_registers = RegExpImpl::IrregexpPrepare(regexp, subject);
  549. if (required_registers < 0) {
  550. // Compiling failed with an exception.
  551. DCHECK(isolate->has_pending_exception());
  552. return MaybeHandle<Object>();
  553. }
  554. int32_t* output_registers = NULL;
  555. if (required_registers > Isolate::kJSRegexpStaticOffsetsVectorSize) {
  556. output_registers = NewArray<int32_t>(required_registers);
  557. }
  558. SmartArrayPointer<int32_t> auto_release(output_registers);
  559. if (output_registers == NULL) {
  560. output_registers = isolate->jsregexp_static_offsets_vector();
  561. }
  562. int res = RegExpImpl::IrregexpExecRaw(
  563. regexp, subject, previous_index, output_registers, required_registers);
  564. if (res == RE_SUCCESS) {
  565. int capture_count =
  566. IrregexpNumberOfCaptures(FixedArray::cast(regexp->data()));
  567. return SetLastMatchInfo(
  568. last_match_info, subject, capture_count, output_registers);
  569. }
  570. if (res == RE_EXCEPTION) {
  571. DCHECK(isolate->has_pending_exception());
  572. return MaybeHandle<Object>();
  573. }
  574. DCHECK(res == RE_FAILURE);
  575. return isolate->factory()->null_value();
  576. }
  577. Handle<JSArray> RegExpImpl::SetLastMatchInfo(Handle<JSArray> last_match_info,
  578. Handle<String> subject,
  579. int capture_count,
  580. int32_t* match) {
  581. DCHECK(last_match_info->HasFastObjectElements());
  582. int capture_register_count = (capture_count + 1) * 2;
  583. JSArray::EnsureSize(last_match_info,
  584. capture_register_count + kLastMatchOverhead);
  585. DisallowHeapAllocation no_allocation;
  586. FixedArray* array = FixedArray::cast(last_match_info->elements());
  587. if (match != NULL) {
  588. for (int i = 0; i < capture_register_count; i += 2) {
  589. SetCapture(array, i, match[i]);
  590. SetCapture(array, i + 1, match[i + 1]);
  591. }
  592. }
  593. SetLastCaptureCount(array, capture_register_count);
  594. SetLastSubject(array, *subject);
  595. SetLastInput(array, *subject);
  596. return last_match_info;
  597. }
  598. RegExpImpl::GlobalCache::GlobalCache(Handle<JSRegExp> regexp,
  599. Handle<String> subject,
  600. bool is_global,
  601. Isolate* isolate)
  602. : register_array_(NULL),
  603. register_array_size_(0),
  604. regexp_(regexp),
  605. subject_(subject) {
  606. #ifdef V8_INTERPRETED_REGEXP
  607. bool interpreted = true;
  608. #else
  609. bool interpreted = false;
  610. #endif // V8_INTERPRETED_REGEXP
  611. if (regexp_->TypeTag() == JSRegExp::ATOM) {
  612. static const int kAtomRegistersPerMatch = 2;
  613. registers_per_match_ = kAtomRegistersPerMatch;
  614. // There is no distinction between interpreted and native for atom regexps.
  615. interpreted = false;
  616. } else {
  617. registers_per_match_ = RegExpImpl::IrregexpPrepare(regexp_, subject_);
  618. if (registers_per_match_ < 0) {
  619. num_matches_ = -1; // Signal exception.
  620. return;
  621. }
  622. }
  623. if (is_global && !interpreted) {
  624. register_array_size_ =
  625. Max(registers_per_match_, Isolate::kJSRegexpStaticOffsetsVectorSize);
  626. max_matches_ = register_array_size_ / registers_per_match_;
  627. } else {
  628. // Global loop in interpreted regexp is not implemented. We choose
  629. // the size of the offsets vector so that it can only store one match.
  630. register_array_size_ = registers_per_match_;
  631. max_matches_ = 1;
  632. }
  633. if (register_array_size_ > Isolate::kJSRegexpStaticOffsetsVectorSize) {
  634. register_array_ = NewArray<int32_t>(register_array_size_);
  635. } else {
  636. register_array_ = isolate->jsregexp_static_offsets_vector();
  637. }
  638. // Set state so that fetching the results the first time triggers a call
  639. // to the compiled regexp.
  640. current_match_index_ = max_matches_ - 1;
  641. num_matches_ = max_matches_;
  642. DCHECK(registers_per_match_ >= 2); // Each match has at least one capture.
  643. DCHECK_GE(register_array_size_, registers_per_match_);
  644. int32_t* last_match =
  645. &register_array_[current_match_index_ * registers_per_match_];
  646. last_match[0] = -1;
  647. last_match[1] = 0;
  648. }
  649. // -------------------------------------------------------------------
  650. // Implementation of the Irregexp regular expression engine.
  651. //
  652. // The Irregexp regular expression engine is intended to be a complete
  653. // implementation of ECMAScript regular expressions. It generates either
  654. // bytecodes or native code.
  655. // The Irregexp regexp engine is structured in three steps.
  656. // 1) The parser generates an abstract syntax tree. See ast.cc.
  657. // 2) From the AST a node network is created. The nodes are all
  658. // subclasses of RegExpNode. The nodes represent states when
  659. // executing a regular expression. Several optimizations are
  660. // performed on the node network.
  661. // 3) From the nodes we generate either byte codes or native code
  662. // that can actually execute the regular expression (perform
  663. // the search). The code generation step is described in more
  664. // detail below.
  665. // Code generation.
  666. //
  667. // The nodes are divided into four main categories.
  668. // * Choice nodes
  669. // These represent places where the regular expression can
  670. // match in more than one way. For example on entry to an
  671. // alternation (foo|bar) or a repetition (*, +, ? or {}).
  672. // * Action nodes
  673. // These represent places where some action should be
  674. // performed. Examples include recording the current position
  675. // in the input string to a register (in order to implement
  676. // captures) or other actions on register for example in order
  677. // to implement the counters needed for {} repetitions.
  678. // * Matching nodes
  679. // These attempt to match some element part of the input string.
  680. // Examples of elements include character classes, plain strings
  681. // or back references.
  682. // * End nodes
  683. // These are used to implement the actions required on finding
  684. // a successful match or failing to find a match.
  685. //
  686. // The code generated (whether as byte codes or native code) maintains
  687. // some state as it runs. This consists of the following elements:
  688. //
  689. // * The capture registers. Used for string captures.
  690. // * Other registers. Used for counters etc.
  691. // * The current position.
  692. // * The stack of backtracking information. Used when a matching node
  693. // fails to find a match and needs to try an alternative.
  694. //
  695. // Conceptual regular expression execution model:
  696. //
  697. // There is a simple conceptual model of regular expression execution
  698. // which will be presented first. The actual code generated is a more
  699. // efficient simulation of the simple conceptual model:
  700. //
  701. // * Choice nodes are implemented as follows:
  702. // For each choice except the last {
  703. // push current position
  704. // push backtrack code location
  705. // <generate code to test for choice>
  706. // backtrack code location:
  707. // pop current position
  708. // }
  709. // <generate code to test for last choice>
  710. //
  711. // * Actions nodes are generated as follows
  712. // <push affected registers on backtrack stack>
  713. // <generate code to perform action>
  714. // push backtrack code location
  715. // <generate code to test for following nodes>
  716. // backtrack code location:
  717. // <pop affected registers to restore their state>
  718. // <pop backtrack location from stack and go to it>
  719. //
  720. // * Matching nodes are generated as follows:
  721. // if input string matches at current position
  722. // update current position
  723. // <generate code to test for following nodes>
  724. // else
  725. // <pop backtrack location from stack and go to it>
  726. //
  727. // Thus it can be seen that the current position is saved and restored
  728. // by the choice nodes, whereas the registers are saved and restored by
  729. // by the action nodes that manipulate them.
  730. //
  731. // The other interesting aspect of this model is that nodes are generated
  732. // at the point where they are needed by a recursive call to Emit(). If
  733. // the node has already been code generated then the Emit() call will
  734. // generate a jump to the previously generated code instead. In order to
  735. // limit recursion it is possible for the Emit() function to put the node
  736. // on a work list for later generation and instead generate a jump. The
  737. // destination of the jump is resolved later when the code is generated.
  738. //
  739. // Actual regular expression code generation.
  740. //
  741. // Code generation is actually more complicated than the above. In order
  742. // to improve the efficiency of the generated code some optimizations are
  743. // performed
  744. //
  745. // * Choice nodes have 1-character lookahead.
  746. // A choice node looks at the following character and eliminates some of
  747. // the choices immediately based on that character. This is not yet
  748. // implemented.
  749. // * Simple greedy loops store reduced backtracking information.
  750. // A quantifier like /.*foo/m will greedily match the whole input. It will
  751. // then need to backtrack to a point where it can match "foo". The naive
  752. // implementation of this would push each character position onto the
  753. // backtracking stack, then pop them off one by one. This would use space
  754. // proportional to the length of the input string. However since the "."
  755. // can only match in one way and always has a constant length (in this case
  756. // of 1) it suffices to store the current position on the top of the stack
  757. // once. Matching now becomes merely incrementing the current position and
  758. // backtracking becomes decrementing the current position and checking the
  759. // result against the stored current position. This is faster and saves
  760. // space.
  761. // * The current state is virtualized.
  762. // This is used to defer expensive operations until it is clear that they
  763. // are needed and to generate code for a node more than once, allowing
  764. // specialized an efficient versions of the code to be created. This is
  765. // explained in the section below.
  766. //
  767. // Execution state virtualization.
  768. //
  769. // Instead of emitting code, nodes that manipulate the state can record their
  770. // manipulation in an object called the Trace. The Trace object can record a
  771. // current position offset, an optional backtrack code location on the top of
  772. // the virtualized backtrack stack and some register changes. When a node is
  773. // to be emitted it can flush the Trace or update it. Flushing the Trace
  774. // will emit code to bring the actual state into line with the virtual state.
  775. // Avoiding flushing the state can postpone some work (e.g. updates of capture
  776. // registers). Postponing work can save time when executing the regular
  777. // expression since it may be found that the work never has to be done as a
  778. // failure to match can occur. In addition it is much faster to jump to a
  779. // known backtrack code location than it is to pop an unknown backtrack
  780. // location from the stack and jump there.
  781. //
  782. // The virtual state found in the Trace affects code generation. For example
  783. // the virtual state contains the difference between the actual current
  784. // position and the virtual current position, and matching code needs to use
  785. // this offset to attempt a match in the correct location of the input
  786. // string. Therefore code generated for a non-trivial trace is specialized
  787. // to that trace. The code generator therefore has the ability to generate
  788. // code for each node several times. In order to limit the size of the
  789. // generated code there is an arbitrary limit on how many specialized sets of
  790. // code may be generated for a given node. If the limit is reached, the
  791. // trace is flushed and a generic version of the code for a node is emitted.
  792. // This is subsequently used for that node. The code emitted for non-generic
  793. // trace is not recorded in the node and so it cannot currently be reused in
  794. // the event that code generation is requested for an identical trace.
  795. void RegExpTree::AppendToText(RegExpText* text, Zone* zone) {
  796. UNREACHABLE();
  797. }
  798. void RegExpAtom::AppendToText(RegExpText* text, Zone* zone) {
  799. text->AddElement(TextElement::Atom(this), zone);
  800. }
  801. void RegExpCharacterClass::AppendToText(RegExpText* text, Zone* zone) {
  802. text->AddElement(TextElement::CharClass(this), zone);
  803. }
  804. void RegExpText::AppendToText(RegExpText* text, Zone* zone) {
  805. for (int i = 0; i < elements()->length(); i++)
  806. text->AddElement(elements()->at(i), zone);
  807. }
  808. TextElement TextElement::Atom(RegExpAtom* atom) {
  809. return TextElement(ATOM, atom);
  810. }
  811. TextElement TextElement::CharClass(RegExpCharacterClass* char_class) {
  812. return TextElement(CHAR_CLASS, char_class);
  813. }
  814. int TextElement::length() const {
  815. switch (text_type()) {
  816. case ATOM:
  817. return atom()->length();
  818. case CHAR_CLASS:
  819. return 1;
  820. }
  821. UNREACHABLE();
  822. return 0;
  823. }
  824. DispatchTable* ChoiceNode::GetTable(bool ignore_case) {
  825. if (table_ == NULL) {
  826. table_ = new(zone()) DispatchTable(zone());
  827. DispatchTableConstructor cons(table_, ignore_case, zone());
  828. cons.BuildTable(this);
  829. }
  830. return table_;
  831. }
  832. class FrequencyCollator {
  833. public:
  834. FrequencyCollator() : total_samples_(0) {
  835. for (int i = 0; i < RegExpMacroAssembler::kTableSize; i++) {
  836. frequencies_[i] = CharacterFrequency(i);
  837. }
  838. }
  839. void CountCharacter(int character) {
  840. int index = (character & RegExpMacroAssembler::kTableMask);
  841. frequencies_[index].Increment();
  842. total_samples_++;
  843. }
  844. // Does not measure in percent, but rather per-128 (the table size from the
  845. // regexp macro assembler).
  846. int Frequency(int in_character) {
  847. DCHECK((in_character & RegExpMacroAssembler::kTableMask) == in_character);
  848. if (total_samples_ < 1) return 1; // Division by zero.
  849. int freq_in_per128 =
  850. (frequencies_[in_character].counter() * 128) / total_samples_;
  851. return freq_in_per128;
  852. }
  853. private:
  854. class CharacterFrequency {
  855. public:
  856. CharacterFrequency() : counter_(0), character_(-1) { }
  857. explicit CharacterFrequency(int character)
  858. : counter_(0), character_(character) { }
  859. void Increment() { counter_++; }
  860. int counter() { return counter_; }
  861. int character() { return character_; }
  862. private:
  863. int counter_;
  864. int character_;
  865. };
  866. private:
  867. CharacterFrequency frequencies_[RegExpMacroAssembler::kTableSize];
  868. int total_samples_;
  869. };
  870. class RegExpCompiler {
  871. public:
  872. RegExpCompiler(int capture_count, bool ignore_case, bool is_ascii,
  873. Zone* zone);
  874. int AllocateRegister() {
  875. if (next_register_ >= RegExpMacroAssembler::kMaxRegister) {
  876. reg_exp_too_big_ = true;
  877. return next_register_;
  878. }
  879. return next_register_++;
  880. }
  881. RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler,
  882. RegExpNode* start,
  883. int capture_count,
  884. Handle<String> pattern);
  885. inline void AddWork(RegExpNode* node) { work_list_->Add(node); }
  886. static const int kImplementationOffset = 0;
  887. static const int kNumberOfRegistersOffset = 0;
  888. static const int kCodeOffset = 1;
  889. RegExpMacroAssembler* macro_assembler() { return macro_assembler_; }
  890. EndNode* accept() { return accept_; }
  891. static const int kMaxRecursion = 100;
  892. inline int recursion_depth() { return recursion_depth_; }
  893. inline void IncrementRecursionDepth() { recursion_depth_++; }
  894. inline void DecrementRecursionDepth() { recursion_depth_--; }
  895. void SetRegExpTooBig() { reg_exp_too_big_ = true; }
  896. inline bool ignore_case() { return ignore_case_; }
  897. inline bool ascii() { return ascii_; }
  898. FrequencyCollator* frequency_collator() { return &frequency_collator_; }
  899. int current_expansion_factor() { return current_expansion_factor_; }
  900. void set_current_expansion_factor(int value) {
  901. current_expansion_factor_ = value;
  902. }
  903. Zone* zone() const { return zone_; }
  904. static const int kNoRegister = -1;
  905. private:
  906. EndNode* accept_;
  907. int next_register_;
  908. List<RegExpNode*>* work_list_;
  909. int recursion_depth_;
  910. RegExpMacroAssembler* macro_assembler_;
  911. bool ignore_case_;
  912. bool ascii_;
  913. bool reg_exp_too_big_;
  914. int current_expansion_factor_;
  915. FrequencyCollator frequency_collator_;
  916. Zone* zone_;
  917. };
  918. class RecursionCheck {
  919. public:
  920. explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
  921. compiler->IncrementRecursionDepth();
  922. }
  923. ~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
  924. private:
  925. RegExpCompiler* compiler_;
  926. };
  927. static RegExpEngine::CompilationResult IrregexpRegExpTooBig(Isolate* isolate) {
  928. return RegExpEngine::CompilationResult(isolate, "RegExp too big");
  929. }
  930. // Attempts to compile the regexp using an Irregexp code generator. Returns
  931. // a fixed array or a null handle depending on whether it succeeded.
  932. RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case, bool ascii,
  933. Zone* zone)
  934. : next_register_(2 * (capture_count + 1)),
  935. work_list_(NULL),
  936. recursion_depth_(0),
  937. ignore_case_(ignore_case),
  938. ascii_(ascii),
  939. reg_exp_too_big_(false),
  940. current_expansion_factor_(1),
  941. frequency_collator_(),
  942. zone_(zone) {
  943. accept_ = new(zone) EndNode(EndNode::ACCEPT, zone);
  944. DCHECK(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
  945. }
  946. RegExpEngine::CompilationResult RegExpCompiler::Assemble(
  947. RegExpMacroAssembler* macro_assembler,
  948. RegExpNode* start,
  949. int capture_count,
  950. Handle<String> pattern) {
  951. Heap* heap = pattern->GetHeap();
  952. bool use_slow_safe_regexp_compiler = false;
  953. if (heap->total_regexp_code_generated() >
  954. RegExpImpl::kRegWxpCompiledLimit &&
  955. heap->isolate()->memory_allocator()->SizeExecutable() >
  956. RegExpImpl::kRegExpExecutableMemoryLimit) {
  957. use_slow_safe_regexp_compiler = true;
  958. }
  959. macro_assembler->set_slow_safe(use_slow_safe_regexp_compiler);
  960. #ifdef DEBUG
  961. if (FLAG_trace_regexp_assembler)
  962. macro_assembler_ = new RegExpMacroAssemblerTracer(macro_assembler);
  963. else
  964. #endif
  965. macro_assembler_ = macro_assembler;
  966. List <RegExpNode*> work_list(0);
  967. work_list_ = &work_list;
  968. Label fail;
  969. macro_assembler_->PushBacktrack(&fail);
  970. Trace new_trace;
  971. start->Emit(this, &new_trace);
  972. macro_assembler_->Bind(&fail);
  973. macro_assembler_->Fail();
  974. while (!work_list.is_empty()) {
  975. work_list.RemoveLast()->Emit(this, &new_trace);
  976. }
  977. if (reg_exp_too_big_) return IrregexpRegExpTooBig(zone_->isolate());
  978. Handle<HeapObject> code = macro_assembler_->GetCode(pattern);
  979. heap->IncreaseTotalRegexpCodeGenerated(code->Size());
  980. work_list_ = NULL;
  981. #ifdef DEBUG
  982. if (FLAG_print_code) {
  983. CodeTracer::Scope trace_scope(heap->isolate()->GetCodeTracer());
  984. OFStream os(trace_scope.file());
  985. Handle<Code>::cast(code)->Disassemble(pattern->ToCString().get(), os);
  986. }
  987. if (FLAG_trace_regexp_assembler) {
  988. delete macro_assembler_;
  989. }
  990. #endif
  991. return RegExpEngine::CompilationResult(*code, next_register_);
  992. }
  993. bool Trace::DeferredAction::Mentions(int that) {
  994. if (action_type() == ActionNode::CLEAR_CAPTURES) {
  995. Interval range = static_cast<DeferredClearCaptures*>(this)->range();
  996. return range.Contains(that);
  997. } else {
  998. return reg() == that;
  999. }
  1000. }
  1001. bool Trace::mentions_reg(int reg) {
  1002. for (DeferredAction* action = actions_;
  1003. action != NULL;
  1004. action = action->next()) {
  1005. if (action->Mentions(reg))
  1006. return true;
  1007. }
  1008. return false;
  1009. }
  1010. bool Trace::GetStoredPosition(int reg, int* cp_offset) {
  1011. DCHECK_EQ(0, *cp_offset);
  1012. for (DeferredAction* action = actions_;
  1013. action != NULL;
  1014. action = action->next()) {
  1015. if (action->Mentions(reg)) {
  1016. if (action->action_type() == ActionNode::STORE_POSITION) {
  1017. *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
  1018. return true;
  1019. } else {
  1020. return false;
  1021. }
  1022. }
  1023. }
  1024. return false;
  1025. }
  1026. int Trace::FindAffectedRegisters(OutSet* affected_registers,
  1027. Zone* zone) {
  1028. int max_register = RegExpCompiler::kNoRegister;
  1029. for (DeferredAction* action = actions_;
  1030. action != NULL;
  1031. action = action->next()) {
  1032. if (action->action_type() == ActionNode::CLEAR_CAPTURES) {
  1033. Interval range = static_cast<DeferredClearCaptures*>(action)->range();
  1034. for (int i = range.from(); i <= range.to(); i++)
  1035. affected_registers->Set(i, zone);
  1036. if (range.to() > max_register) max_register = range.to();
  1037. } else {
  1038. affected_registers->Set(action->reg(), zone);
  1039. if (action->reg() > max_register) max_register = action->reg();
  1040. }
  1041. }
  1042. return max_register;
  1043. }
  1044. void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
  1045. int max_register,
  1046. const OutSet& registers_to_pop,
  1047. const OutSet& registers_to_clear) {
  1048. for (int reg = max_register; reg >= 0; reg--) {
  1049. if (registers_to_pop.Get(reg)) {
  1050. assembler->PopRegister(reg);
  1051. } else if (registers_to_clear.Get(reg)) {
  1052. int clear_to = reg;
  1053. while (reg > 0 && registers_to_clear.Get(reg - 1)) {
  1054. reg--;
  1055. }
  1056. assembler->ClearRegisters(reg, clear_to);
  1057. }
  1058. }
  1059. }
  1060. void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
  1061. int max_register,
  1062. const OutSet& affected_registers,
  1063. OutSet* registers_to_pop,
  1064. OutSet* registers_to_clear,
  1065. Zone* zone) {
  1066. // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
  1067. const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
  1068. // Count pushes performed to force a stack limit check occasionally.
  1069. int pushes = 0;
  1070. for (int reg = 0; reg <= max_register; reg++) {
  1071. if (!affected_registers.Get(reg)) {
  1072. continue;
  1073. }
  1074. // The chronologically first deferred action in the trace
  1075. // is used to infer the action needed to restore a register
  1076. // to its previous state (or not, if it's safe to ignore it).
  1077. enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
  1078. DeferredActionUndoType undo_action = IGNORE;
  1079. int value = 0;
  1080. bool absolute = false;
  1081. bool clear = false;
  1082. int store_position = -1;
  1083. // This is a little tricky because we are scanning the actions in reverse
  1084. // historical order (newest first).
  1085. for (DeferredAction* action = actions_;
  1086. action != NULL;
  1087. action = action->next()) {
  1088. if (action->Mentions(reg)) {
  1089. switch (action->action_type()) {
  1090. case ActionNode::SET_REGISTER: {
  1091. Trace::DeferredSetRegister* psr =
  1092. static_cast<Trace::DeferredSetRegister*>(action);
  1093. if (!absolute) {
  1094. value += psr->value();
  1095. absolute = true;
  1096. }
  1097. // SET_REGISTER is currently only used for newly introduced loop
  1098. // counters. They can have a significant previous value if they
  1099. // occour in a loop. TODO(lrn): Propagate this information, so
  1100. // we can set undo_action to IGNORE if we know there is no value to
  1101. // restore.
  1102. undo_action = RESTORE;
  1103. DCHECK_EQ(store_position, -1);
  1104. DCHECK(!clear);
  1105. break;
  1106. }
  1107. case ActionNode::INCREMENT_REGISTER:
  1108. if (!absolute) {
  1109. value++;
  1110. }
  1111. DCHECK_EQ(store_position, -1);
  1112. DCHECK(!clear);
  1113. undo_action = RESTORE;
  1114. break;
  1115. case ActionNode::STORE_POSITION: {
  1116. Trace::DeferredCapture* pc =
  1117. static_cast<Trace::DeferredCapture*>(action);
  1118. if (!clear && store_position == -1) {
  1119. store_position = pc->cp_offset();
  1120. }
  1121. // For captures we know that stores and clears alternate.
  1122. // Other register, are never cleared, and if the occur
  1123. // inside a loop, they might be assigned more than once.
  1124. if (reg <= 1) {
  1125. // Registers zero and one, aka "capture zero", is
  1126. // always set correctly if we succeed. There is no
  1127. // need to undo a setting on backtrack, because we
  1128. // will set it again or fail.
  1129. undo_action = IGNORE;
  1130. } else {
  1131. undo_action = pc->is_capture() ? CLEAR : RESTORE;
  1132. }
  1133. DCHECK(!absolute);
  1134. DCHECK_EQ(value, 0);
  1135. break;
  1136. }
  1137. case ActionNode::CLEAR_CAPTURES: {
  1138. // Since we're scanning in reverse order, if we've already
  1139. // set the position we have to ignore historically earlier
  1140. // clearing operations.
  1141. if (store_position == -1) {
  1142. clear = true;
  1143. }
  1144. undo_action = RESTORE;
  1145. DCHECK(!absolute);
  1146. DCHECK_EQ(value, 0);
  1147. break;
  1148. }
  1149. default:
  1150. UNREACHABLE();
  1151. break;
  1152. }
  1153. }
  1154. }
  1155. // Prepare for the undo-action (e.g., push if it's going to be popped).
  1156. if (undo_action == RESTORE) {
  1157. pushes++;
  1158. RegExpMacroAssembler::StackCheckFlag stack_check =
  1159. RegExpMacroAssembler::kNoStackLimitCheck;
  1160. if (pushes == push_limit) {
  1161. stack_check = RegExpMacroAssembler::kCheckStackLimit;
  1162. pushes = 0;
  1163. }
  1164. assembler->PushRegister(reg, stack_check);
  1165. registers_to_pop->Set(reg, zone);
  1166. } else if (undo_action == CLEAR) {
  1167. registers_to_clear->Set(reg, zone);
  1168. }
  1169. // Perform the chronologically last action (or accumulated increment)
  1170. // for the register.
  1171. if (store_position != -1) {
  1172. assembler->WriteCurrentPositionToRegister(reg, store_position);
  1173. } else if (clear) {
  1174. assembler->ClearRegisters(reg, reg);
  1175. } else if (absolute) {
  1176. assembler->SetRegister(reg, value);
  1177. } else if (value != 0) {
  1178. assembler->AdvanceRegister(reg, value);
  1179. }
  1180. }
  1181. }
  1182. // This is called as we come into a loop choice node and some other tricky
  1183. // nodes. It normalizes the state of the code generator to ensure we can
  1184. // generate generic code.
  1185. void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
  1186. RegExpMacroAssembler* assembler = compiler->macro_assembler();
  1187. DCHECK(!is_trivial());
  1188. if (actions_ == NULL && backtrack() == NULL) {
  1189. // Here we just have some deferred cp advances to fix and we are back to
  1190. // a normal situation. We may also have to forget some information gained
  1191. // through a quick check that was already performed.
  1192. if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
  1193. // Create a new trivial state and generate the node with that.
  1194. Trace new_state;
  1195. successor->Emit(compiler, &new_state);
  1196. return;
  1197. }
  1198. // Generate deferred actions here along with code to undo them again.
  1199. OutSet affected_registers;
  1200. if (backtrack() != NULL) {
  1201. // Here we have a concrete backtrack location. These are set up by choice
  1202. // nodes and so they indicate that we have a deferred save of the current
  1203. // position which we may need to emit here.
  1204. assembler->PushCurrentPosition();
  1205. }
  1206. int max_register = FindAffectedRegisters(&affected_registers,
  1207. compiler->zone());
  1208. OutSet registers_to_pop;
  1209. OutSet registers_to_clear;
  1210. PerformDeferredActions(assembler,
  1211. max_register,
  1212. affected_registers,
  1213. &registers_to_pop,
  1214. &registers_to_clear,
  1215. compiler->zone());
  1216. if (cp_offset_ != 0) {
  1217. assembler->AdvanceCurrentPosition(cp_offset_);
  1218. }
  1219. // Create a new trivial state and generate the node with that.
  1220. Label undo;
  1221. assembler->PushBacktrack(&undo);
  1222. Trace new_state;
  1223. successor->Emit(compiler, &new_state);
  1224. // On backtrack we need to restore state.
  1225. assembler->Bind(&undo);
  1226. RestoreAffectedRegisters(assembler,
  1227. max_register,
  1228. registers_to_pop,
  1229. registers_to_clear);
  1230. if (backtrack() == NULL) {
  1231. assembler->Backtrack();
  1232. } else {
  1233. assembler->PopCurrentPosition();
  1234. assembler->GoTo(backtrack());
  1235. }
  1236. }
  1237. void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
  1238. RegExpMacroAssembler* assembler = compiler->macro_assembler();
  1239. // Omit flushing the trace. We discard the entire stack frame anyway.
  1240. if (!label()->is_bound()) {
  1241. // We are completely independent of the trace, since we ignore it,
  1242. // so this code can be used as the generic version.
  1243. assembler->Bind(label());
  1244. }
  1245. // Throw away everything on the backtrack stack since the start
  1246. // of the negative submatch and restore the character position.
  1247. assembler->ReadCurrentPositionFromRegister(current_position_register_);
  1248. assembler->ReadStackPointerFromRegister(stack_pointer_register_);
  1249. if (clear_capture_count_ > 0) {
  1250. // Clear any captures that might have been performed during the success
  1251. // of the body of the negative look-ahead.
  1252. int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
  1253. assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
  1254. }
  1255. // Now that we have unwound the stack we find at the top of the stack the
  1256. // backtrack that the BeginSubmatch node got.
  1257. assembler->Backtrack();
  1258. }
  1259. void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
  1260. if (!trace->is_trivial()) {
  1261. trace->Flush(compiler, this);
  1262. return;
  1263. }
  1264. RegExpMacroAssembler* assembler = compiler->macro_assembler();
  1265. if (!label()->is_bound()) {
  1266. assembler->Bind(label());
  1267. }
  1268. switch (action_) {
  1269. case ACCEPT:
  1270. assembler->Succeed();
  1271. return;
  1272. case BACKTRACK:
  1273. assembler->GoTo(trace->backtrack());
  1274. return;
  1275. case NEGATIVE_SUBMATCH_SUCCESS:
  1276. // This case is handled in a different virtual method.
  1277. UNREACHABLE();
  1278. }
  1279. UNIMPLEMENTED();
  1280. }
  1281. void GuardedAlternative::AddGuard(Guard* guard, Zone* zone) {
  1282. if (guards_ == NULL)
  1283. guards_ = new(zone) ZoneList<Guard*>(1, zone);
  1284. guards_->Add(guard, zone);
  1285. }
  1286. ActionNode* ActionNode::SetRegister(int reg,
  1287. int val,
  1288. RegExpNode* on_success) {
  1289. ActionNode* result =
  1290. new(on_success->zone()) ActionNode(SET_REGISTER, on_success);
  1291. result->data_.u_store_register.reg = reg;
  1292. result->data_.u_store_register.value = val;
  1293. return result;
  1294. }
  1295. ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
  1296. ActionNode* result =
  1297. new(on_success->zone()) ActionNode(INCREMENT_REGISTER, on_success);
  1298. result->data_.u_increment_register.reg = reg;
  1299. return result;
  1300. }
  1301. ActionNode* ActionNode::StorePosition(int reg,
  1302. bool is_capture,
  1303. RegExpNode* on_success) {
  1304. ActionNode* result =
  1305. new(on_success->zone()) ActionNode(STORE_POSITION, on_success);
  1306. result->data_.u_position_register.reg = reg;
  1307. result->data_.u_position_register.is_capture = is_capture;
  1308. return result;
  1309. }
  1310. ActionNode* ActionNode::ClearCaptures(Interval range,
  1311. RegExpNode* on_success) {
  1312. ActionNode* result =
  1313. new(on_success->zone()) ActionNode(CLEAR_CAPTURES, on_success);
  1314. result->data_.u_clear_captures.range_from = range.from();
  1315. result->data_.u_clear_captures.range_to = range.to();
  1316. return result;
  1317. }
  1318. ActionNode* ActionNode::BeginSubmatch(int stack_reg,
  1319. int position_reg,
  1320. RegExpNode* on_success) {
  1321. ActionNode* result =
  1322. new(on_success->zone()) ActionNode(BEGIN_SUBMATCH, on_success);
  1323. result->data_.u_submatch.stack_pointer_register = stack_reg;
  1324. result->data_.u_submatch.current_position_register = position_reg;
  1325. return result;
  1326. }
  1327. ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
  1328. int position_reg,
  1329. int clear_register_count,
  1330. int clear_register_from,
  1331. RegExpNode* on_success) {
  1332. ActionNode* result =
  1333. new(on_success->zone()) ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
  1334. result->data_.u_submatch.stack_pointer_register = stack_reg;
  1335. result->data_.u_submatch.current_position_register = position_reg;
  1336. result->data_.u_submatch.clear_register_count = clear_register_count;
  1337. result->data_.u_submatch.clear_register_from = clear_register_from;
  1338. return result;
  1339. }
  1340. ActionNode* ActionNode::EmptyMatchCheck(int start_register,
  1341. int repetition_register,
  1342. int repetition_limit,
  1343. RegExpNode* on_success) {
  1344. ActionNode* result =
  1345. new(on_success->zone()) ActionNode(EMPTY_MATCH_CHECK, on_success);
  1346. result->data_.u_empty_match_check.start_register = start_register;
  1347. result->data_.u_empty_match_check.repetition_register = repetition_register;
  1348. result->data_.u_empty_match_check.repetition_limit = repetition_limit;
  1349. return result;
  1350. }
  1351. #define DEFINE_ACCEPT(Type) \
  1352. void Type##Node::Accept(NodeVisitor* visitor) { \
  1353. visitor->Visit##Type(this); \
  1354. }
  1355. FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
  1356. #undef DEFINE_ACCEPT
  1357. void LoopChoiceNode::Accept(NodeVisitor* visitor) {
  1358. visitor->VisitLoopChoice(this);
  1359. }
  1360. // -------------------------------------------------------------------
  1361. // Emit code.
  1362. void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
  1363. Guard* guard,
  1364. Trace* trace) {
  1365. switch (guard->op()) {
  1366. case Guard::LT:
  1367. DCHECK(!trace->mentions_reg(guard->reg()));
  1368. macro_assembler->IfRegisterGE(guard->reg(),
  1369. guard->value(),
  1370. trace->backtrack());
  1371. break;
  1372. case Guard::GEQ:
  1373. DCHECK(!trace->mentions_reg(guard->reg()));
  1374. macro_assembler->IfRegisterLT(guard->reg(),
  1375. guard->value(),
  1376. trace->backtrack());
  1377. break;
  1378. }
  1379. }
  1380. // Returns the number of characters in the equivalence class, omitting those
  1381. // that cannot occur in the source string because it is ASCII.
  1382. static int GetCaseIndependentLetters(Isolate* isolate,
  1383. uc16 character,
  1384. bool ascii_subject,
  1385. unibrow::uchar* letters) {
  1386. int length =
  1387. isolate->jsregexp_uncanonicalize()->get(character, '\0', letters);
  1388. // Unibrow returns 0 or 1 for characters where case independence is
  1389. // trivial.
  1390. if (length == 0) {
  1391. letters[0] = character;
  1392. length = 1;
  1393. }
  1394. if (!ascii_subject || character <= String::kMaxOneByteCharCode) {
  1395. return length;
  1396. }
  1397. // The standard requires that non-ASCII characters cannot have ASCII
  1398. // character codes in their equivalence class.
  1399. return 0;
  1400. }
  1401. static inline bool EmitSimpleCharacter(Isolate* isolate,
  1402. RegExpCompiler* compiler,
  1403. uc16 c,
  1404. Label* on_failure,
  1405. int cp_offset,
  1406. bool check,
  1407. bool preloaded) {
  1408. RegExpMacroAssembler* assembler = compiler->macro_assembler();
  1409. bool bound_checked = false;
  1410. if (!preloaded) {
  1411. assembler->LoadCurrentCharacter(
  1412. cp_offset,
  1413. on_failure,
  1414. check);
  1415. bound_checked = true;
  1416. }
  1417. assembler->CheckNotCharacter(c, on_failure);
  1418. return bound_checked;
  1419. }
  1420. // Only emits non-letters (things that don't have case). Only used for case
  1421. // independent matches.
  1422. static inline bool EmitAtomNonLetter(Isolate* isolate,
  1423. RegExpCompiler* compiler,
  1424. uc16 c,
  1425. Label* on_failure,
  1426. int cp_offset,
  1427. bool check,
  1428. bool preloaded) {
  1429. RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
  1430. bool ascii = compiler->ascii();
  1431. unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
  1432. int length = GetCaseIndependentLetters(isolate, c, ascii, chars);
  1433. if (length < 1) {
  1434. // This can't match. Must be an ASCII subject and a non-ASCII character.
  1435. // We do not need to do anything since the ASCII pass already handled this.
  1436. return false; // Bounds not checked.
  1437. }
  1438. bool checked = false;
  1439. // We handle the length > 1 case in a later pass.
  1440. if (length == 1) {
  1441. if (ascii && c > String::kMaxOneByteCharCodeU) {
  1442. // Can't match - see above.
  1443. return false; // Bounds not checked.
  1444. }
  1445. if (!preloaded) {
  1446. macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
  1447. checked = check;
  1448. }
  1449. macro_assembler->CheckNotCharacter(c, on_failure);
  1450. }
  1451. return checked;
  1452. }
  1453. static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
  1454. bool ascii,
  1455. uc16 c1,
  1456. uc16 c2,
  1457. Label* on_failure) {
  1458. uc16 char_mask;
  1459. if (ascii) {
  1460. char_mask = String::kMaxOneByteCharCode;
  1461. } else {
  1462. char_mask = String::kMaxUtf16CodeUnit;
  1463. }
  1464. uc16 exor = c1 ^ c2;
  1465. // Check whether exor has only one bit set.
  1466. if (((exor - 1) & exor) == 0) {
  1467. // If c1 and c2 differ only by one bit.
  1468. // Ecma262UnCanonicalize always gives the highest number last.
  1469. DCHECK(c2 > c1);
  1470. uc16 mask = char_mask ^ exor;
  1471. macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
  1472. return true;
  1473. }
  1474. DCHECK(c2 > c1);
  1475. uc16 diff = c2 - c1;
  1476. if (((diff - 1) & diff) == 0 && c1 >= diff) {
  1477. // If the characters differ by 2^n but don't differ by one bit then
  1478. // subtract the difference from the found character, then do the or
  1479. // trick. We avoid the theoretical case where negative numbers are
  1480. // involved in order to simplify code generation.
  1481. uc16 mask = char_mask ^ diff;
  1482. macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff,
  1483. diff,
  1484. mask,
  1485. on_failure);
  1486. return true;
  1487. }
  1488. return false;
  1489. }
  1490. typedef bool EmitCharacterFunction(Isolate* isolate,
  1491. RegExpCompiler* compiler,
  1492. uc16 c,
  1493. Label* on_failure,
  1494. int cp_offset,
  1495. bool check,
  1496. bool preloaded);
  1497. // Only emits letters (things that have case). Only used for case independent
  1498. // matches.
  1499. static inline bool EmitAtomLetter(Isolate* isolate,
  1500. RegExpCompiler* compiler,
  1501. uc16 c,
  1502. Label* on_failure,
  1503. int cp_offset,
  1504. bool check,
  1505. bool preloaded) {
  1506. RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
  1507. bool ascii = compiler->ascii();
  1508. unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
  1509. int length = GetCaseIndependentLetters(isolate, c, ascii, chars);
  1510. if (length <= 1) return false;
  1511. // We may not need to check against the end of the input string
  1512. // if this character lies before a character that matched.
  1513. if (!preloaded) {
  1514. macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
  1515. }
  1516. Label ok;
  1517. DCHECK(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4);
  1518. switch (length) {
  1519. case 2: {
  1520. if (ShortCutEmitCharacterPair(macro_assembler,
  1521. ascii,
  1522. chars[0],
  1523. chars[1],
  1524. on_failure)) {
  1525. } else {
  1526. macro_assembler->CheckCharacter(chars[0], &ok);
  1527. macro_assembler->CheckNotCharacter(chars[1], on_failure);
  1528. macro_assembler->Bind(&ok);
  1529. }
  1530. break;
  1531. }
  1532. case 4:
  1533. macro_assembler->CheckCharacter(chars[3], &ok);
  1534. // Fall through!
  1535. case 3:
  1536. macro_assembler->CheckCharacter(chars[0], &ok);
  1537. macro_assembler->CheckCharacter(chars[1], &ok);
  1538. macro_assembler->CheckNotCharacter(chars[2], on_failure);
  1539. macro_assembler->Bind(&ok);
  1540. break;
  1541. default:
  1542. UNREACHABLE();
  1543. break;
  1544. }
  1545. return true;
  1546. }
  1547. static void EmitBoundaryTest(RegExpMacroAssembler* masm,
  1548. int border,
  1549. Label* fall_through,
  1550. Label* above_or_equal,
  1551. Label* below) {
  1552. if (below != fall_through) {
  1553. masm->CheckCharacterLT(border, below);
  1554. if (above_or_equal != fall_through) masm->GoTo(above_or_equal);
  1555. } else {
  1556. masm->CheckCharacterGT(border - 1, above_or_equal);
  1557. }
  1558. }
  1559. static void EmitDoubleBoundaryTest(RegExpMacroAssembler* masm,
  1560. int first,
  1561. int last,
  1562. Label* fall_through,
  1563. Label* in_range,
  1564. Label* out_of_range) {
  1565. if (in_range == fall_through) {
  1566. if (first == last) {
  1567. masm->CheckNotCharacter(first, out_of_range);
  1568. } else {
  1569. masm->CheckCharacterNotInRange(first, last, out_of_range);
  1570. }
  1571. } else {
  1572. if (first == last) {
  1573. masm->CheckCharacter(first, in_range);
  1574. } else {
  1575. masm->CheckCharacterInRange(first, last, in_range);
  1576. }
  1577. if (out_of_range != fall_through) masm->GoTo(out_of_range);
  1578. }
  1579. }
  1580. // even_label is for ranges[i] to ranges[i + 1] where i - start_index is even.
  1581. // odd_label is for ranges[i] to ranges[i + 1] where i - start_index is odd.
  1582. static void EmitUseLookupTable(
  1583. RegExpMacroAssembler* masm,
  1584. ZoneList<int>* ranges,
  1585. int start_index,
  1586. int end_index,
  1587. int min_char,
  1588. Label* fall_through,
  1589. Label* even_label,
  1590. Label* odd_label) {
  1591. static const int kSize = RegExpMacroAssembler::kTableSize;
  1592. static const int kMask = RegExpMacroAssembler::kTableMask;
  1593. int base = (min_char & ~kMask);
  1594. USE(base);
  1595. // Assert that everything is on one kTableSize page.
  1596. for (int i = start_index; i <= end_index; i++) {
  1597. DCHECK_EQ(ranges->at(i) & ~kMask, base);
  1598. }
  1599. DCHECK(start_index == 0 || (ranges->at(start_index - 1) & ~kMask) <= base);
  1600. char templ[kSize];
  1601. Label* on_bit_set;
  1602. Label* on_bit_clear;
  1603. int bit;
  1604. if (even_label == fall_through) {
  1605. on_bit_set = odd_label;
  1606. on_bit_clear = even_label;
  1607. bit = 1;
  1608. } else {
  1609. on_bit_set = even_label;
  1610. on_bit_clear = odd_label;
  1611. bit = 0;
  1612. }
  1613. for (int i = 0; i < (ranges->at(start_index) & kMask) && i < kSize; i++) {
  1614. templ[i] = bit;
  1615. }
  1616. int j = 0;
  1617. bit ^= 1;
  1618. for (int i = start_index; i < end_index; i++) {
  1619. for (j = (ranges->at(i) & kMask); j < (ranges->at(i + 1) & kMask); j++) {
  1620. templ[j] = bit;
  1621. }
  1622. bit ^= 1;
  1623. }
  1624. for (int i = j; i < kSize; i++) {
  1625. templ[i] = bit;
  1626. }
  1627. Factory* factory = masm->zone()->isolate()->factory();
  1628. // TODO(erikcorry): Cache these.
  1629. Handle<ByteArray> ba = factory->NewByteArray(kSize, TENURED);
  1630. for (int i = 0; i < kSize; i++) {
  1631. ba->set(i, templ[i]);
  1632. }
  1633. masm->CheckBitInTable(ba, on_bit_set);
  1634. if (on_bit_clear != fall_through) masm->GoTo(on_bit_clear);
  1635. }
  1636. static void CutOutRange(RegExpMacroAssembler* masm,
  1637. ZoneList<int>* ranges,
  1638. int start_index,
  1639. int end_index,
  1640. int cut_index,
  1641. Label* even_label,
  1642. Label* odd_label) {
  1643. bool odd = (((cut_index - start_index) & 1) == 1);
  1644. Label* in_range_label = odd ? odd_label : even_label;
  1645. Label dummy;
  1646. EmitDoubleBoundaryTest(masm,
  1647. ranges->at(cut_index),
  1648. ranges->at(cut_index + 1) - 1,
  1649. &dummy,
  1650. in_range_label,
  1651. &dummy);
  1652. DCHECK(!dummy.is_linked());
  1653. // Cut out the single range by rewriting the array. This creates a new
  1654. // range that is a merger of the two ranges on either side of the one we
  1655. // are cutting out. The oddity of the labels is preserved.
  1656. for (int j = cut_index; j > start_index; j--) {
  1657. ranges->at(j) = ranges->at(j - 1);
  1658. }
  1659. for (int j = cut_index + 1; j < end_index; j++) {
  1660. ranges->at(j) = ranges->at(j + 1);
  1661. }
  1662. }
  1663. // Unicode case. Split the search space into kSize spaces that are handled
  1664. // with recursion.
  1665. static void SplitSearchSpace(ZoneList<int>* ranges,
  1666. int start_index,
  1667. int end_index,
  1668. int* new_start_index,
  1669. int* new_end_index,
  1670. int* border) {
  1671. static const int kSize = RegExpMacroAssembler::kTableSize;
  1672. static const int kMask = RegExpMacroAssembler::kTableMask;
  1673. int first = ranges->at(start_index);
  1674. int last = ranges->at(end_index) - 1;
  1675. *new_start_index = start_index;
  1676. *border = (ranges->at(start_index) & ~kMask) + kSize;
  1677. while (*new_start_index < end_index) {
  1678. if (ranges->at(*new_start_index) > *border) break;
  1679. (*new_start_index)++;
  1680. }
  1681. // new_start_index is the index of the first edge that is beyond the
  1682. // current kSize space.
  1683. // For very large search spaces we do a binary chop search of the non-ASCII
  1684. // space instead of just going to the end of the current kSize space. The
  1685. // heuristics are complicated a little by the fact that any 128-character
  1686. // encoding space can be quickly tested with a table lookup, so we don't
  1687. // wish to do binary chop search at a smaller granularity than that. A
  1688. // 128-character space can take up a lot of space in the ranges array if,
  1689. // for example, we only want to match every second character (eg. the lower
  1690. // case characters on some Unicode pages).
  1691. int binary_chop_index = (end_index + start_index) / 2;
  1692. // The first test ensures that we get to the code that handles the ASCII
  1693. // range with a single not-taken branch, speeding up this important
  1694. // character range (even non-ASCII charset-based text has spaces and
  1695. // punctuation).
  1696. if (*border - 1 > String::kMaxOneByteCharCode && // ASCII case.
  1697. end_index - start_index > (*new_start_index - start_index) * 2 &&
  1698. last - first > kSize * 2 &&
  1699. binary_chop_index > *new_start_index &&
  1700. ranges->at(binary_chop_index) >= first + 2 * kSize) {
  1701. int scan_forward_for_section_border = binary_chop_index;;
  1702. int new_border = (ranges->at(binary_chop_index) | kMask) + 1;
  1703. while (scan_forward_for_section_border < end_index) {
  1704. if (ranges->at(scan_forward_for_section_border) > new_border) {
  1705. *new_start_index = scan_forward_for_section_border;
  1706. *border = new_border;
  1707. break;
  1708. }
  1709. scan_forward_for_section_border++;
  1710. }
  1711. }
  1712. DCHECK(*new_start_index > start_index);
  1713. *new_end_index = *new_start_index - 1;
  1714. if (ranges->at(*new_end_index) == *border) {
  1715. (*new_end_index)--;
  1716. }
  1717. if (*border >= ranges->at(end_index)) {
  1718. *border = ranges->at(end_index);
  1719. *new_start_index = end_index; // Won't be used.
  1720. *new_end_index = end_index - 1;
  1721. }
  1722. }
  1723. // Gets a series of segment boundaries representing a character class. If the
  1724. // character is in the range between an even and an odd boundary (counting from
  1725. // start_index) then go to even_label, otherwise go to odd_label. We already
  1726. // know that the character is in the range of min_char to max_char inclusive.
  1727. // Either label can be NULL indicating backtracking. Either label can also be
  1728. // equal to the fall_through label.
  1729. static void GenerateBranches(RegExpMacroAssembler* masm,
  1730. ZoneList<int>* ranges,
  1731. int start_index,
  1732. int end_index,
  1733. uc16 min_char,
  1734. uc16 max_char,
  1735. Label* fall_through,
  1736. Label* even_label,
  1737. Label* odd_label) {
  1738. int first = ranges->at(start_index);
  1739. int last = ranges->at(end_index) - 1;
  1740. DCHECK_LT(min_char, first);
  1741. // Just need to test if the character is before or on-or-after
  1742. // a particular character.
  1743. if (start_index == end_index) {
  1744. EmitBoundaryTest(masm, first, fall_through, even_label, odd_label);
  1745. return;
  1746. }
  1747. // Another almost trivial case: There is one interval in the middle that is
  1748. // different from the end intervals.
  1749. if (start_index + 1 == end_index) {
  1750. EmitDoubleBoundaryTest(
  1751. masm, first, last, fall_through, even_label, odd_label);
  1752. return;
  1753. }
  1754. // It's not worth using table lookup if there are very few intervals in the
  1755. // character class.
  1756. if (end_index - start_index <= 6) {
  1757. // It is faster to test for individual characters, so we look for those
  1758. // first, then try arbitrary ranges in the second round.
  1759. static int kNoCutIndex = -1;
  1760. int cut = kNoCutIndex;
  1761. for (int i = start_index; i < end_index; i++) {
  1762. if (ranges->at(i) == ranges->at(i + 1) - 1) {
  1763. cut = i;
  1764. break;
  1765. }
  1766. }
  1767. if (cut == kNoCutIndex) cut = start_index;
  1768. CutOutRange(
  1769. masm, ranges, start_index, end_index, cut, even_label, odd_label);
  1770. DCHECK_GE(end_index - start_index, 2);
  1771. GenerateBranches(masm,
  1772. ranges,
  1773. start_index + 1,
  1774. end_index - 1,
  1775. min_char,
  1776. max_char,
  1777. fall_through,
  1778. even_label,
  1779. odd_label);
  1780. return;
  1781. }
  1782. // If there are a lot of intervals in the regexp, then we will use tables to
  1783. // determine whether the character is inside or outside the character class.
  1784. static const int kBits = RegExpMacroAssembler::kTableSizeBits;
  1785. if ((max_char >> kBits) == (min_char >> kBits)) {
  1786. EmitUseLookupTable(masm,
  1787. ranges,
  1788. start_index,
  1789. end_index,
  1790. min_char,
  1791. fall_through,
  1792. even_label,
  1793. odd_label);
  1794. return;
  1795. }
  1796. if ((min_char >> kBits) != (first >> kBits)) {
  1797. masm->CheckCharacterLT(first, odd_label);
  1798. GenerateBranches(masm,
  1799. ranges,
  1800. start_index + 1,
  1801. end_index,
  1802. first,
  1803. max_char,
  1804. fall_through,
  1805. odd_label,
  1806. even_label);
  1807. return;
  1808. }
  1809. int new_start_index = 0;
  1810. int new_end_index = 0;
  1811. int border = 0;
  1812. SplitSearchSpace(ranges,
  1813. start_index,
  1814. end_index,
  1815. &new_start_index,
  1816. &new_end_index,
  1817. &border);
  1818. Label handle_rest;
  1819. Label* above = &handle_rest;
  1820. if (border == last + 1) {
  1821. // We didn't find any section that started after the limit, so everything
  1822. // above the border is one of the terminal labels.
  1823. above = (end_index & 1) != (start_index & 1) ? odd_label : even_label;
  1824. DCHECK(new_end_index == end_index - 1);
  1825. }
  1826. DCHECK_LE(start_index, new_end_index);
  1827. DCHECK_LE(new_start_index, end_index);
  1828. DCHECK_LT(start_index, new_start_index);
  1829. DCHECK_LT(new_end_index, end_index);
  1830. DCHECK(new_end_index + 1 == new_start_index ||
  1831. (new_end_index + 2 == new_start_index &&
  1832. border == ranges->at(new_end_index + 1)));
  1833. DCHECK_LT(min_char, border - 1);
  1834. DCHECK_LT(border, max_char);
  1835. DCHECK_LT(ranges->at(new_end_index), border);
  1836. DCHECK(border < ranges->at(new_start_index) ||
  1837. (border == ranges->at(new_start_index) &&
  1838. new_start_index == end_index &&
  1839. new_end_index == end_index - 1 &&
  1840. border == last + 1));
  1841. DCHECK(new_start_index == 0 || border >= ranges->at(new_start_index - 1));
  1842. masm->CheckCharacterGT(border - 1, above);
  1843. Label dummy;
  1844. GenerateBranches(masm,
  1845. ranges,
  1846. start_index,
  1847. new_end_index,
  1848. min_char,
  1849. border - 1,
  1850. &dummy,
  1851. even_label,
  1852. odd_label);
  1853. if (handle_rest.is_linked()) {
  1854. masm->Bind(&handle_rest);
  1855. bool flip = (new_start_index & 1) != (start_index & 1);
  1856. GenerateBranches(masm,
  1857. ranges,
  1858. new_start_index,
  1859. end_index,
  1860. border,
  1861. max_char,
  1862. &dummy,
  1863. flip ? odd_label : even_label,
  1864. flip ? even_label : odd_label);
  1865. }
  1866. }
  1867. static void EmitCharClass(RegExpMacroAssembler* macro_assembler,
  1868. RegExpCharacterClass* cc,
  1869. bool ascii,
  1870. Label* on_failure,
  1871. int cp_offset,
  1872. bool check_offset,
  1873. bool preloaded,
  1874. Zone* zone) {
  1875. ZoneList<CharacterRange>* ranges = cc->ranges(zone);
  1876. if (!CharacterRange::IsCanonical(ranges)) {
  1877. CharacterRange::Canonicalize(ranges);
  1878. }
  1879. int max_char;
  1880. if (ascii) {
  1881. max_char = String::kMaxOneByteCharCode;
  1882. } else {
  1883. max_char = String::kMaxUtf16CodeUnit;
  1884. }
  1885. int range_count = ranges->length();
  1886. int last_valid_range = range_count - 1;
  1887. while (last_valid_range >= 0) {
  1888. CharacterRange& range = ranges->at(last_valid_range);
  1889. if (range.from() <= max_char) {
  1890. break;
  1891. }
  1892. last_valid_range--;
  1893. }
  1894. if (last_valid_range < 0) {
  1895. if (!cc->is_negated()) {
  1896. macro_assembler->GoTo(on_failure);
  1897. }
  1898. if (check_offset) {
  1899. macro_assembler->CheckPosition(cp_offset, on_failure);
  1900. }
  1901. return;
  1902. }
  1903. if (last_valid_range == 0 &&
  1904. ranges->at(0).IsEverything(max_char)) {
  1905. if (cc->is_negated()) {
  1906. macro_assembler->GoTo(on_failure);
  1907. } else {
  1908. // This is a common case hit by non-anchored expressions.
  1909. if (check_offset) {
  1910. macro_assembler->CheckPosition(cp_offset, on_failure);
  1911. }
  1912. }
  1913. return;
  1914. }
  1915. if (last_valid_range == 0 &&
  1916. !cc->is_negated() &&
  1917. ranges->at(0).IsEverything(max_char)) {
  1918. // This is a common case hit by non-anchored expressions.
  1919. if (check_offset) {
  1920. macro_assembler->CheckPosition(cp_offset, on_failure);
  1921. }
  1922. return;
  1923. }
  1924. if (!preloaded) {
  1925. macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset);
  1926. }
  1927. if (cc->is_standard(zone) &&
  1928. macro_assembler->CheckSpecialCharacterClass(cc->standard_type(),
  1929. on_failure)) {
  1930. return;
  1931. }
  1932. // A new list with ascending entries. Each entry is a code unit
  1933. // where there is a boundary between code units that are part of
  1934. // the class and code units that are not. Normally we insert an
  1935. // entry at zero which goes to the failure label, but if there
  1936. // was already one there we fall through for success on that entry.
  1937. // Subsequent entries have alternating meaning (success/failure).
  1938. ZoneList<int>* range_boundaries =
  1939. new(zone) ZoneList<int>(last_valid_range, zone);
  1940. bool zeroth_entry_is_failure = !cc->is_negated();
  1941. for (int i = 0; i <= last_valid_range; i++) {
  1942. CharacterRange& range = ranges->at(i);
  1943. if (range.from() == 0) {
  1944. DCHECK_EQ(i, 0);
  1945. zeroth_entry_is_failure = !zeroth_entry_is_failure;
  1946. } else {
  1947. range_boundaries->Add(range.from(), zone);
  1948. }
  1949. range_boundaries->Add(range.to() + 1, zone);
  1950. }
  1951. int end_index = range_boundaries->length() - 1;
  1952. if (range_boundaries->at(end_index) > max_char) {
  1953. end_index--;
  1954. }
  1955. Label fall_through;
  1956. GenerateBranches(macro_assembler,
  1957. range_boundaries,
  1958. 0, // start_index.
  1959. end_index,
  1960. 0, // min_char.
  1961. max_char,
  1962. &fall_through,
  1963. zeroth_entry_is_failure ? &fall_through : on_failure,
  1964. zeroth_entry_is_failure ? on_failure : &fall_through);
  1965. macro_assembler->Bind(&fall_through);
  1966. }
  1967. RegExpNode::~RegExpNode() {
  1968. }
  1969. RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler,
  1970. Trace* trace) {
  1971. // If we are generating a greedy loop then don't stop and don't reuse code.
  1972. if (trace->stop_node() != NULL) {
  1973. return CONTINUE;
  1974. }
  1975. RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
  1976. if (trace->is_trivial()) {
  1977. if (label_.is_bound()) {
  1978. // We are being asked to generate a generic version, but that's already
  1979. // been done so just go to it.
  1980. macro_assembler->GoTo(&label_);
  1981. return DONE;
  1982. }
  1983. if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) {
  1984. // To avoid too deep recursion we push the node to the work queue and just
  1985. // generate a goto here.
  1986. compiler->AddWork(this);
  1987. macro_assembler->GoTo(&label_);
  1988. return DONE;
  1989. }
  1990. // Generate generic version of the node and bind the label for later use.
  1991. macro_assembler->Bind(&label_);
  1992. return CONTINUE;
  1993. }
  1994. // We are being asked to make a non-generic version. Keep track of how many
  1995. // non-generic versions we generate so as not to overdo it.
  1996. trace_count_++;
  1997. if (FLAG_regexp_optimization &&
  1998. trace_count_ < kMaxCopiesCodeGenerated &&
  1999. compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) {
  2000. return CONTINUE;
  2001. }
  2002. // If we get here code has been generated for this node too many times or
  2003. // recursion is too deep. Time to switch to a generic version. The code for
  2004. // generic versions above can handle deep recursion properly.
  2005. trace->Flush(compiler, this);
  2006. return DONE;
  2007. }
  2008. int ActionNode::EatsAtLeast(int still_to_find,
  2009. int budget,
  2010. bool not_at_start) {
  2011. if (budget <= 0) return 0;
  2012. if (action_type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input!
  2013. return on_success()->EatsAtLeast(still_to_find,
  2014. budget - 1,
  2015. not_at_start);
  2016. }
  2017. void ActionNode::FillInBMInfo(int offset,
  2018. int budget,
  2019. BoyerMooreLookahead* bm,
  2020. bool not_at_start) {
  2021. if (action_type_ == BEGIN_SUBMATCH) {
  2022. bm->SetRest(offset);
  2023. } else if (action_type_ != POSITIVE_SUBMATCH_SUCCESS) {
  2024. on_success()->FillInBMInfo(offset, budget - 1, bm, not_at_start);
  2025. }
  2026. SaveBMInfo(bm, not_at_start, offset);
  2027. }
  2028. int AssertionNode::EatsAtLeast(int still_to_find,
  2029. int budget,
  2030. bool not_at_start) {
  2031. if (budget <= 0) return 0;
  2032. // If we know we are not at the start and we are asked "how many characters
  2033. // will you match if you succeed?" then we can answer anything since false
  2034. // implies false. So lets just return the max answer (still_to_find) since
  2035. // that won't prevent us from preloading a lot of characters for the other
  2036. // branches in the node graph.
  2037. if (assertion_type() == AT_START && not_at_start) return still_to_find;
  2038. return on_success()->EatsAtLeast(still_to_find,
  2039. budget - 1,
  2040. not_at_start);
  2041. }
  2042. void AssertionNode::FillInBMInfo(int offset,
  2043. int budget,
  2044. BoyerMooreLookahead* bm,
  2045. bool not_at_start) {
  2046. // Match the behaviour of EatsAtLeast on this node.
  2047. if (assertion_type() == AT_START && not_at_start) return;
  2048. on_success()->FillInBMInfo(offset, budget - 1, bm, not_at_start);
  2049. SaveBMInfo(bm, not_at_start, offset);
  2050. }
  2051. int BackReferenceNode::EatsAtLeast(int still_to_find,
  2052. int budget,
  2053. bool not_at_start) {
  2054. if (budget <= 0) return 0;
  2055. return on_success()->EatsAtLeast(still_to_find,
  2056. budget - 1,
  2057. not_at_start);
  2058. }
  2059. int TextNode::EatsAtLeast(int still_to_find,
  2060. int budget,
  2061. bool not_at_start) {
  2062. int answer = Length();
  2063. if (answer >= still_to_find) return answer;
  2064. if (budget <= 0) return answer;
  2065. // We are not at start after this node so we set the last argument to 'true'.
  2066. return answer + on_success()->EatsAtLeast(still_to_find - answer,
  2067. budget - 1,
  2068. true);
  2069. }
  2070. int NegativeLookaheadChoiceNode::EatsAtLeast(int still_to_find,
  2071. int budget,
  2072. bool not_at_start) {
  2073. if (budget <= 0) return 0;
  2074. // Alternative 0 is the negative lookahead, alternative 1 is what comes
  2075. // afterwards.
  2076. RegExpNode* node = alternatives_->at(1).node();
  2077. return node->EatsAtLeast(still_to_find, budget - 1, not_at_start);
  2078. }
  2079. void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
  2080. QuickCheckDetails* details,
  2081. RegExpCompiler* compiler,
  2082. int filled_in,
  2083. bool not_at_start) {
  2084. // Alternative 0 is the negative lookahead, alternative 1 is what comes
  2085. // afterwards.
  2086. RegExpNode* node = alternatives_->at(1).node();
  2087. return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
  2088. }
  2089. int ChoiceNode::EatsAtLeastHelper(int still_to_find,
  2090. int budget,
  2091. RegExpNode* ignore_this_node,
  2092. bool not_at_start) {
  2093. if (budget <= 0) return 0;
  2094. int min = 100;
  2095. int choice_count = alternatives_->length();
  2096. budget = (budget - 1) / choice_count;
  2097. for (int i = 0; i < choice_count; i++) {
  2098. RegExpNode* node = alternatives_->at(i).node();
  2099. if (node == ignore_this_node) continue;
  2100. int node_eats_at_least =
  2101. node->EatsAtLeast(still_to_find, budget, not_at_start);
  2102. if (node_eats_at_least < min) min = node_eats_at_least;
  2103. if (min == 0) return 0;
  2104. }
  2105. return min;
  2106. }
  2107. int LoopChoiceNode::EatsAtLeast(int still_to_find,
  2108. int budget,
  2109. bool not_at_start) {
  2110. return EatsAtLeastHelper(still_to_find,
  2111. budget - 1,
  2112. loop_node_,
  2113. not_at_start);
  2114. }
  2115. int ChoiceNode::EatsAtLeast(int still_to_find,
  2116. int budget,
  2117. bool not_at_start) {
  2118. return EatsAtLeastHelper(still_to_find,
  2119. budget,
  2120. NULL,
  2121. not_at_start);
  2122. }
  2123. // Takes the left-most 1-bit and smears it out, setting all bits to its right.
  2124. static inline uint32_t SmearBitsRight(uint32_t v) {
  2125. v |= v >> 1;
  2126. v |= v >> 2;
  2127. v |= v >> 4;
  2128. v |= v >> 8;
  2129. v |= v >> 16;
  2130. return v;
  2131. }
  2132. bool QuickCheckDetails::Rationalize(bool asc) {
  2133. bool found_useful_op = false;
  2134. uint32_t char_mask;
  2135. if (asc) {
  2136. char_mask = String::kMaxOneByteCharCode;
  2137. } else {
  2138. char_mask = String::kMaxUtf16CodeUnit;
  2139. }
  2140. mask_ = 0;
  2141. value_ = 0;
  2142. int char_shift = 0;
  2143. for (int i = 0; i < characters_; i++) {
  2144. Position* pos = &positions_[i];
  2145. if ((pos->mask & String::kMaxOneByteCharCode) != 0) {
  2146. found_useful_op = true;
  2147. }
  2148. mask_ |= (pos->mask & char_mask) << char_shift;
  2149. value_ |= (pos->value & char_mask) << char_shift;
  2150. char_shift += asc ? 8 : 16;
  2151. }
  2152. return found_useful_op;
  2153. }
  2154. bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
  2155. Trace* trace,
  2156. bool preload_has_checked_bounds,
  2157. Label* on_possible_success,
  2158. QuickCheckDetails* details,
  2159. bool fall_through_on_failure) {
  2160. if (details->characters() == 0) return false;
  2161. GetQuickCheckDetails(
  2162. details, compiler, 0, trace->at_start() == Trace::FALSE_VALUE);
  2163. if (details->cannot_match()) return false;
  2164. if (!details->Rationalize(compiler->ascii())) return false;
  2165. DCHECK(details->characters() == 1 ||
  2166. compiler->macro_assembler()->CanReadUnaligned());
  2167. uint32_t mask = details->mask();
  2168. uint32_t value = details->value();
  2169. RegExpMacroAssembler* assembler = compiler->macro_assembler();
  2170. if (trace->characters_preloaded() != details->characters()) {
  2171. assembler->LoadCurrentCharacter(trace->cp_offset(),
  2172. trace->backtrack(),
  2173. !preload_has_checked_bounds,
  2174. details->characters());
  2175. }
  2176. bool need_mask = true;
  2177. if (details->characters() == 1) {
  2178. // If number of characters preloaded is 1 then we used a byte or 16 bit
  2179. // load so the value is already masked down.
  2180. uint32_t char_mask;
  2181. if (compiler->ascii()) {
  2182. char_mask = String::kMaxOneByteCharCode;
  2183. } else {
  2184. char_mask = String::kMaxUtf16CodeUnit;
  2185. }
  2186. if ((mask & char_mask) == char_mask) need_mask = false;
  2187. mask &= char_mask;
  2188. } else {
  2189. // For 2-character preloads in ASCII mode or 1-character preloads in
  2190. // TWO_BYTE mode we also use a 16 bit load with zero extend.
  2191. if (details->characters() == 2 && compiler->ascii()) {
  2192. if ((mask & 0xffff) == 0xffff) need_mask = false;
  2193. } else if (details->characters() == 1 && !compiler->ascii()) {
  2194. if ((mask & 0xffff) == 0xffff) need_mask = false;
  2195. } else {
  2196. if (mask == 0xffffffff) need_mask = false;
  2197. }
  2198. }
  2199. if (fall_through_on_failure) {
  2200. if (need_mask) {
  2201. assembler->CheckCharacterAfterAnd(value, mask, on_possible_success);
  2202. } else {
  2203. assembler->CheckCharacter(value, on_possible_success);
  2204. }
  2205. } else {
  2206. if (need_mask) {
  2207. assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack());
  2208. } else {
  2209. assembler->CheckNotCharacter(value, trace->backtrack());
  2210. }
  2211. }
  2212. return true;
  2213. }
  2214. // Here is the meat of GetQuickCheckDetails (see also the comment on the
  2215. // super-class in the .h file).
  2216. //
  2217. // We iterate along the text object, building up for each character a
  2218. // mask and value that can be used to test for a quick failure to match.
  2219. // The masks and values for the positions will be combined into a single
  2220. // machine word for the current character width in order to be used in
  2221. // generating a quick check.
  2222. void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
  2223. RegExpCompiler* compiler,
  2224. int characters_filled_in,
  2225. bool not_at_start) {
  2226. Isolate* isolate = compiler->macro_assembler()->zone()->isolate();
  2227. DCHECK(characters_filled_in < details->characters());
  2228. int characters = details->characters();
  2229. int char_mask;
  2230. if (compiler->ascii()) {
  2231. char_mask = String::kMaxOneByteCharCode;
  2232. } else {
  2233. char_mask = String::kMaxUtf16CodeUnit;
  2234. }
  2235. for (int k = 0; k < elms_->length(); k++) {
  2236. TextElement elm = elms_->at(k);
  2237. if (elm.text_type() == TextElement::ATOM) {
  2238. Vector<const uc16> quarks = elm.atom()->data();
  2239. for (int i = 0; i < characters && i < quarks.length(); i++) {
  2240. QuickCheckDetails::Position* pos =
  2241. details->positions(characters_filled_in);
  2242. uc16 c = quarks[i];
  2243. if (c > char_mask) {
  2244. // If we expect a non-ASCII character from an ASCII string,
  2245. // there is no way we can match. Not even case independent
  2246. // matching can turn an ASCII character into non-ASCII or
  2247. // vice versa.
  2248. details->set_cannot_match();
  2249. pos->determines_perfectly = false;
  2250. return;
  2251. }
  2252. if (compiler->ignore_case()) {
  2253. unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
  2254. int length = GetCaseIndependentLetters(isolate, c, compiler->ascii(),
  2255. chars);
  2256. DCHECK(length != 0); // Can only happen if c > char_mask (see above).
  2257. if (length == 1) {
  2258. // This letter has no case equivalents, so it's nice and simple
  2259. // and the mask-compare will determine definitely whether we have
  2260. // a match at this character position.
  2261. pos->mask = char_mask;
  2262. pos->value = c;
  2263. pos->determines_perfectly = true;
  2264. } else {
  2265. uint32_t common_bits = char_mask;
  2266. uint32_t bits = chars[0];
  2267. for (int j = 1; j < length; j++) {
  2268. uint32_t differing_bits = ((chars[j] & common_bits) ^ bits);
  2269. common_bits ^= differing_bits;
  2270. bits &= common_bits;
  2271. }
  2272. // If length is 2 and common bits has only one zero in it then
  2273. // our mask and compare instruction will determine definitely
  2274. // whether we have a match at this character position. Otherwise
  2275. // it can only be an approximate check.
  2276. uint32_t one_zero = (common_bits | ~char_mask);
  2277. if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) {
  2278. pos->determines_perfectly = true;
  2279. }
  2280. pos->mask = common_bits;
  2281. pos->value = bits;
  2282. }
  2283. } else {
  2284. // Don't ignore case. Nice simple case where the mask-compare will
  2285. // determine definitely whether we have a match at this character
  2286. // position.
  2287. pos->mask = char_mask;
  2288. pos->value = c;
  2289. pos->determines_perfectly = true;
  2290. }
  2291. characters_filled_in++;
  2292. DCHECK(characters_filled_in <= details->characters());
  2293. if (characters_filled_in == details->characters()) {
  2294. return;
  2295. }
  2296. }
  2297. } else {
  2298. QuickCheckDetails::Position* pos =
  2299. details->positions(characters_filled_in);
  2300. RegExpCharacterClass* tree = elm.char_class();
  2301. ZoneList<CharacterRange>* ranges = tree->ranges(zone());
  2302. if (tree->is_negated()) {
  2303. // A quick check uses multi-character mask and compare. There is no
  2304. // useful way to incorporate a negative char class into this scheme
  2305. // so we just conservatively create a mask and value that will always
  2306. // succeed.
  2307. pos->mask = 0;
  2308. pos->value = 0;
  2309. } else {
  2310. int first_range = 0;
  2311. while (ranges->at(first_range).from() > char_mask) {
  2312. first_range++;
  2313. if (first_range == ranges->length()) {
  2314. details->set_cannot_match();
  2315. pos->determines_perfectly = false;
  2316. return;
  2317. }
  2318. }
  2319. CharacterRange range = ranges->at(first_range);
  2320. uc16 from = range.from();
  2321. uc16 to = range.to();
  2322. if (to > char_mask) {
  2323. to = char_mask;
  2324. }
  2325. uint32_t differing_bits = (from ^ to);
  2326. // A mask and compare is only perfect if the differing bits form a
  2327. // number like 00011111 with one single block of trailing 1s.
  2328. if ((differing_bits & (differing_bits + 1)) == 0 &&
  2329. from + differing_bits == to) {
  2330. pos->determines_perfectly = true;
  2331. }
  2332. uint32_t common_bits = ~SmearBitsRight(differing_bits);
  2333. uint32_t bits = (from & common_bits);
  2334. for (int i = first_range + 1; i < ranges->length(); i++) {
  2335. CharacterRange range = ranges->at(i);
  2336. uc16 from = range.from();
  2337. uc16 to = range.to();
  2338. if (from > char_mask) continue;
  2339. if (to > char_mask) to = char_mask;
  2340. // Here we are combining more ranges into the mask and compare
  2341. // value. With each new range the mask becomes more sparse and
  2342. // so the chances of a false positive rise. A character class
  2343. // with multiple ranges is assumed never to be equivalent to a
  2344. // mask and compare operation.
  2345. pos->determines_perfectly = false;
  2346. uint32_t new_common_bits = (from ^ to);
  2347. new_common_bits = ~SmearBitsRight(new_common_bits);
  2348. common_bits &= new_common_bits;
  2349. bits &= new_common_bits;
  2350. uint32_t differing_bits = (from & common_bits) ^ bits;
  2351. common_bits ^= differing_bits;
  2352. bits &= common_bits;
  2353. }
  2354. pos->mask = common_bits;
  2355. pos->value = bits;
  2356. }
  2357. characters_filled_in++;
  2358. DCHECK(characters_filled_in <= details->characters());
  2359. if (characters_filled_in == details->characters()) {
  2360. return;
  2361. }
  2362. }
  2363. }
  2364. DCHECK(characters_filled_in != details->characters());
  2365. if (!details->cannot_match()) {
  2366. on_success()-> GetQuickCheckDetails(details,
  2367. compiler,
  2368. characters_filled_in,
  2369. true);
  2370. }
  2371. }
  2372. void QuickCheckDetails::Clear() {
  2373. for (int i = 0; i < characters_; i++) {
  2374. positions_[i].mask = 0;
  2375. positions_[i].value = 0;
  2376. positions_[i].determines_perfectly = false;
  2377. }
  2378. characters_ = 0;
  2379. }
  2380. void QuickCheckDetails::Advance(int by, bool ascii) {
  2381. DCHECK(by >= 0);
  2382. if (by >= characters_) {
  2383. Clear();
  2384. return;
  2385. }
  2386. for (int i = 0; i < characters_ - by; i++) {
  2387. positions_[i] = positions_[by + i];
  2388. }
  2389. for (int i = characters_ - by; i < characters_; i++) {
  2390. positions_[i].mask = 0;
  2391. positions_[i].value = 0;
  2392. positions_[i].determines_perfectly = false;
  2393. }
  2394. characters_ -= by;
  2395. // We could change mask_ and value_ here but we would never advance unless
  2396. // they had already been used in a check and they won't be used again because
  2397. // it would gain us nothing. So there's no point.
  2398. }
  2399. void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) {
  2400. DCHECK(characters_ == other->characters_);
  2401. if (other->cannot_match_) {
  2402. return;
  2403. }
  2404. if (cannot_match_) {
  2405. *this = *other;
  2406. return;
  2407. }
  2408. for (int i = from_index; i < characters_; i++) {
  2409. QuickCheckDetails::Position* pos = positions(i);
  2410. QuickCheckDetails::Position* other_pos = other->positions(i);
  2411. if (pos->mask != other_pos->mask ||
  2412. pos->value != other_pos->value ||
  2413. !other_pos->determines_perfectly) {
  2414. // Our mask-compare operation will be approximate unless we have the
  2415. // exact same operation on both sides of the alternation.
  2416. pos->determines_perfectly = false;
  2417. }
  2418. pos->mask &= other_pos->mask;
  2419. pos->value &= pos->mask;
  2420. other_pos->value &= pos->mask;
  2421. uc16 differing_bits = (pos->value ^ other_pos->value);
  2422. pos->mask &= ~differing_bits;
  2423. pos->value &= pos->mask;
  2424. }
  2425. }
  2426. class VisitMarker {
  2427. public:
  2428. explicit VisitMarker(NodeInfo* info) : info_(info) {
  2429. DCHECK(!info->visited);
  2430. info->visited = true;
  2431. }
  2432. ~VisitMarker() {
  2433. info_->visited = false;
  2434. }
  2435. private:
  2436. NodeInfo* info_;
  2437. };
  2438. RegExpNode* SeqRegExpNode::FilterASCII(int depth, bool ignore_case) {
  2439. if (info()->replacement_calculated) return replacement();
  2440. if (depth < 0) return this;
  2441. DCHECK(!info()->visited);
  2442. VisitMarker marker(info());
  2443. return FilterSuccessor(depth - 1, ignore_case);
  2444. }
  2445. RegExpNode* SeqRegExpNode::FilterSuccessor(int depth, bool ignore_case) {
  2446. RegExpNode* next = on_success_->FilterASCII(depth - 1, ignore_case);
  2447. if (next == NULL) return set_replacement(NULL);
  2448. on_success_ = next;
  2449. return set_replacement(this);
  2450. }
  2451. // We need to check for the following characters: 0x39c 0x3bc 0x178.
  2452. static inline bool RangeContainsLatin1Equivalents(CharacterRange range) {
  2453. // TODO(dcarney): this could be a lot more efficient.
  2454. return range.Contains(0x39c) ||
  2455. range.Contains(0x3bc) || range.Contains(0x178);
  2456. }
  2457. static bool RangesContainLatin1Equivalents(ZoneList<CharacterRange>* ranges) {
  2458. for (int i = 0; i < ranges->length(); i++) {
  2459. // TODO(dcarney): this could be a lot more efficient.
  2460. if (RangeContainsLatin1Equivalents(ranges->at(i))) return true;
  2461. }
  2462. return false;
  2463. }
  2464. RegExpNode* TextNode::FilterASCII(int depth, bool ignore_case) {
  2465. if (info()->replacement_calculated) return replacement();
  2466. if (depth < 0) return this;
  2467. DCHECK(!info()->visited);
  2468. VisitMarker marker(info());
  2469. int element_count = elms_->length();
  2470. for (int i = 0; i < element_count; i++) {
  2471. TextElement elm = elms_->at(i);
  2472. if (elm.text_type() == TextElement::ATOM) {
  2473. Vector<const uc16> quarks = elm.atom()->data();
  2474. for (int j = 0; j < quarks.length(); j++) {
  2475. uint16_t c = quarks[j];
  2476. if (c <= String::kMaxOneByteCharCode) continue;
  2477. if (!ignore_case) return set_replacement(NULL);
  2478. // Here, we need to check for characters whose upper and lower cases
  2479. // are outside the Latin-1 range.
  2480. uint16_t converted = unibrow::Latin1::ConvertNonLatin1ToLatin1(c);
  2481. // Character is outside Latin-1 completely
  2482. if (converted == 0) return set_replacement(NULL);
  2483. // Convert quark to Latin-1 in place.
  2484. uint16_t* copy = const_cast<uint16_t*>(quarks.start());
  2485. copy[j] = converted;
  2486. }
  2487. } else {
  2488. DCHECK(elm.text_type() == TextElement::CHAR_CLASS);
  2489. RegExpCharacterClass* cc = elm.char_class();
  2490. ZoneList<CharacterRange>* ranges = cc->ranges(zone());
  2491. if (!CharacterRange::IsCanonical(ranges)) {
  2492. CharacterRange::Canonicalize(ranges);
  2493. }
  2494. // Now they are in order so we only need to look at the first.
  2495. int range_count = ranges->length();
  2496. if (cc->is_negated()) {
  2497. if (range_count != 0 &&
  2498. ranges->at(0).from() == 0 &&
  2499. ranges->at(0).to() >= String::kMaxOneByteCharCode) {
  2500. // This will be handled in a later filter.
  2501. if (ignore_case && RangesContainLatin1Equivalents(ranges)) continue;
  2502. return set_replacement(NULL);
  2503. }
  2504. } else {
  2505. if (range_count == 0 ||
  2506. ranges->at(0).from() > String::kMaxOneByteCharCode) {
  2507. // This will be handled in a later filter.
  2508. if (ignore_case && RangesContainLatin1Equivalents(ranges)) continue;
  2509. return set_replacement(NULL);
  2510. }
  2511. }
  2512. }
  2513. }
  2514. return FilterSuccessor(depth - 1, ignore_case);
  2515. }
  2516. RegExpNode* LoopChoiceNode::FilterASCII(int depth, bool ignore_case) {
  2517. if (info()->replacement_calculated) return replacement();
  2518. if (depth < 0) return this;
  2519. if (info()->visited) return this;
  2520. {
  2521. VisitMarker marker(info());
  2522. RegExpNode* continue_replacement =
  2523. continue_node_->FilterASCII(depth - 1, ignore_case);
  2524. // If we can't continue after the loop then there is no sense in doing the
  2525. // loop.
  2526. if (continue_replacement == NULL) return set_replacement(NULL);
  2527. }
  2528. return ChoiceNode::FilterASCII(depth - 1, ignore_case);
  2529. }
  2530. RegExpNode* ChoiceNode::FilterASCII(int depth, bool ignore_case) {
  2531. if (info()->replacement_calculated) return replacement();
  2532. if (depth < 0) return this;
  2533. if (info()->visited) return this;
  2534. VisitMarker marker(info());
  2535. int choice_count = alternatives_->length();
  2536. for (int i = 0; i < choice_count; i++) {
  2537. GuardedAlternative alternative = alternatives_->at(i);
  2538. if (alternative.guards() != NULL && alternative.guards()->length() != 0) {
  2539. set_replacement(this);
  2540. return this;
  2541. }
  2542. }
  2543. int surviving = 0;
  2544. RegExpNode* survivor = NULL;
  2545. for (int i = 0; i < choice_count; i++) {
  2546. GuardedAlternative alternative = alternatives_->at(i);
  2547. RegExpNode* replacement =
  2548. alternative.node()->FilterASCII(depth - 1, ignore_case);
  2549. DCHECK(replacement != this); // No missing EMPTY_MATCH_CHECK.
  2550. if (replacement != NULL) {
  2551. alternatives_->at(i).set_node(replacement);
  2552. surviving++;
  2553. survivor = replacement;
  2554. }
  2555. }
  2556. if (surviving < 2) return set_replacement(survivor);
  2557. set_replacement(this);
  2558. if (surviving == choice_count) {
  2559. return this;
  2560. }
  2561. // Only some of the nodes survived the filtering. We need to rebuild the
  2562. // alternatives list.
  2563. ZoneList<GuardedAlternative>* new_alternatives =
  2564. new(zone()) ZoneList<GuardedAlternative>(surviving, zone());
  2565. for (int i = 0; i < choice_count; i++) {
  2566. RegExpNode* replacement =
  2567. alternatives_->at(i).node()->FilterASCII(depth - 1, ignore_case);
  2568. if (replacement != NULL) {
  2569. alternatives_->at(i).set_node(replacement);
  2570. new_alternatives->Add(alternatives_->at(i), zone());
  2571. }
  2572. }
  2573. alternatives_ = new_alternatives;
  2574. return this;
  2575. }
  2576. RegExpNode* NegativeLookaheadChoiceNode::FilterASCII(int depth,
  2577. bool ignore_case) {
  2578. if (info()->replacement_calculated) return replacement();
  2579. if (depth < 0) return this;
  2580. if (info()->visited) return this;
  2581. VisitMarker marker(info());
  2582. // Alternative 0 is the negative lookahead, alternative 1 is what comes
  2583. // afterwards.
  2584. RegExpNode* node = alternatives_->at(1).node();
  2585. RegExpNode* replacement = node->FilterASCII(depth - 1, ignore_case);
  2586. if (replacement == NULL) return set_replacement(NULL);
  2587. alternatives_->at(1).set_node(replacement);
  2588. RegExpNode* neg_node = alternatives_->at(0).node();
  2589. RegExpNode* neg_replacement = neg_node->FilterASCII(depth - 1, ignore_case);
  2590. // If the negative lookahead is always going to fail then
  2591. // we don't need to check it.
  2592. if (neg_replacement == NULL) return set_replacement(replacement);
  2593. alternatives_->at(0).set_node(neg_replacement);
  2594. return set_replacement(this);
  2595. }
  2596. void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
  2597. RegExpCompiler* compiler,
  2598. int characters_filled_in,
  2599. bool not_at_start) {
  2600. if (body_can_be_zero_length_ || info()->visited) return;
  2601. VisitMarker marker(info());
  2602. return ChoiceNode::GetQuickCheckDetails(details,
  2603. compiler,
  2604. characters_filled_in,
  2605. not_at_start);
  2606. }
  2607. void LoopChoiceNode::FillInBMInfo(int offset,
  2608. int budget,
  2609. BoyerMooreLookahead* bm,
  2610. bool not_at_start) {
  2611. if (body_can_be_zero_length_ || budget <= 0) {
  2612. bm->SetRest(offset);
  2613. SaveBMInfo(bm, not_at_start, offset);
  2614. return;
  2615. }
  2616. ChoiceNode::FillInBMInfo(offset, budget - 1, bm, not_at_start);
  2617. SaveBMInfo(bm, not_at_start, offset);
  2618. }
  2619. void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
  2620. RegExpCompiler* compiler,
  2621. int characters_filled_in,
  2622. bool not_at_start) {
  2623. not_at_start = (not_at_start || not_at_start_);
  2624. int choice_count = alternatives_->length();
  2625. DCHECK(choice_count > 0);
  2626. alternatives_->at(0).node()->GetQuickCheckDetails(details,
  2627. compiler,
  2628. characters_filled_in,
  2629. not_at_start);
  2630. for (int i = 1; i < choice_count; i++) {
  2631. QuickCheckDetails new_details(details->characters());
  2632. RegExpNode* node = alternatives_->at(i).node();
  2633. node->GetQuickCheckDetails(&new_details, compiler,
  2634. characters_filled_in,
  2635. not_at_start);
  2636. // Here we merge the quick match details of the two branches.
  2637. details->Merge(&new_details, characters_filled_in);
  2638. }
  2639. }
  2640. // Check for [0-9A-Z_a-z].
  2641. static void EmitWordCheck(RegExpMacroAssembler* assembler,
  2642. Label* word,
  2643. Label* non_word,
  2644. bool fall_through_on_word) {
  2645. if (assembler->CheckSpecialCharacterClass(
  2646. fall_through_on_word ? 'w' : 'W',
  2647. fall_through_on_word ? non_word : word)) {
  2648. // Optimized implementation available.
  2649. return;
  2650. }
  2651. assembler->CheckCharacterGT('z', non_word);
  2652. assembler->CheckCharacterLT('0', non_word);
  2653. assembler->CheckCharacterGT('a' - 1, word);
  2654. assembler->CheckCharacterLT('9' + 1, word);
  2655. assembler->CheckCharacterLT('A', non_word);
  2656. assembler->CheckCharacterLT('Z' + 1, word);
  2657. if (fall_through_on_word) {
  2658. assembler->CheckNotCharacter('_', non_word);
  2659. } else {
  2660. assembler->CheckCharacter('_', word);
  2661. }
  2662. }
  2663. // Emit the code to check for a ^ in multiline mode (1-character lookbehind
  2664. // that matches newline or the start of input).
  2665. static void EmitHat(RegExpCompiler* compiler,
  2666. RegExpNode* on_success,
  2667. Trace* trace) {
  2668. RegExpMacroAssembler* assembler = compiler->macro_assembler();
  2669. // We will be loading the previous character into the current character
  2670. // register.
  2671. Trace new_trace(*trace);
  2672. new_trace.InvalidateCurrentCharacter();
  2673. Label ok;
  2674. if (new_trace.cp_offset() == 0) {
  2675. // The start of input counts as a newline in this context, so skip to
  2676. // ok if we are at the start.
  2677. assembler->CheckAtStart(&ok);
  2678. }
  2679. // We already checked that we are not at the start of input so it must be
  2680. // OK to load the previous character.
  2681. assembler->LoadCurrentCharacter(new_trace.cp_offset() -1,
  2682. new_trace.backtrack(),
  2683. false);
  2684. if (!assembler->CheckSpecialCharacterClass('n',
  2685. new_trace.backtrack())) {
  2686. // Newline means \n, \r, 0x2028 or 0x2029.
  2687. if (!compiler->ascii()) {
  2688. assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok);
  2689. }
  2690. assembler->CheckCharacter('\n', &ok);
  2691. assembler->CheckNotCharacter('\r', new_trace.backtrack());
  2692. }
  2693. assembler->Bind(&ok);
  2694. on_success->Emit(compiler, &new_trace);
  2695. }
  2696. // Emit the code to handle \b and \B (word-boundary or non-word-boundary).
  2697. void AssertionNode::EmitBoundaryCheck(RegExpCompiler* compiler, Trace* trace) {
  2698. RegExpMacroAssembler* assembler = compiler->macro_assembler();
  2699. Trace::TriBool next_is_word_character = Trace::UNKNOWN;
  2700. bool not_at_start = (trace->at_start() == Trace::FALSE_VALUE);
  2701. BoyerMooreLookahead* lookahead = bm_info(not_at_start);
  2702. if (lookahead == NULL) {
  2703. int eats_at_least =
  2704. Min(kMaxLookaheadForBoyerMoore, EatsAtLeast(kMaxLookaheadForBoyerMoore,
  2705. kRecursionBudget,
  2706. not_at_start));
  2707. if (eats_at_least >= 1) {
  2708. BoyerMooreLookahead* bm =
  2709. new(zone()) BoyerMooreLookahead(eats_at_least, compiler, zone());
  2710. FillInBMInfo(0, kRecursionBudget, bm, not_at_start);
  2711. if (bm->at(0)->is_non_word())
  2712. next_is_word_character = Trace::FALSE_VALUE;
  2713. if (bm->at(0)->is_word()) next_is_word_character = Trace::TRUE_VALUE;
  2714. }
  2715. } else {
  2716. if (lookahead->at(0)->is_non_word())
  2717. next_is_word_character = Trace::FALSE_VALUE;
  2718. if (lookahead->at(0)->is_word())
  2719. next_is_word_character = Trace::TRUE_VALUE;
  2720. }
  2721. bool at_boundary = (assertion_type_ == AssertionNode::AT_BOUNDARY);
  2722. if (next_is_word_character == Trace::UNKNOWN) {
  2723. Label before_non_word;
  2724. Label before_word;
  2725. if (trace->characters_preloaded() != 1) {
  2726. assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word);
  2727. }
  2728. // Fall through on non-word.
  2729. EmitWordCheck(assembler, &before_word, &before_non_word, false);
  2730. // Next character is not a word character.
  2731. assembler->Bind(&before_non_word);
  2732. Label ok;
  2733. BacktrackIfPrevious(compiler, trace, at_boundary ? kIsNonWord : kIsWord);
  2734. assembler->GoTo(&ok);
  2735. assembler->Bind(&before_word);
  2736. BacktrackIfPrevious(compiler, trace, at_boundary ? kIsWord : kIsNonWord);
  2737. assembler->Bind(&ok);
  2738. } else if (next_is_word_character == Trace::TRUE_VALUE) {
  2739. BacktrackIfPrevious(compiler, trace, at_boundary ? kIsWord : kIsNonWord);
  2740. } else {
  2741. DCHECK(next_is_word_character == Trace::FALSE_VALUE);
  2742. BacktrackIfPrevious(compiler, trace, at_boundary ? kIsNonWord : kIsWord);
  2743. }
  2744. }
  2745. void AssertionNode::BacktrackIfPrevious(
  2746. RegExpCompiler* compiler,
  2747. Trace* trace,
  2748. AssertionNode::IfPrevious backtrack_if_previous) {
  2749. RegExpMacroAssembler* assembler = compiler->macro_assembler();
  2750. Trace new_trace(*trace);
  2751. new_trace.InvalidateCurrentCharacter();
  2752. Label fall_through, dummy;
  2753. Label* non_word = backtrack_if_previous == kIsNonWord ?
  2754. new_trace.backtrack() :
  2755. &fall_through;
  2756. Label* word = backtrack_if_previous == kIsNonWord ?
  2757. &fall_through :
  2758. new_trace.backtrack();
  2759. if (new_trace.cp_offset() == 0) {
  2760. // The start of input counts as a non-word character, so the question is
  2761. // decided if we are at the start.
  2762. assembler->CheckAtStart(non_word);
  2763. }
  2764. // We already checked that we are not at the start of input so it must be
  2765. // OK to load the previous character.
  2766. assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1, &dummy, false);
  2767. EmitWordCheck(assembler, word, non_word, backtrack_if_previous == kIsNonWord);
  2768. assembler->Bind(&fall_through);
  2769. on_success()->Emit(compiler, &new_trace);
  2770. }
  2771. void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details,
  2772. RegExpCompiler* compiler,
  2773. int filled_in,
  2774. bool not_at_start) {
  2775. if (assertion_type_ == AT_START && not_at_start) {
  2776. details->set_cannot_match();
  2777. return;
  2778. }
  2779. return on_success()->GetQuickCheckDetails(details,
  2780. compiler,
  2781. filled_in,
  2782. not_at_start);
  2783. }
  2784. void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
  2785. RegExpMacroAssembler* assembler = compiler->macro_assembler();
  2786. switch (assertion_type_) {
  2787. case AT_END: {
  2788. Label ok;
  2789. assembler->CheckPosition(trace->cp_offset(), &ok);
  2790. assembler->GoTo(trace->backtrack());
  2791. assembler->Bind(&ok);
  2792. break;
  2793. }
  2794. case AT_START: {
  2795. if (trace->at_start() == Trace::FALSE_VALUE) {
  2796. assembler->GoTo(trace->backtrack());
  2797. return;
  2798. }
  2799. if (trace->at_start() == Trace::UNKNOWN) {
  2800. assembler->CheckNotAtStart(trace->backtrack());
  2801. Trace at_start_trace = *trace;
  2802. at_start_trace.set_at_start(true);
  2803. on_success()->Emit(compiler, &at_start_trace);
  2804. return;
  2805. }
  2806. }
  2807. break;
  2808. case AFTER_NEWLINE:
  2809. EmitHat(compiler, on_success(), trace);
  2810. return;
  2811. case AT_BOUNDARY:
  2812. case AT_NON_BOUNDARY: {
  2813. EmitBoundaryCheck(compiler, trace);
  2814. return;
  2815. }
  2816. }
  2817. on_success()->Emit(compiler, trace);
  2818. }
  2819. static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) {
  2820. if (quick_check == NULL) return false;
  2821. if (offset >= quick_check->characters()) return false;
  2822. return quick_check->positions(offset)->determines_perfectly;
  2823. }
  2824. static void UpdateBoundsCheck(int index, int* checked_up_to) {
  2825. if (index > *checked_up_to) {
  2826. *checked_up_to = index;
  2827. }
  2828. }
  2829. // We call this repeatedly to generate code for each pass over the text node.
  2830. // The passes are in increasing order of difficulty because we hope one
  2831. // of the first passes will fail in which case we are saved the work of the
  2832. // later passes. for example for the case independent regexp /%[asdfghjkl]a/
  2833. // we will check the '%' in the first pass, the case independent 'a' in the
  2834. // second pass and the character class in the last pass.
  2835. //
  2836. // The passes are done from right to left, so for example to test for /bar/
  2837. // we will first test for an 'r' with offset 2, then an 'a' with offset 1
  2838. // and then a 'b' with offset 0. This means we can avoid the end-of-input
  2839. // bounds check most of the time. In the example we only need to check for
  2840. // end-of-input when loading the putative 'r'.
  2841. //
  2842. // A slight complication involves the fact that the first character may already
  2843. // be fetched into a register by the previous node. In this case we want to
  2844. // do the test for that character first. We do this in separate passes. The
  2845. // 'preloaded' argument indicates that we are doing such a 'pass'. If such a
  2846. // pass has been performed then subsequent passes will have true in
  2847. // first_element_checked to indicate that that character does not need to be
  2848. // checked again.
  2849. //
  2850. // In addition to all this we are passed a Trace, which can
  2851. // contain an AlternativeGeneration object. In this AlternativeGeneration
  2852. // object we can see details of any quick check that was already passed in
  2853. // order to get to the code we are now generating. The quick check can involve
  2854. // loading characters, which means we do not need to recheck the bounds
  2855. // up to the limit the quick check already checked. In addition the quick
  2856. // check can have involved a mask and compare operation which may simplify
  2857. // or obviate the need for further checks at some character positions.
  2858. void TextNode::TextEmitPass(RegExpCompiler* compiler,
  2859. TextEmitPassType pass,
  2860. bool preloaded,
  2861. Trace* trace,
  2862. bool first_element_checked,
  2863. int* checked_up_to) {
  2864. RegExpMacroAssembler* assembler = compiler->macro_assembler();
  2865. Isolate* isolate = assembler->zone()->isolate();
  2866. bool ascii = compiler->ascii();
  2867. Label* backtrack = trace->backtrack();
  2868. QuickCheckDetails* quick_check = trace->quick_check_performed();
  2869. int element_count = elms_->length();
  2870. for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) {
  2871. TextElement elm = elms_->at(i);
  2872. int cp_offset = trace->cp_offset() + elm.cp_offset();
  2873. if (elm.text_type() == TextElement::ATOM) {
  2874. Vector<const uc16> quarks = elm.atom()->data();
  2875. for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) {
  2876. if (first_element_checked && i == 0 && j == 0) continue;
  2877. if (DeterminedAlready(quick_check, elm.cp_offset() + j)) continue;
  2878. EmitCharacterFunction* emit_function = NULL;
  2879. switch (pass) {
  2880. case NON_ASCII_MATCH:
  2881. DCHECK(ascii);
  2882. if (quarks[j] > String::kMaxOneByteCharCode) {
  2883. assembler->GoTo(backtrack);
  2884. return;
  2885. }
  2886. break;
  2887. case NON_LETTER_CHARACTER_MATCH:
  2888. emit_function = &EmitAtomNonLetter;
  2889. break;
  2890. case SIMPLE_CHARACTER_MATCH:
  2891. emit_function = &EmitSimpleCharacter;
  2892. break;
  2893. case CASE_CHARACTER_MATCH:
  2894. emit_function = &EmitAtomLetter;
  2895. break;
  2896. default:
  2897. break;
  2898. }
  2899. if (emit_function != NULL) {
  2900. bool bound_checked = emit_function(isolate,
  2901. compiler,
  2902. quarks[j],
  2903. backtrack,
  2904. cp_offset + j,
  2905. *checked_up_to < cp_offset + j,
  2906. preloaded);
  2907. if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
  2908. }
  2909. }
  2910. } else {
  2911. DCHECK_EQ(TextElement::CHAR_CLASS, elm.text_type());
  2912. if (pass == CHARACTER_CLASS_MATCH) {
  2913. if (first_element_checked && i == 0) continue;
  2914. if (DeterminedAlready(quick_check, elm.cp_offset())) continue;
  2915. RegExpCharacterClass* cc = elm.char_class();
  2916. EmitCharClass(assembler,
  2917. cc,
  2918. ascii,
  2919. backtrack,
  2920. cp_offset,
  2921. *checked_up_to < cp_offset,
  2922. preloaded,
  2923. zone());
  2924. UpdateBoundsCheck(cp_offset, checked_up_to);
  2925. }
  2926. }
  2927. }
  2928. }
  2929. int TextNode::Length() {
  2930. TextElement elm = elms_->last();
  2931. DCHECK(elm.cp_offset() >= 0);
  2932. return elm.cp_offset() + elm.length();
  2933. }
  2934. bool TextNode::SkipPass(int int_pass, bool ignore_case) {
  2935. TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass);
  2936. if (ignore_case) {
  2937. return pass == SIMPLE_CHARACTER_MATCH;
  2938. } else {
  2939. return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH;
  2940. }
  2941. }
  2942. // This generates the code to match a text node. A text node can contain
  2943. // straight character sequences (possibly to be matched in a case-independent
  2944. // way) and character classes. For efficiency we do not do this in a single
  2945. // pass from left to right. Instead we pass over the text node several times,
  2946. // emitting code for some character positions every time. See the comment on
  2947. // TextEmitPass for details.
  2948. void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
  2949. LimitResult limit_result = LimitVersions(compiler, trace);
  2950. if (limit_result == DONE) return;
  2951. DCHECK(limit_result == CONTINUE);
  2952. if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
  2953. compiler->SetRegExpTooBig();
  2954. return;
  2955. }
  2956. if (compiler->ascii()) {
  2957. int dummy = 0;
  2958. TextEmitPass(compiler, NON_ASCII_MATCH, false, trace, false, &dummy);
  2959. }
  2960. bool first_elt_done = false;
  2961. int bound_checked_to = trace->cp_offset() - 1;
  2962. bound_checked_to += trace->bound_checked_up_to();
  2963. // If a character is preloaded into the current character register then
  2964. // check that now.
  2965. if (trace->characters_preloaded() == 1) {
  2966. for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
  2967. if (!SkipPass(pass, compiler->ignore_case())) {
  2968. TextEmitPass(compiler,
  2969. static_cast<TextEmitPassType>(pass),
  2970. true,
  2971. trace,
  2972. false,
  2973. &bound_checked_to);
  2974. }
  2975. }
  2976. first_elt_done = true;
  2977. }
  2978. for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
  2979. if (!SkipPass(pass, compiler->ignore_case())) {
  2980. TextEmitPass(compiler,
  2981. static_cast<TextEmitPassType>(pass),
  2982. false,
  2983. trace,
  2984. first_elt_done,
  2985. &bound_checked_to);
  2986. }
  2987. }
  2988. Trace successor_trace(*trace);
  2989. successor_trace.set_at_start(false);
  2990. successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler);
  2991. RecursionCheck rc(compiler);
  2992. on_success()->Emit(compiler, &successor_trace);
  2993. }
  2994. void Trace::InvalidateCurrentCharacter() {
  2995. characters_preloaded_ = 0;
  2996. }
  2997. void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) {
  2998. DCHECK(by > 0);
  2999. // We don't have an instruction for shifting the current character register
  3000. // down or for using a shifted value for anything so lets just forget that
  3001. // we preloaded any characters into it.
  3002. characters_preloaded_ = 0;
  3003. // Adjust the offsets of the quick check performed information. This
  3004. // information is used to find out what we already determined about the
  3005. // characters by means of mask and compare.
  3006. quick_check_performed_.Advance(by, compiler->ascii());
  3007. cp_offset_ += by;
  3008. if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
  3009. compiler->SetRegExpTooBig();
  3010. cp_offset_ = 0;
  3011. }
  3012. bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
  3013. }
  3014. void TextNode::MakeCaseIndependent(bool is_ascii) {
  3015. int element_count = elms_->length();
  3016. for (int i = 0; i < element_count; i++) {
  3017. TextElement elm = elms_->at(i);
  3018. if (elm.text_type() == TextElement::CHAR_CLASS) {
  3019. RegExpCharacterClass* cc = elm.char_class();
  3020. // None of the standard character classes is different in the case
  3021. // independent case and it slows us down if we don't know that.
  3022. if (cc->is_standard(zone())) continue;
  3023. ZoneList<CharacterRange>* ranges = cc->ranges(zone());
  3024. int range_count = ranges->length();
  3025. for (int j = 0; j < range_count; j++) {
  3026. ranges->at(j).AddCaseEquivalents(ranges, is_ascii, zone());
  3027. }
  3028. }
  3029. }
  3030. }
  3031. int TextNode::GreedyLoopTextLength() {
  3032. TextElement elm = elms_->at(elms_->length() - 1);
  3033. return elm.cp_offset() + elm.length();
  3034. }
  3035. RegExpNode* TextNode::GetSuccessorOfOmnivorousTextNode(
  3036. RegExpCompiler* compiler) {
  3037. if (elms_->length() != 1) return NULL;
  3038. TextElement elm = elms_->at(0);
  3039. if (elm.text_type() != TextElement::CHAR_CLASS) return NULL;
  3040. RegExpCharacterClass* node = elm.char_class();
  3041. ZoneList<CharacterRange>* ranges = node->ranges(zone());
  3042. if (!CharacterRange::IsCanonical(ranges)) {
  3043. CharacterRange::Canonicalize(ranges);
  3044. }
  3045. if (node->is_negated()) {
  3046. return ranges->length() == 0 ? on_success() : NULL;
  3047. }
  3048. if (ranges->length() != 1) return NULL;
  3049. uint32_t max_char;
  3050. if (compiler->ascii()) {
  3051. max_char = String::kMaxOneByteCharCode;
  3052. } else {
  3053. max_char = String::kMaxUtf16CodeUnit;
  3054. }
  3055. return ranges->at(0).IsEverything(max_char) ? on_success() : NULL;
  3056. }
  3057. // Finds the fixed match length of a sequence of nodes that goes from
  3058. // this alternative and back to this choice node. If there are variable
  3059. // length nodes or other complications in the way then return a sentinel
  3060. // value indicating that a greedy loop cannot be constructed.
  3061. int ChoiceNode::GreedyLoopTextLengthForAlternative(
  3062. GuardedAlternative* alternative) {
  3063. int length = 0;
  3064. RegExpNode* node = alternative->node();
  3065. // Later we will generate code for all these text nodes using recursion
  3066. // so we have to limit the max number.
  3067. int recursion_depth = 0;
  3068. while (node != this) {
  3069. if (recursion_depth++ > RegExpCompiler::kMaxRecursion) {
  3070. return kNodeIsTooComplexForGreedyLoops;
  3071. }
  3072. int node_length = node->GreedyLoopTextLength();
  3073. if (node_length == kNodeIsTooComplexForGreedyLoops) {
  3074. return kNodeIsTooComplexForGreedyLoops;
  3075. }
  3076. length += node_length;
  3077. SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node);
  3078. node = seq_node->on_success();
  3079. }
  3080. return length;
  3081. }
  3082. void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
  3083. DCHECK_EQ(loop_node_, NULL);
  3084. AddAlternative(alt);
  3085. loop_node_ = alt.node();
  3086. }
  3087. void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
  3088. DCHECK_EQ(continue_node_, NULL);
  3089. AddAlternative(alt);
  3090. continue_node_ = alt.node();
  3091. }
  3092. void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
  3093. RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
  3094. if (trace->stop_node() == this) {
  3095. int text_length =
  3096. GreedyLoopTextLengthForAlternative(&(alternatives_->at(0)));
  3097. DCHECK(text_length != kNodeIsTooComplexForGreedyLoops);
  3098. // Update the counter-based backtracking info on the stack. This is an
  3099. // optimization for greedy loops (see below).
  3100. DCHECK(trace->cp_offset() == text_length);
  3101. macro_assembler->AdvanceCurrentPosition(text_length);
  3102. macro_assembler->GoTo(trace->loop_label());
  3103. return;
  3104. }
  3105. DCHECK(trace->stop_node() == NULL);
  3106. if (!trace->is_trivial()) {
  3107. trace->Flush(compiler, this);
  3108. return;
  3109. }
  3110. ChoiceNode::Emit(compiler, trace);
  3111. }
  3112. int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler,
  3113. int eats_at_least) {
  3114. int preload_characters = Min(4, eats_at_least);
  3115. if (compiler->macro_assembler()->CanReadUnaligned()) {
  3116. bool ascii = compiler->ascii();
  3117. if (ascii) {
  3118. if (preload_characters > 4) preload_characters = 4;
  3119. // We can't preload 3 characters because there is no machine instruction
  3120. // to do that. We can't just load 4 because we could be reading
  3121. // beyond the end of the string, which could cause a memory fault.
  3122. if (preload_characters == 3) preload_characters = 2;
  3123. } else {
  3124. if (preload_characters > 2) preload_characters = 2;
  3125. }
  3126. } else {
  3127. if (preload_characters > 1) preload_characters = 1;
  3128. }
  3129. return preload_characters;
  3130. }
  3131. // This class is used when generating the alternatives in a choice node. It
  3132. // records the way the alternative is being code generated.
  3133. class AlternativeGeneration: public Malloced {
  3134. public:
  3135. AlternativeGeneration()
  3136. : possible_success(),
  3137. expects_preload(false),
  3138. after(),
  3139. quick_check_details() { }
  3140. Label possible_success;
  3141. bool expects_preload;
  3142. Label after;
  3143. QuickCheckDetails quick_check_details;
  3144. };
  3145. // Creates a list of AlternativeGenerations. If the list has a reasonable
  3146. // size then it is on the stack, otherwise the excess is on the heap.
  3147. class AlternativeGenerationList {
  3148. public:
  3149. AlternativeGenerationList(int count, Zone* zone)
  3150. : alt_gens_(count, zone) {
  3151. for (int i = 0; i < count && i < kAFew; i++) {
  3152. alt_gens_.Add(a_few_alt_gens_ + i, zone);
  3153. }
  3154. for (int i = kAFew; i < count; i++) {
  3155. alt_gens_.Add(new AlternativeGeneration(), zone);
  3156. }
  3157. }
  3158. ~AlternativeGenerationList() {
  3159. for (int i = kAFew; i < alt_gens_.length(); i++) {
  3160. delete alt_gens_[i];
  3161. alt_gens_[i] = NULL;
  3162. }
  3163. }
  3164. AlternativeGeneration* at(int i) {
  3165. return alt_gens_[i];
  3166. }
  3167. private:
  3168. static const int kAFew = 10;
  3169. ZoneList<AlternativeGeneration*> alt_gens_;
  3170. AlternativeGeneration a_few_alt_gens_[kAFew];
  3171. };
  3172. // The '2' variant is has inclusive from and exclusive to.
  3173. // This covers \s as defined in ECMA-262 5.1, 15.10.2.12,
  3174. // which include WhiteSpace (7.2) or LineTerminator (7.3) values.
  3175. static const int kSpaceRanges[] = { '\t', '\r' + 1, ' ', ' ' + 1,
  3176. 0x00A0, 0x00A1, 0x1680, 0x1681, 0x180E, 0x180F, 0x2000, 0x200B,
  3177. 0x2028, 0x202A, 0x202F, 0x2030, 0x205F, 0x2060, 0x3000, 0x3001,
  3178. 0xFEFF, 0xFF00, 0x10000 };
  3179. static const int kSpaceRangeCount = ARRAY_SIZE(kSpaceRanges);
  3180. static const int kWordRanges[] = {
  3181. '0', '9' + 1, 'A', 'Z' + 1, '_', '_' + 1, 'a', 'z' + 1, 0x10000 };
  3182. static const int kWordRangeCount = ARRAY_SIZE(kWordRanges);
  3183. static const int kDigitRanges[] = { '0', '9' + 1, 0x10000 };
  3184. static const int kDigitRangeCount = ARRAY_SIZE(kDigitRanges);
  3185. static const int kSurrogateRanges[] = { 0xd800, 0xe000, 0x10000 };
  3186. static const int kSurrogateRangeCount = ARRAY_SIZE(kSurrogateRanges);
  3187. static const int kLineTerminatorRanges[] = { 0x000A, 0x000B, 0x000D, 0x000E,
  3188. 0x2028, 0x202A, 0x10000 };
  3189. static const int kLineTerminatorRangeCount = ARRAY_SIZE(kLineTerminatorRanges);
  3190. void BoyerMoorePositionInfo::Set(int character) {
  3191. SetInterval(Interval(character, character));
  3192. }
  3193. void BoyerMoorePositionInfo::SetInterval(const Interval& interval) {
  3194. s_ = AddRange(s_, kSpaceRanges, kSpaceRangeCount, interval);
  3195. w_ = AddRange(w_, kWordRanges, kWordRangeCount, interval);
  3196. d_ = AddRange(d_, kDigitRanges, kDigitRangeCount, interval);
  3197. surrogate_ =
  3198. AddRange(surrogate_, kSurrogateRanges, kSurrogateRangeCount, interval);
  3199. if (interval.to() - interval.from() >= kMapSize - 1) {
  3200. if (map_count_ != kMapSize) {
  3201. map_count_ = kMapSize;
  3202. for (int i = 0; i < kMapSize; i++) map_->at(i) = true;
  3203. }
  3204. return;
  3205. }
  3206. for (int i = interval.from(); i <= interval.to(); i++) {
  3207. int mod_character = (i & kMask);
  3208. if (!map_->at(mod_character)) {
  3209. map_count_++;
  3210. map_->at(mod_character) = true;
  3211. }
  3212. if (map_count_ == kMapSize) return;
  3213. }
  3214. }
  3215. void BoyerMoorePositionInfo::SetAll() {
  3216. s_ = w_ = d_ = kLatticeUnknown;
  3217. if (map_count_ != kMapSize) {
  3218. map_count_ = kMapSize;
  3219. for (int i = 0; i < kMapSize; i++) map_->at(i) = true;
  3220. }
  3221. }
  3222. BoyerMooreLookahead::BoyerMooreLookahead(
  3223. int length, RegExpCompiler* compiler, Zone* zone)
  3224. : length_(length),
  3225. compiler_(compiler) {
  3226. if (compiler->ascii()) {
  3227. max_char_ = String::kMaxOneByteCharCode;
  3228. } else {
  3229. max_char_ = String::kMaxUtf16CodeUnit;
  3230. }
  3231. bitmaps_ = new(zone) ZoneList<BoyerMoorePositionInfo*>(length, zone);
  3232. for (int i = 0; i < length; i++) {
  3233. bitmaps_->Add(new(zone) BoyerMoorePositionInfo(zone), zone);
  3234. }
  3235. }
  3236. // Find the longest range of lookahead that has the fewest number of different
  3237. // characters that can occur at a given position. Since we are optimizing two
  3238. // different parameters at once this is a tradeoff.
  3239. bool BoyerMooreLookahead::FindWorthwhileInterval(int* from, int* to) {
  3240. int biggest_points = 0;
  3241. // If more than 32 characters out of 128 can occur it is unlikely that we can
  3242. // be lucky enough to step forwards much of the time.
  3243. const int kMaxMax = 32;
  3244. for (int max_number_of_chars = 4;
  3245. max_number_of_chars < kMaxMax;
  3246. max_number_of_chars *= 2) {
  3247. biggest_points =
  3248. FindBestInterval(max_number_of_chars, biggest_points, from, to);
  3249. }
  3250. if (biggest_points == 0) return false;
  3251. return true;
  3252. }
  3253. // Find the highest-points range between 0 and length_ where the character
  3254. // information is not too vague. 'Too vague' means that there are more than
  3255. // max_number_of_chars that can occur at this position. Calculates the number
  3256. // of points as the product of width-of-the-range and
  3257. // probability-of-finding-one-of-the-characters, where the probability is
  3258. // calculated using the frequency distribution of the sample subject string.
  3259. int BoyerMooreLookahead::FindBestInterval(
  3260. int max_number_of_chars, int old_biggest_points, int* from, int* to) {
  3261. int biggest_points = old_biggest_points;
  3262. static const int kSize = RegExpMacroAssembler::kTableSize;
  3263. for (int i = 0; i < length_; ) {
  3264. while (i < length_ && Count(i) > max_number_of_chars) i++;
  3265. if (i == length_) break;
  3266. int remembered_from = i;
  3267. bool union_map[kSize];
  3268. for (int j = 0; j < kSize; j++) union_map[j] = false;
  3269. while (i < length_ && Count(i) <= max_number_of_chars) {
  3270. BoyerMoorePositionInfo* map = bitmaps_->at(i);
  3271. for (int j = 0; j < kSize; j++) union_map[j] |= map->at(j);
  3272. i++;
  3273. }
  3274. int frequency = 0;
  3275. for (int j = 0; j < kSize; j++) {
  3276. if (union_map[j]) {
  3277. // Add 1 to the frequency to give a small per-character boost for
  3278. // the cases where our sampling is not good enough and many
  3279. // characters have a frequency of zero. This means the frequency
  3280. // can theoretically be up to 2*kSize though we treat it mostly as
  3281. // a fraction of kSize.
  3282. frequency += compiler_->frequency_collator()->Frequency(j) + 1;
  3283. }
  3284. }
  3285. // We use the probability of skipping times the distance we are skipping to
  3286. // judge the effectiveness of this. Actually we have a cut-off: By
  3287. // dividing by 2 we switch off the skipping if the probability of skipping
  3288. // is less than 50%. This is because the multibyte mask-and-compare
  3289. // skipping in quickcheck is more likely to do well on this case.
  3290. bool in_quickcheck_range = ((i - remembered_from < 4) ||
  3291. (compiler_->ascii() ? remembered_from <= 4 : remembered_from <= 2));
  3292. // Called 'probability' but it is only a rough estimate and can actually
  3293. // be outside the 0-kSize range.
  3294. int probability = (in_quickcheck_range ? kSize / 2 : kSize) - frequency;
  3295. int points = (i - remembered_from) * probability;
  3296. if (points > biggest_points) {
  3297. *from = remembered_from;
  3298. *to = i - 1;
  3299. biggest_points = points;
  3300. }
  3301. }
  3302. return biggest_points;
  3303. }
  3304. // Take all the characters that will not prevent a successful match if they
  3305. // occur in the subject string in the range between min_lookahead and
  3306. // max_lookahead (inclusive) measured from the current position. If the
  3307. // character at max_lookahead offset is not one of these characters, then we
  3308. // can safely skip forwards by the number of characters in the range.
  3309. int BoyerMooreLookahead::GetSkipTable(int min_lookahead,
  3310. int max_lookahead,
  3311. Handle<ByteArray> boolean_skip_table) {
  3312. const int kSize = RegExpMacroAssembler::kTableSize;
  3313. const int kSkipArrayEntry = 0;
  3314. const int kDontSkipArrayEntry = 1;
  3315. for (int i = 0; i < kSize; i++) {
  3316. boolean_skip_table->set(i, kSkipArrayEntry);
  3317. }
  3318. int skip = max_lookahead + 1 - min_lookahead;
  3319. for (int i = max_lookahead; i >= min_lookahead; i--) {
  3320. BoyerMoorePositionInfo* map = bitmaps_->at(i);
  3321. for (int j = 0; j < kSize; j++) {
  3322. if (map->at(j)) {
  3323. boolean_skip_table->set(j, kDontSkipArrayEntry);
  3324. }
  3325. }
  3326. }
  3327. return skip;
  3328. }
  3329. // See comment above on the implementation of GetSkipTable.
  3330. bool BoyerMooreLookahead::EmitSkipInstructions(RegExpMacroAssembler* masm) {
  3331. const int kSize = RegExpMacroAssembler::kTableSize;
  3332. int min_lookahead = 0;
  3333. int max_lookahead = 0;
  3334. if (!FindWorthwhileInterval(&min_lookahead, &max_lookahead)) return false;
  3335. bool found_single_character = false;
  3336. int single_character = 0;
  3337. for (int i = max_lookahead; i >= min_lookahead; i--) {
  3338. BoyerMoorePositionInfo* map = bitmaps_->at(i);
  3339. if (map->map_count() > 1 ||
  3340. (found_single_character && map->map_count() != 0)) {
  3341. found_single_character = false;
  3342. break;
  3343. }
  3344. for (int j = 0; j < kSize; j++) {
  3345. if (map->at(j)) {
  3346. found_single_character = true;
  3347. single_character = j;
  3348. break;
  3349. }
  3350. }
  3351. }
  3352. int lookahead_width = max_lookahead + 1 - min_lookahead;
  3353. if (found_single_character && lookahead_width == 1 && max_lookahead < 3) {
  3354. // The mask-compare can probably handle this better.
  3355. return false;
  3356. }
  3357. if (found_single_character) {
  3358. Label cont, again;
  3359. masm->Bind(&again);
  3360. masm->LoadCurrentCharacter(max_lookahead, &cont, true);
  3361. if (max_char_ > kSize) {
  3362. masm->CheckCharacterAfterAnd(single_character,
  3363. RegExpMacroAssembler::kTableMask,
  3364. &cont);
  3365. } else {
  3366. masm->CheckCharacter(single_character, &cont);
  3367. }
  3368. masm->AdvanceCurrentPosition(lookahead_width);
  3369. masm->GoTo(&again);
  3370. masm->Bind(&cont);
  3371. return true;
  3372. }
  3373. Factory* factory = masm->zone()->isolate()->factory();
  3374. Handle<ByteArray> boolean_skip_table = factory->NewByteArray(kSize, TENURED);
  3375. int skip_distance = GetSkipTable(
  3376. min_lookahead, max_lookahead, boolean_skip_table);
  3377. DCHECK(skip_distance != 0);
  3378. Label cont, again;
  3379. masm->Bind(&again);
  3380. masm->LoadCurrentCharacter(max_lookahead, &cont, true);
  3381. masm->CheckBitInTable(boolean_skip_table, &cont);
  3382. masm->AdvanceCurrentPosition(skip_distance);
  3383. masm->GoTo(&again);
  3384. masm->Bind(&cont);
  3385. return true;
  3386. }
  3387. /* Code generation for choice nodes.
  3388. *
  3389. * We generate quick checks that do a mask and compare to eliminate a
  3390. * choice. If the quick check succeeds then it jumps to the continuation to
  3391. * do slow checks and check subsequent nodes. If it fails (the common case)
  3392. * it falls through to the next choice.
  3393. *
  3394. * Here is the desired flow graph. Nodes directly below each other imply
  3395. * fallthrough. Alternatives 1 and 2 have quick checks. Alternative
  3396. * 3 doesn't have a quick check so we have to call the slow check.
  3397. * Nodes are marked Qn for quick checks and Sn for slow checks. The entire
  3398. * regexp continuation is generated directly after the Sn node, up to the
  3399. * next GoTo if we decide to reuse some already generated code. Some
  3400. * nodes expect preload_characters to be preloaded into the current
  3401. * character register. R nodes do this preloading. Vertices are marked
  3402. * F for failures and S for success (possible success in the case of quick
  3403. * nodes). L, V, < and > are used as arrow heads.
  3404. *
  3405. * ----------> R
  3406. * |
  3407. * V
  3408. * Q1 -----> S1
  3409. * | S /
  3410. * F| /
  3411. * | F/
  3412. * | /
  3413. * | R
  3414. * | /
  3415. * V L
  3416. * Q2 -----> S2
  3417. * | S /
  3418. * F| /
  3419. * | F/
  3420. * | /
  3421. * | R
  3422. * | /
  3423. * V L
  3424. * S3
  3425. * |
  3426. * F|
  3427. * |
  3428. * R
  3429. * |
  3430. * backtrack V
  3431. * <----------Q4
  3432. * \ F |
  3433. * \ |S
  3434. * \ F V
  3435. * \-----S4
  3436. *
  3437. * For greedy loops we reverse our expectation and expect to match rather
  3438. * than fail. Therefore we want the loop code to look like this (U is the
  3439. * unwind code that steps back in the greedy loop). The following alternatives
  3440. * look the same as above.
  3441. * _____
  3442. * / \
  3443. * V |
  3444. * ----------> S1 |
  3445. * /| |
  3446. * / |S |
  3447. * F/ \_____/
  3448. * /
  3449. * |<-----------
  3450. * | \
  3451. * V \
  3452. * Q2 ---> S2 \
  3453. * | S / |
  3454. * F| / |
  3455. * | F/ |
  3456. * | / |
  3457. * | R |
  3458. * | / |
  3459. * F VL |
  3460. * <------U |
  3461. * back |S |
  3462. * \______________/
  3463. */
  3464. void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
  3465. RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
  3466. int choice_count = alternatives_->length();
  3467. #ifdef DEBUG
  3468. for (int i = 0; i < choice_count - 1; i++) {
  3469. GuardedAlternative alternative = alternatives_->at(i);
  3470. ZoneList<Guard*>* guards = alternative.guards();
  3471. int guard_count = (guards == NULL) ? 0 : guards->length();
  3472. for (int j = 0; j < guard_count; j++) {
  3473. DCHECK(!trace->mentions_reg(guards->at(j)->reg()));
  3474. }
  3475. }
  3476. #endif
  3477. LimitResult limit_result = LimitVersions(compiler, trace);
  3478. if (limit_result == DONE) return;
  3479. DCHECK(limit_result == CONTINUE);
  3480. int new_flush_budget = trace->flush_budget() / choice_count;
  3481. if (trace->flush_budget() == 0 && trace->actions() != NULL) {
  3482. trace->Flush(compiler, this);
  3483. return;
  3484. }
  3485. RecursionCheck rc(compiler);
  3486. Trace* current_trace = trace;
  3487. int text_length = GreedyLoopTextLengthForAlternative(&(alternatives_->at(0)));
  3488. bool greedy_loop = false;
  3489. Label greedy_loop_label;
  3490. Trace counter_backtrack_trace;
  3491. counter_backtrack_trace.set_backtrack(&greedy_loop_label);
  3492. if (not_at_start()) counter_backtrack_trace.set_at_start(false);
  3493. if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) {
  3494. // Here we have special handling for greedy loops containing only text nodes
  3495. // and other simple nodes. These are handled by pushing the current
  3496. // position on the stack and then incrementing the current position each
  3497. // time around the switch. On backtrack we decrement the current position
  3498. // and check it against the pushed value. This avoids pushing backtrack
  3499. // information for each iteration of the loop, which could take up a lot of
  3500. // space.
  3501. greedy_loop = true;
  3502. DCHECK(trace->stop_node() == NULL);
  3503. macro_assembler->PushCurrentPosition();
  3504. current_trace = &counter_backtrack_trace;
  3505. Label greedy_match_failed;
  3506. Trace greedy_match_trace;
  3507. if (not_at_start()) greedy_match_trace.set_at_start(false);
  3508. greedy_match_trace.set_backtrack(&greedy_match_failed);
  3509. Label loop_label;
  3510. macro_assembler->Bind(&loop_label);
  3511. greedy_match_trace.set_stop_node(this);
  3512. greedy_match_trace.set_loop_label(&loop_label);
  3513. alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
  3514. macro_assembler->Bind(&greedy_match_failed);
  3515. }
  3516. Label second_choice; // For use in greedy matches.
  3517. macro_assembler->Bind(&second_choice);
  3518. int first_normal_choice = greedy_loop ? 1 : 0;
  3519. bool not_at_start = current_trace->at_start() == Trace::FALSE_VALUE;
  3520. const int kEatsAtLeastNotYetInitialized = -1;
  3521. int eats_at_least = kEatsAtLeastNotYetInitialized;
  3522. bool skip_was_emitted = false;
  3523. if (!greedy_loop && choice_count == 2) {
  3524. GuardedAlternative alt1 = alternatives_->at(1);
  3525. if (alt1.guards() == NULL || alt1.guards()->length() == 0) {
  3526. RegExpNode* eats_anything_node = alt1.node();
  3527. if (eats_anything_node->GetSuccessorOfOmnivorousTextNode(compiler) ==
  3528. this) {
  3529. // At this point we know that we are at a non-greedy loop that will eat
  3530. // any character one at a time. Any non-anchored regexp has such a
  3531. // loop prepended to it in order to find where it starts. We look for
  3532. // a pattern of the form ...abc... where we can look 6 characters ahead
  3533. // and step forwards 3 if the character is not one of abc. Abc need
  3534. // not be atoms, they can be any reasonably limited character class or
  3535. // small alternation.
  3536. DCHECK(trace->is_trivial()); // This is the case on LoopChoiceNodes.
  3537. BoyerMooreLookahead* lookahead = bm_info(not_at_start);
  3538. if (lookahead == NULL) {
  3539. eats_at_least = Min(kMaxLookaheadForBoyerMoore,
  3540. EatsAtLeast(kMaxLookaheadForBoyerMoore,
  3541. kRecursionBudget,
  3542. not_at_start));
  3543. if (eats_at_least >= 1) {
  3544. BoyerMooreLookahead* bm =
  3545. new(zone()) BoyerMooreLookahead(eats_at_least,
  3546. compiler,
  3547. zone());
  3548. GuardedAlternative alt0 = alternatives_->at(0);
  3549. alt0.node()->FillInBMInfo(0, kRecursionBudget, bm, not_at_start);
  3550. skip_was_emitted = bm->EmitSkipInstructions(macro_assembler);
  3551. }
  3552. } else {
  3553. skip_was_emitted = lookahead->EmitSkipInstructions(macro_assembler);
  3554. }
  3555. }
  3556. }
  3557. }
  3558. if (eats_at_least == kEatsAtLeastNotYetInitialized) {
  3559. // Save some time by looking at most one machine word ahead.
  3560. eats_at_least =
  3561. EatsAtLeast(compiler->ascii() ? 4 : 2, kRecursionBudget, not_at_start);
  3562. }
  3563. int preload_characters = CalculatePreloadCharacters(compiler, eats_at_least);
  3564. bool preload_is_current = !skip_was_emitted &&
  3565. (current_trace->characters_preloaded() == preload_characters);
  3566. bool preload_has_checked_bounds = preload_is_current;
  3567. AlternativeGenerationList alt_gens(choice_count, zone());
  3568. // For now we just call all choices one after the other. The idea ultimately
  3569. // is to use the Dispatch table to try only the relevant ones.
  3570. for (int i = first_normal_choice; i < choice_count; i++) {
  3571. GuardedAlternative alternative = alternatives_->at(i);
  3572. AlternativeGeneration* alt_gen = alt_gens.at(i);
  3573. alt_gen->quick_check_details.set_characters(preload_characters);
  3574. ZoneList<Guard*>* guards = alternative.guards();
  3575. int guard_count = (guards == NULL) ? 0 : guards->length();
  3576. Trace new_trace(*current_trace);
  3577. new_trace.set_characters_preloaded(preload_is_current ?
  3578. preload_characters :
  3579. 0);
  3580. if (preload_has_checked_bounds) {
  3581. new_trace.set_bound_checked_up_to(preload_characters);
  3582. }
  3583. new_trace.quick_check_performed()->Clear();
  3584. if (not_at_start_) new_trace.set_at_start(Trace::FALSE_VALUE);
  3585. alt_gen->expects_preload = preload_is_current;
  3586. bool generate_full_check_inline = false;
  3587. if (FLAG_regexp_optimization &&
  3588. try_to_emit_quick_check_for_alternative(i) &&
  3589. alternative.node()->EmitQuickCheck(compiler,
  3590. &new_trace,
  3591. preload_has_checked_bounds,
  3592. &alt_gen->possible_success,
  3593. &alt_gen->quick_check_details,
  3594. i < choice_count - 1)) {
  3595. // Quick check was generated for this choice.
  3596. preload_is_current = true;
  3597. preload_has_checked_bounds = true;
  3598. // On the last choice in the ChoiceNode we generated the quick
  3599. // check to fall through on possible success. So now we need to
  3600. // generate the full check inline.
  3601. if (i == choice_count - 1) {
  3602. macro_assembler->Bind(&alt_gen->possible_success);
  3603. new_trace.set_quick_check_performed(&alt_gen->quick_check_details);
  3604. new_trace.set_characters_preloaded(preload_characters);
  3605. new_trace.set_bound_checked_up_to(preload_characters);
  3606. generate_full_check_inline = true;
  3607. }
  3608. } else if (alt_gen->quick_check_details.cannot_match()) {
  3609. if (i == choice_count - 1 && !greedy_loop) {
  3610. macro_assembler->GoTo(trace->backtrack());
  3611. }
  3612. continue;
  3613. } else {
  3614. // No quick check was generated. Put the full code here.
  3615. // If this is not the first choice then there could be slow checks from
  3616. // previous cases that go here when they fail. There's no reason to
  3617. // insist that they preload characters since the slow check we are about
  3618. // to generate probably can't use it.
  3619. if (i != first_normal_choice) {
  3620. alt_gen->expects_preload = false;
  3621. new_trace.InvalidateCurrentCharacter();
  3622. }
  3623. if (i < choice_count - 1) {
  3624. new_trace.set_backtrack(&alt_gen->after);
  3625. }
  3626. generate_full_check_inline = true;
  3627. }
  3628. if (generate_full_check_inline) {
  3629. if (new_trace.actions() != NULL) {
  3630. new_trace.set_flush_budget(new_flush_budget);
  3631. }
  3632. for (int j = 0; j < guard_count; j++) {
  3633. GenerateGuard(macro_assembler, guards->at(j), &new_trace);
  3634. }
  3635. alternative.node()->Emit(compiler, &new_trace);
  3636. preload_is_current = false;
  3637. }
  3638. macro_assembler->Bind(&alt_gen->after);
  3639. }
  3640. if (greedy_loop) {
  3641. macro_assembler->Bind(&greedy_loop_label);
  3642. // If we have unwound to the bottom then backtrack.
  3643. macro_assembler->CheckGreedyLoop(trace->backtrack());
  3644. // Otherwise try the second priority at an earlier position.
  3645. macro_assembler->AdvanceCurrentPosition(-text_length);
  3646. macro_assembler->GoTo(&second_choice);
  3647. }
  3648. // At this point we need to generate slow checks for the alternatives where
  3649. // the quick check was inlined. We can recognize these because the associated
  3650. // label was bound.
  3651. for (int i = first_normal_choice; i < choice_count - 1; i++) {
  3652. AlternativeGeneration* alt_gen = alt_gens.at(i);
  3653. Trace new_trace(*current_trace);
  3654. // If there are actions to be flushed we have to limit how many times
  3655. // they are flushed. Take the budget of the parent trace and distribute
  3656. // it fairly amongst the children.
  3657. if (new_trace.actions() != NULL) {
  3658. new_trace.set_flush_budget(new_flush_budget);
  3659. }
  3660. EmitOutOfLineContinuation(compiler,
  3661. &new_trace,
  3662. alternatives_->at(i),
  3663. alt_gen,
  3664. preload_characters,
  3665. alt_gens.at(i + 1)->expects_preload);
  3666. }
  3667. }
  3668. void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
  3669. Trace* trace,
  3670. GuardedAlternative alternative,
  3671. AlternativeGeneration* alt_gen,
  3672. int preload_characters,
  3673. bool next_expects_preload) {
  3674. if (!alt_gen->possible_success.is_linked()) return;
  3675. RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
  3676. macro_assembler->Bind(&alt_gen->possible_success);
  3677. Trace out_of_line_trace(*trace);
  3678. out_of_line_trace.set_characters_preloaded(preload_characters);
  3679. out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details);
  3680. if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE_VALUE);
  3681. ZoneList<Guard*>* guards = alternative.guards();
  3682. int guard_count = (guards == NULL) ? 0 : guards->length();
  3683. if (next_expects_preload) {
  3684. Label reload_current_char;
  3685. out_of_line_trace.set_backtrack(&reload_current_char);
  3686. for (int j = 0; j < guard_count; j++) {
  3687. GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
  3688. }
  3689. alternative.node()->Emit(compiler, &out_of_line_trace);
  3690. macro_assembler->Bind(&reload_current_char);
  3691. // Reload the current character, since the next quick check expects that.
  3692. // We don't need to check bounds here because we only get into this
  3693. // code through a quick check which already did the checked load.
  3694. macro_assembler->LoadCurrentCharacter(trace->cp_offset(),
  3695. NULL,
  3696. false,
  3697. preload_characters);
  3698. macro_assembler->GoTo(&(alt_gen->after));
  3699. } else {
  3700. out_of_line_trace.set_backtrack(&(alt_gen->after));
  3701. for (int j = 0; j < guard_count; j++) {
  3702. GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
  3703. }
  3704. alternative.node()->Emit(compiler, &out_of_line_trace);
  3705. }
  3706. }
  3707. void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
  3708. RegExpMacroAssembler* assembler = compiler->macro_assembler();
  3709. LimitResult limit_result = LimitVersions(compiler, trace);
  3710. if (limit_result == DONE) return;
  3711. DCHECK(limit_result == CONTINUE);
  3712. RecursionCheck rc(compiler);
  3713. switch (action_type_) {
  3714. case STORE_POSITION: {
  3715. Trace::DeferredCapture
  3716. new_capture(data_.u_position_register.reg,
  3717. data_.u_position_register.is_capture,
  3718. trace);
  3719. Trace new_trace = *trace;
  3720. new_trace.add_action(&new_capture);
  3721. on_success()->Emit(compiler, &new_trace);
  3722. break;
  3723. }
  3724. case INCREMENT_REGISTER: {
  3725. Trace::DeferredIncrementRegister
  3726. new_increment(data_.u_increment_register.reg);
  3727. Trace new_trace = *trace;
  3728. new_trace.add_action(&new_increment);
  3729. on_success()->Emit(compiler, &new_trace);
  3730. break;
  3731. }
  3732. case SET_REGISTER: {
  3733. Trace::DeferredSetRegister
  3734. new_set(data_.u_store_register.reg, data_.u_store_register.value);
  3735. Trace new_trace = *trace;
  3736. new_trace.add_action(&new_set);
  3737. on_success()->Emit(compiler, &new_trace);
  3738. break;
  3739. }
  3740. case CLEAR_CAPTURES: {
  3741. Trace::DeferredClearCaptures
  3742. new_capture(Interval(data_.u_clear_captures.range_from,
  3743. data_.u_clear_captures.range_to));
  3744. Trace new_trace = *trace;
  3745. new_trace.add_action(&new_capture);
  3746. on_success()->Emit(compiler, &new_trace);
  3747. break;
  3748. }
  3749. case BEGIN_SUBMATCH:
  3750. if (!trace->is_trivial()) {
  3751. trace->Flush(compiler, this);
  3752. } else {
  3753. assembler->WriteCurrentPositionToRegister(
  3754. data_.u_submatch.current_position_register, 0);
  3755. assembler->WriteStackPointerToRegister(
  3756. data_.u_submatch.stack_pointer_register);
  3757. on_success()->Emit(compiler, trace);
  3758. }
  3759. break;
  3760. case EMPTY_MATCH_CHECK: {
  3761. int start_pos_reg = data_.u_empty_match_check.start_register;
  3762. int stored_pos = 0;
  3763. int rep_reg = data_.u_empty_match_check.repetition_register;
  3764. bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister);
  3765. bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos);
  3766. if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) {
  3767. // If we know we haven't advanced and there is no minimum we
  3768. // can just backtrack immediately.
  3769. assembler->GoTo(trace->backtrack());
  3770. } else if (know_dist && stored_pos < trace->cp_offset()) {
  3771. // If we know we've advanced we can generate the continuation
  3772. // immediately.
  3773. on_success()->Emit(compiler, trace);
  3774. } else if (!trace->is_trivial()) {
  3775. trace->Flush(compiler, this);
  3776. } else {
  3777. Label skip_empty_check;
  3778. // If we have a minimum number of repetitions we check the current
  3779. // number first and skip the empty check if it's not enough.
  3780. if (has_minimum) {
  3781. int limit = data_.u_empty_match_check.repetition_limit;
  3782. assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check);
  3783. }
  3784. // If the match is empty we bail out, otherwise we fall through
  3785. // to the on-success continuation.
  3786. assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register,
  3787. trace->backtrack());
  3788. assembler->Bind(&skip_empty_check);
  3789. on_success()->Emit(compiler, trace);
  3790. }
  3791. break;
  3792. }
  3793. case POSITIVE_SUBMATCH_SUCCESS: {
  3794. if (!trace->is_trivial()) {
  3795. trace->Flush(compiler, this);
  3796. return;
  3797. }
  3798. assembler->ReadCurrentPositionFromRegister(
  3799. data_.u_submatch.current_position_register);
  3800. assembler->ReadStackPointerFromRegister(
  3801. data_.u_submatch.stack_pointer_register);
  3802. int clear_register_count = data_.u_submatch.clear_register_count;
  3803. if (clear_register_count == 0) {
  3804. on_success()->Emit(compiler, trace);
  3805. return;
  3806. }
  3807. int clear_registers_from = data_.u_submatch.clear_register_from;
  3808. Label clear_registers_backtrack;
  3809. Trace new_trace = *trace;
  3810. new_trace.set_backtrack(&clear_registers_backtrack);
  3811. on_success()->Emit(compiler, &new_trace);
  3812. assembler->Bind(&clear_registers_backtrack);
  3813. int clear_registers_to = clear_registers_from + clear_register_count - 1;
  3814. assembler->ClearRegisters(clear_registers_from, clear_registers_to);
  3815. DCHECK(trace->backtrack() == NULL);
  3816. assembler->Backtrack();
  3817. return;
  3818. }
  3819. default:
  3820. UNREACHABLE();
  3821. }
  3822. }
  3823. void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
  3824. RegExpMacroAssembler* assembler = compiler->macro_assembler();
  3825. if (!trace->is_trivial()) {
  3826. trace->Flush(compiler, this);
  3827. return;
  3828. }
  3829. LimitResult limit_result = LimitVersions(compiler, trace);
  3830. if (limit_result == DONE) return;
  3831. DCHECK(limit_result == CONTINUE);
  3832. RecursionCheck rc(compiler);
  3833. DCHECK_EQ(start_reg_ + 1, end_reg_);
  3834. if (compiler->ignore_case()) {
  3835. assembler->CheckNotBackReferenceIgnoreCase(start_reg_,
  3836. trace->backtrack());
  3837. } else {
  3838. assembler->CheckNotBackReference(start_reg_, trace->backtrack());
  3839. }
  3840. on_success()->Emit(compiler, trace);
  3841. }
  3842. // -------------------------------------------------------------------
  3843. // Dot/dotty output
  3844. #ifdef DEBUG
  3845. class DotPrinter: public NodeVisitor {
  3846. public:
  3847. DotPrinter(OStream& os, bool ignore_case) // NOLINT
  3848. : os_(os),
  3849. ignore_case_(ignore_case) {}
  3850. void PrintNode(const char* label, RegExpNode* node);
  3851. void Visit(RegExpNode* node);
  3852. void PrintAttributes(RegExpNode* from);
  3853. void PrintOnFailure(RegExpNode* from, RegExpNode* to);
  3854. #define DECLARE_VISIT(Type) \
  3855. virtual void Visit##Type(Type##Node* that);
  3856. FOR_EACH_NODE_TYPE(DECLARE_VISIT)
  3857. #undef DECLARE_VISIT
  3858. private:
  3859. OStream& os_;
  3860. bool ignore_case_;
  3861. };
  3862. void DotPrinter::PrintNode(const char* label, RegExpNode* node) {
  3863. os_ << "digraph G {\n graph [label=\"";
  3864. for (int i = 0; label[i]; i++) {
  3865. switch (label[i]) {
  3866. case '\\':
  3867. os_ << "\\\\";
  3868. break;
  3869. case '"':
  3870. os_ << "\"";
  3871. break;
  3872. default:
  3873. os_ << label[i];
  3874. break;
  3875. }
  3876. }
  3877. os_ << "\"];\n";
  3878. Visit(node);
  3879. os_ << "}" << endl;
  3880. }
  3881. void DotPrinter::Visit(RegExpNode* node) {
  3882. if (node->info()->visited) return;
  3883. node->info()->visited = true;
  3884. node->Accept(this);
  3885. }
  3886. void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
  3887. os_ << " n" << from << " -> n" << on_failure << " [style=dotted];\n";
  3888. Visit(on_failure);
  3889. }
  3890. class TableEntryBodyPrinter {
  3891. public:
  3892. TableEntryBodyPrinter(OStream& os, ChoiceNode* choice) // NOLINT
  3893. : os_(os),
  3894. choice_(choice) {}
  3895. void Call(uc16 from, DispatchTable::Entry entry) {
  3896. OutSet* out_set = entry.out_set();
  3897. for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
  3898. if (out_set->Get(i)) {
  3899. os_ << " n" << choice() << ":s" << from << "o" << i << " -> n"
  3900. << choice()->alternatives()->at(i).node() << ";\n";
  3901. }
  3902. }
  3903. }
  3904. private:
  3905. ChoiceNode* choice() { return choice_; }
  3906. OStream& os_;
  3907. ChoiceNode* choice_;
  3908. };
  3909. class TableEntryHeaderPrinter {
  3910. public:
  3911. explicit TableEntryHeaderPrinter(OStream& os) // NOLINT
  3912. : first_(true),
  3913. os_(os) {}
  3914. void Call(uc16 from, DispatchTable::Entry entry) {
  3915. if (first_) {
  3916. first_ = false;
  3917. } else {
  3918. os_ << "|";
  3919. }
  3920. os_ << "{\\" << AsUC16(from) << "-\\" << AsUC16(entry.to()) << "|{";
  3921. OutSet* out_set = entry.out_set();
  3922. int priority = 0;
  3923. for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
  3924. if (out_set->Get(i)) {
  3925. if (priority > 0) os_ << "|";
  3926. os_ << "<s" << from << "o" << i << "> " << priority;
  3927. priority++;
  3928. }
  3929. }
  3930. os_ << "}}";
  3931. }
  3932. private:
  3933. bool first_;
  3934. OStream& os_;
  3935. };
  3936. class AttributePrinter {
  3937. public:
  3938. explicit AttributePrinter(OStream& os) // NOLINT
  3939. : os_(os),
  3940. first_(true) {}
  3941. void PrintSeparator() {
  3942. if (first_) {
  3943. first_ = false;
  3944. } else {
  3945. os_ << "|";
  3946. }
  3947. }
  3948. void PrintBit(const char* name, bool value) {
  3949. if (!value) return;
  3950. PrintSeparator();
  3951. os_ << "{" << name << "}";
  3952. }
  3953. void PrintPositive(const char* name, int value) {
  3954. if (value < 0) return;
  3955. PrintSeparator();
  3956. os_ << "{" << name << "|" << value << "}";
  3957. }
  3958. private:
  3959. OStream& os_;
  3960. bool first_;
  3961. };
  3962. void DotPrinter::PrintAttributes(RegExpNode* that) {
  3963. os_ << " a" << that << " [shape=Mrecord, color=grey, fontcolor=grey, "
  3964. << "margin=0.1, fontsize=10, label=\"{";
  3965. AttributePrinter printer(os_);
  3966. NodeInfo* info = that->info();
  3967. printer.PrintBit("NI", info->follows_newline_interest);
  3968. printer.PrintBit("WI", info->follows_word_interest);
  3969. printer.PrintBit("SI", info->follows_start_interest);
  3970. Label* label = that->label();
  3971. if (label->is_bound())
  3972. printer.PrintPositive("@", label->pos());
  3973. os_ << "}\"];\n"
  3974. << " a" << that << " -> n" << that
  3975. << " [style=dashed, color=grey, arrowhead=none];\n";
  3976. }
  3977. static const bool kPrintDispatchTable = false;
  3978. void DotPrinter::VisitChoice(ChoiceNode* that) {
  3979. if (kPrintDispatchTable) {
  3980. os_ << " n" << that << " [shape=Mrecord, label=\"";
  3981. TableEntryHeaderPrinter header_printer(os_);
  3982. that->GetTable(ignore_case_)->ForEach(&header_printer);
  3983. os_ << "\"]\n";
  3984. PrintAttributes(that);
  3985. TableEntryBodyPrinter body_printer(os_, that);
  3986. that->GetTable(ignore_case_)->ForEach(&body_printer);
  3987. } else {
  3988. os_ << " n" << that << " [shape=Mrecord, label=\"?\"];\n";
  3989. for (int i = 0; i < that->alternatives()->length(); i++) {
  3990. GuardedAlternative alt = that->alternatives()->at(i);
  3991. os_ << " n" << that << " -> n" << alt.node();
  3992. }
  3993. }
  3994. for (int i = 0; i < that->alternatives()->length(); i++) {
  3995. GuardedAlternative alt = that->alternatives()->at(i);
  3996. alt.node()->Accept(this);
  3997. }
  3998. }
  3999. void DotPrinter::VisitText(TextNode* that) {
  4000. Zone* zone = that->zone();
  4001. os_ << " n" << that << " [label=\"";
  4002. for (int i = 0; i < that->elements()->length(); i++) {
  4003. if (i > 0) os_ << " ";
  4004. TextElement elm = that->elements()->at(i);
  4005. switch (elm.text_type()) {
  4006. case TextElement::ATOM: {
  4007. Vector<const uc16> data = elm.atom()->data();
  4008. for (int i = 0; i < data.length(); i++) {
  4009. os_ << static_cast<char>(data[i]);
  4010. }
  4011. break;
  4012. }
  4013. case TextElement::CHAR_CLASS: {
  4014. RegExpCharacterClass* node = elm.char_class();
  4015. os_ << "[";
  4016. if (node->is_negated()) os_ << "^";
  4017. for (int j = 0; j < node->ranges(zone)->length(); j++) {
  4018. CharacterRange range = node->ranges(zone)->at(j);
  4019. os_ << AsUC16(range.from()) << "-" << AsUC16(range.to());
  4020. }
  4021. os_ << "]";
  4022. break;
  4023. }
  4024. default:
  4025. UNREACHABLE();
  4026. }
  4027. }
  4028. os_ << "\", shape=box, peripheries=2];\n";
  4029. PrintAttributes(that);
  4030. os_ << " n" << that << " -> n" << that->on_success() << ";\n";
  4031. Visit(that->on_success());
  4032. }
  4033. void DotPrinter::VisitBackReference(BackReferenceNode* that) {
  4034. os_ << " n" << that << " [label=\"$" << that->start_register() << "..$"
  4035. << that->end_register() << "\", shape=doubleoctagon];\n";
  4036. PrintAttributes(that);
  4037. os_ << " n" << that << " -> n" << that->on_success() << ";\n";
  4038. Visit(that->on_success());
  4039. }
  4040. void DotPrinter::VisitEnd(EndNode* that) {
  4041. os_ << " n" << that << " [style=bold, shape=point];\n";
  4042. PrintAttributes(that);
  4043. }
  4044. void DotPrinter::VisitAssertion(AssertionNode* that) {
  4045. os_ << " n" << that << " [";
  4046. switch (that->assertion_type()) {
  4047. case AssertionNode::AT_END:
  4048. os_ << "label=\"$\", shape=septagon";
  4049. break;
  4050. case AssertionNode::AT_START:
  4051. os_ << "label=\"^\", shape=septagon";
  4052. break;
  4053. case AssertionNode::AT_BOUNDARY:
  4054. os_ << "label=\"\\b\", shape=septagon";
  4055. break;
  4056. case AssertionNode::AT_NON_BOUNDARY:
  4057. os_ << "label=\"\\B\", shape=septagon";
  4058. break;
  4059. case AssertionNode::AFTER_NEWLINE:
  4060. os_ << "label=\"(?<=\\n)\", shape=septagon";
  4061. break;
  4062. }
  4063. os_ << "];\n";
  4064. PrintAttributes(that);
  4065. RegExpNode* successor = that->on_success();
  4066. os_ << " n" << that << " -> n" << successor << ";\n";
  4067. Visit(successor);
  4068. }
  4069. void DotPrinter::VisitAction(ActionNode* that) {
  4070. os_ << " n" << that << " [";
  4071. switch (that->action_type_) {
  4072. case ActionNode::SET_REGISTER:
  4073. os_ << "label=\"$" << that->data_.u_store_register.reg
  4074. << ":=" << that->data_.u_store_register.value << "\", shape=octagon";
  4075. break;
  4076. case ActionNode::INCREMENT_REGISTER:
  4077. os_ << "label=\"$" << that->data_.u_increment_register.reg
  4078. << "++\", shape=octagon";
  4079. break;
  4080. case ActionNode::STORE_POSITION:
  4081. os_ << "label=\"$" << that->data_.u_position_register.reg
  4082. << ":=$pos\", shape=octagon";
  4083. break;
  4084. case ActionNode::BEGIN_SUBMATCH:
  4085. os_ << "label=\"$" << that->data_.u_submatch.current_position_register
  4086. << ":=$pos,begin\", shape=septagon";
  4087. break;
  4088. case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
  4089. os_ << "label=\"escape\", shape=septagon";
  4090. break;
  4091. case ActionNode::EMPTY_MATCH_CHECK:
  4092. os_ << "label=\"$" << that->data_.u_empty_match_check.start_register
  4093. << "=$pos?,$" << that->data_.u_empty_match_check.repetition_register
  4094. << "<" << that->data_.u_empty_match_check.repetition_limit
  4095. << "?\", shape=septagon";
  4096. break;
  4097. case ActionNode::CLEAR_CAPTURES: {
  4098. os_ << "label=\"clear $" << that->data_.u_clear_captures.range_from
  4099. << " to $" << that->data_.u_clear_captures.range_to
  4100. << "\", shape=septagon";
  4101. break;
  4102. }
  4103. }
  4104. os_ << "];\n";
  4105. PrintAttributes(that);
  4106. RegExpNode* successor = that->on_success();
  4107. os_ << " n" << that << " -> n" << successor << ";\n";
  4108. Visit(successor);
  4109. }
  4110. class DispatchTableDumper {
  4111. public:
  4112. explicit DispatchTableDumper(OStream& os) : os_(os) {}
  4113. void Call(uc16 key, DispatchTable::Entry entry);
  4114. private:
  4115. OStream& os_;
  4116. };
  4117. void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) {
  4118. os_ << "[" << AsUC16(key) << "-" << AsUC16(entry.to()) << "]: {";
  4119. OutSet* set = entry.out_set();
  4120. bool first = true;
  4121. for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
  4122. if (set->Get(i)) {
  4123. if (first) {
  4124. first = false;
  4125. } else {
  4126. os_ << ", ";
  4127. }
  4128. os_ << i;
  4129. }
  4130. }
  4131. os_ << "}\n";
  4132. }
  4133. void DispatchTable::Dump() {
  4134. OFStream os(stderr);
  4135. DispatchTableDumper dumper(os);
  4136. tree()->ForEach(&dumper);
  4137. }
  4138. void RegExpEngine::DotPrint(const char* label,
  4139. RegExpNode* node,
  4140. bool ignore_case) {
  4141. OFStream os(stdout);
  4142. DotPrinter printer(os, ignore_case);
  4143. printer.PrintNode(label, node);
  4144. }
  4145. #endif // DEBUG
  4146. // -------------------------------------------------------------------
  4147. // Tree to graph conversion
  4148. RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
  4149. RegExpNode* on_success) {
  4150. ZoneList<TextElement>* elms =
  4151. new(compiler->zone()) ZoneList<TextElement>(1, compiler->zone());
  4152. elms->Add(TextElement::Atom(this), compiler->zone());
  4153. return new(compiler->zone()) TextNode(elms, on_success);
  4154. }
  4155. RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
  4156. RegExpNode* on_success) {
  4157. return new(compiler->zone()) TextNode(elements(), on_success);
  4158. }
  4159. static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
  4160. const int* special_class,
  4161. int length) {
  4162. length--; // Remove final 0x10000.
  4163. DCHECK(special_class[length] == 0x10000);
  4164. DCHECK(ranges->length() != 0);
  4165. DCHECK(length != 0);
  4166. DCHECK(special_class[0] != 0);
  4167. if (ranges->length() != (length >> 1) + 1) {
  4168. return false;
  4169. }
  4170. CharacterRange range = ranges->at(0);
  4171. if (range.from() != 0) {
  4172. return false;
  4173. }
  4174. for (int i = 0; i < length; i += 2) {
  4175. if (special_class[i] != (range.to() + 1)) {
  4176. return false;
  4177. }
  4178. range = ranges->at((i >> 1) + 1);
  4179. if (special_class[i+1] != range.from()) {
  4180. return false;
  4181. }
  4182. }
  4183. if (range.to() != 0xffff) {
  4184. return false;
  4185. }
  4186. return true;
  4187. }
  4188. static bool CompareRanges(ZoneList<CharacterRange>* ranges,
  4189. const int* special_class,
  4190. int length) {
  4191. length--; // Remove final 0x10000.
  4192. DCHECK(special_class[length] == 0x10000);
  4193. if (ranges->length() * 2 != length) {
  4194. return false;
  4195. }
  4196. for (int i = 0; i < length; i += 2) {
  4197. CharacterRange range = ranges->at(i >> 1);
  4198. if (range.from() != special_class[i] ||
  4199. range.to() != special_class[i + 1] - 1) {
  4200. return false;
  4201. }
  4202. }
  4203. return true;
  4204. }
  4205. bool RegExpCharacterClass::is_standard(Zone* zone) {
  4206. // TODO(lrn): Remove need for this function, by not throwing away information
  4207. // along the way.
  4208. if (is_negated_) {
  4209. return false;
  4210. }
  4211. if (set_.is_standard()) {
  4212. return true;
  4213. }
  4214. if (CompareRanges(set_.ranges(zone), kSpaceRanges, kSpaceRangeCount)) {
  4215. set_.set_standard_set_type('s');
  4216. return true;
  4217. }
  4218. if (CompareInverseRanges(set_.ranges(zone), kSpaceRanges, kSpaceRangeCount)) {
  4219. set_.set_standard_set_type('S');
  4220. return true;
  4221. }
  4222. if (CompareInverseRanges(set_.ranges(zone),
  4223. kLineTerminatorRanges,
  4224. kLineTerminatorRangeCount)) {
  4225. set_.set_standard_set_type('.');
  4226. return true;
  4227. }
  4228. if (CompareRanges(set_.ranges(zone),
  4229. kLineTerminatorRanges,
  4230. kLineTerminatorRangeCount)) {
  4231. set_.set_standard_set_type('n');
  4232. return true;
  4233. }
  4234. if (CompareRanges(set_.ranges(zone), kWordRanges, kWordRangeCount)) {
  4235. set_.set_standard_set_type('w');
  4236. return true;
  4237. }
  4238. if (CompareInverseRanges(set_.ranges(zone), kWordRanges, kWordRangeCount)) {
  4239. set_.set_standard_set_type('W');
  4240. return true;
  4241. }
  4242. return false;
  4243. }
  4244. RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
  4245. RegExpNode* on_success) {
  4246. return new(compiler->zone()) TextNode(this, on_success);
  4247. }
  4248. RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
  4249. RegExpNode* on_success) {
  4250. ZoneList<RegExpTree*>* alternatives = this->alternatives();
  4251. int length = alternatives->length();
  4252. ChoiceNode* result =
  4253. new(compiler->zone()) ChoiceNode(length, compiler->zone());
  4254. for (int i = 0; i < length; i++) {
  4255. GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler,
  4256. on_success));
  4257. result->AddAlternative(alternative);
  4258. }
  4259. return result;
  4260. }
  4261. RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
  4262. RegExpNode* on_success) {
  4263. return ToNode(min(),
  4264. max(),
  4265. is_greedy(),
  4266. body(),
  4267. compiler,
  4268. on_success);
  4269. }
  4270. // Scoped object to keep track of how much we unroll quantifier loops in the
  4271. // regexp graph generator.
  4272. class RegExpExpansionLimiter {
  4273. public:
  4274. static const int kMaxExpansionFactor = 6;
  4275. RegExpExpansionLimiter(RegExpCompiler* compiler, int factor)
  4276. : compiler_(compiler),
  4277. saved_expansion_factor_(compiler->current_expansion_factor()),
  4278. ok_to_expand_(saved_expansion_factor_ <= kMaxExpansionFactor) {
  4279. DCHECK(factor > 0);
  4280. if (ok_to_expand_) {
  4281. if (factor > kMaxExpansionFactor) {
  4282. // Avoid integer overflow of the current expansion factor.
  4283. ok_to_expand_ = false;
  4284. compiler->set_current_expansion_factor(kMaxExpansionFactor + 1);
  4285. } else {
  4286. int new_factor = saved_expansion_factor_ * factor;
  4287. ok_to_expand_ = (new_factor <= kMaxExpansionFactor);
  4288. compiler->set_current_expansion_factor(new_factor);
  4289. }
  4290. }
  4291. }
  4292. ~RegExpExpansionLimiter() {
  4293. compiler_->set_current_expansion_factor(saved_expansion_factor_);
  4294. }
  4295. bool ok_to_expand() { return ok_to_expand_; }
  4296. private:
  4297. RegExpCompiler* compiler_;
  4298. int saved_expansion_factor_;
  4299. bool ok_to_expand_;
  4300. DISALLOW_IMPLICIT_CONSTRUCTORS(RegExpExpansionLimiter);
  4301. };
  4302. RegExpNode* RegExpQuantifier::ToNode(int min,
  4303. int max,
  4304. bool is_greedy,
  4305. RegExpTree* body,
  4306. RegExpCompiler* compiler,
  4307. RegExpNode* on_success,
  4308. bool not_at_start) {
  4309. // x{f, t} becomes this:
  4310. //
  4311. // (r++)<-.
  4312. // | `
  4313. // | (x)
  4314. // v ^
  4315. // (r=0)-->(?)---/ [if r < t]
  4316. // |
  4317. // [if r >= f] \----> ...
  4318. //
  4319. // 15.10.2.5 RepeatMatcher algorithm.
  4320. // The parser has already eliminated the case where max is 0. In the case
  4321. // where max_match is zero the parser has removed the quantifier if min was
  4322. // > 0 and removed the atom if min was 0. See AddQuantifierToAtom.
  4323. // If we know that we cannot match zero length then things are a little
  4324. // simpler since we don't need to make the special zero length match check
  4325. // from step 2.1. If the min and max are small we can unroll a little in
  4326. // this case.
  4327. static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,}
  4328. static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3}
  4329. if (max == 0) return on_success; // This can happen due to recursion.
  4330. bool body_can_be_empty = (body->min_match() == 0);
  4331. int body_start_reg = RegExpCompiler::kNoRegister;
  4332. Interval capture_registers = body->CaptureRegisters();
  4333. bool needs_capture_clearing = !capture_registers.is_empty();
  4334. Zone* zone = compiler->zone();
  4335. if (body_can_be_empty) {
  4336. body_start_reg = compiler->AllocateRegister();
  4337. } else if (FLAG_regexp_optimization && !needs_capture_clearing) {
  4338. // Only unroll if there are no captures and the body can't be
  4339. // empty.
  4340. {
  4341. RegExpExpansionLimiter limiter(
  4342. compiler, min + ((max != min) ? 1 : 0));
  4343. if (min > 0 && min <= kMaxUnrolledMinMatches && limiter.ok_to_expand()) {
  4344. int new_max = (max == kInfinity) ? max : max - min;
  4345. // Recurse once to get the loop or optional matches after the fixed
  4346. // ones.
  4347. RegExpNode* answer = ToNode(
  4348. 0, new_max, is_greedy, body, compiler, on_success, true);
  4349. // Unroll the forced matches from 0 to min. This can cause chains of
  4350. // TextNodes (which the parser does not generate). These should be
  4351. // combined if it turns out they hinder good code generation.
  4352. for (int i = 0; i < min; i++) {
  4353. answer = body->ToNode(compiler, answer);
  4354. }
  4355. return answer;
  4356. }
  4357. }
  4358. if (max <= kMaxUnrolledMaxMatches && min == 0) {
  4359. DCHECK(max > 0); // Due to the 'if' above.
  4360. RegExpExpansionLimiter limiter(compiler, max);
  4361. if (limiter.ok_to_expand()) {
  4362. // Unroll the optional matches up to max.
  4363. RegExpNode* answer = on_success;
  4364. for (int i = 0; i < max; i++) {
  4365. ChoiceNode* alternation = new(zone) ChoiceNode(2, zone);
  4366. if (is_greedy) {
  4367. alternation->AddAlternative(
  4368. GuardedAlternative(body->ToNode(compiler, answer)));
  4369. alternation->AddAlternative(GuardedAlternative(on_success));
  4370. } else {
  4371. alternation->AddAlternative(GuardedAlternative(on_success));
  4372. alternation->AddAlternative(
  4373. GuardedAlternative(body->ToNode(compiler, answer)));
  4374. }
  4375. answer = alternation;
  4376. if (not_at_start) alternation->set_not_at_start();
  4377. }
  4378. return answer;
  4379. }
  4380. }
  4381. }
  4382. bool has_min = min > 0;
  4383. bool has_max = max < RegExpTree::kInfinity;
  4384. bool needs_counter = has_min || has_max;
  4385. int reg_ctr = needs_counter
  4386. ? compiler->AllocateRegister()
  4387. : RegExpCompiler::kNoRegister;
  4388. LoopChoiceNode* center = new(zone) LoopChoiceNode(body->min_match() == 0,
  4389. zone);
  4390. if (not_at_start) center->set_not_at_start();
  4391. RegExpNode* loop_return = needs_counter
  4392. ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
  4393. : static_cast<RegExpNode*>(center);
  4394. if (body_can_be_empty) {
  4395. // If the body can be empty we need to check if it was and then
  4396. // backtrack.
  4397. loop_return = ActionNode::EmptyMatchCheck(body_start_reg,
  4398. reg_ctr,
  4399. min,
  4400. loop_return);
  4401. }
  4402. RegExpNode* body_node = body->ToNode(compiler, loop_return);
  4403. if (body_can_be_empty) {
  4404. // If the body can be empty we need to store the start position
  4405. // so we can bail out if it was empty.
  4406. body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
  4407. }
  4408. if (needs_capture_clearing) {
  4409. // Before entering the body of this loop we need to clear captures.
  4410. body_node = ActionNode::ClearCaptures(capture_registers, body_node);
  4411. }
  4412. GuardedAlternative body_alt(body_node);
  4413. if (has_max) {
  4414. Guard* body_guard =
  4415. new(zone) Guard(reg_ctr, Guard::LT, max);
  4416. body_alt.AddGuard(body_guard, zone);
  4417. }
  4418. GuardedAlternative rest_alt(on_success);
  4419. if (has_min) {
  4420. Guard* rest_guard = new(compiler->zone()) Guard(reg_ctr, Guard::GEQ, min);
  4421. rest_alt.AddGuard(rest_guard, zone);
  4422. }
  4423. if (is_greedy) {
  4424. center->AddLoopAlternative(body_alt);
  4425. center->AddContinueAlternative(rest_alt);
  4426. } else {
  4427. center->AddContinueAlternative(rest_alt);
  4428. center->AddLoopAlternative(body_alt);
  4429. }
  4430. if (needs_counter) {
  4431. return ActionNode::SetRegister(reg_ctr, 0, center);
  4432. } else {
  4433. return center;
  4434. }
  4435. }
  4436. RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
  4437. RegExpNode* on_success) {
  4438. NodeInfo info;
  4439. Zone* zone = compiler->zone();
  4440. switch (assertion_type()) {
  4441. case START_OF_LINE:
  4442. return AssertionNode::AfterNewline(on_success);
  4443. case START_OF_INPUT:
  4444. return AssertionNode::AtStart(on_success);
  4445. case BOUNDARY:
  4446. return AssertionNode::AtBoundary(on_success);
  4447. case NON_BOUNDARY:
  4448. return AssertionNode::AtNonBoundary(on_success);
  4449. case END_OF_INPUT:
  4450. return AssertionNode::AtEnd(on_success);
  4451. case END_OF_LINE: {
  4452. // Compile $ in multiline regexps as an alternation with a positive
  4453. // lookahead in one side and an end-of-input on the other side.
  4454. // We need two registers for the lookahead.
  4455. int stack_pointer_register = compiler->AllocateRegister();
  4456. int position_register = compiler->AllocateRegister();
  4457. // The ChoiceNode to distinguish between a newline and end-of-input.
  4458. ChoiceNode* result = new(zone) ChoiceNode(2, zone);
  4459. // Create a newline atom.
  4460. ZoneList<CharacterRange>* newline_ranges =
  4461. new(zone) ZoneList<CharacterRange>(3, zone);
  4462. CharacterRange::AddClassEscape('n', newline_ranges, zone);
  4463. RegExpCharacterClass* newline_atom = new(zone) RegExpCharacterClass('n');
  4464. TextNode* newline_matcher = new(zone) TextNode(
  4465. newline_atom,
  4466. ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
  4467. position_register,
  4468. 0, // No captures inside.
  4469. -1, // Ignored if no captures.
  4470. on_success));
  4471. // Create an end-of-input matcher.
  4472. RegExpNode* end_of_line = ActionNode::BeginSubmatch(
  4473. stack_pointer_register,
  4474. position_register,
  4475. newline_matcher);
  4476. // Add the two alternatives to the ChoiceNode.
  4477. GuardedAlternative eol_alternative(end_of_line);
  4478. result->AddAlternative(eol_alternative);
  4479. GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
  4480. result->AddAlternative(end_alternative);
  4481. return result;
  4482. }
  4483. default:
  4484. UNREACHABLE();
  4485. }
  4486. return on_success;
  4487. }
  4488. RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
  4489. RegExpNode* on_success) {
  4490. return new(compiler->zone())
  4491. BackReferenceNode(RegExpCapture::StartRegister(index()),
  4492. RegExpCapture::EndRegister(index()),
  4493. on_success);
  4494. }
  4495. RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
  4496. RegExpNode* on_success) {
  4497. return on_success;
  4498. }
  4499. RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler,
  4500. RegExpNode* on_success) {
  4501. int stack_pointer_register = compiler->AllocateRegister();
  4502. int position_register = compiler->AllocateRegister();
  4503. const int registers_per_capture = 2;
  4504. const int register_of_first_capture = 2;
  4505. int register_count = capture_count_ * registers_per_capture;
  4506. int register_start =
  4507. register_of_first_capture + capture_from_ * registers_per_capture;
  4508. RegExpNode* success;
  4509. if (is_positive()) {
  4510. RegExpNode* node = ActionNode::BeginSubmatch(
  4511. stack_pointer_register,
  4512. position_register,
  4513. body()->ToNode(
  4514. compiler,
  4515. ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
  4516. position_register,
  4517. register_count,
  4518. register_start,
  4519. on_success)));
  4520. return node;
  4521. } else {
  4522. // We use a ChoiceNode for a negative lookahead because it has most of
  4523. // the characteristics we need. It has the body of the lookahead as its
  4524. // first alternative and the expression after the lookahead of the second
  4525. // alternative. If the first alternative succeeds then the
  4526. // NegativeSubmatchSuccess will unwind the stack including everything the
  4527. // choice node set up and backtrack. If the first alternative fails then
  4528. // the second alternative is tried, which is exactly the desired result
  4529. // for a negative lookahead. The NegativeLookaheadChoiceNode is a special
  4530. // ChoiceNode that knows to ignore the first exit when calculating quick
  4531. // checks.
  4532. Zone* zone = compiler->zone();
  4533. GuardedAlternative body_alt(
  4534. body()->ToNode(
  4535. compiler,
  4536. success = new(zone) NegativeSubmatchSuccess(stack_pointer_register,
  4537. position_register,
  4538. register_count,
  4539. register_start,
  4540. zone)));
  4541. ChoiceNode* choice_node =
  4542. new(zone) NegativeLookaheadChoiceNode(body_alt,
  4543. GuardedAlternative(on_success),
  4544. zone);
  4545. return ActionNode::BeginSubmatch(stack_pointer_register,
  4546. position_register,
  4547. choice_node);
  4548. }
  4549. }
  4550. RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
  4551. RegExpNode* on_success) {
  4552. return ToNode(body(), index(), compiler, on_success);
  4553. }
  4554. RegExpNode* RegExpCapture::ToNode(RegExpTree* body,
  4555. int index,
  4556. RegExpCompiler* compiler,
  4557. RegExpNode* on_success) {
  4558. int start_reg = RegExpCapture::StartRegister(index);
  4559. int end_reg = RegExpCapture::EndRegister(index);
  4560. RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
  4561. RegExpNode* body_node = body->ToNode(compiler, store_end);
  4562. return ActionNode::StorePosition(start_reg, true, body_node);
  4563. }
  4564. RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
  4565. RegExpNode* on_success) {
  4566. ZoneList<RegExpTree*>* children = nodes();
  4567. RegExpNode* current = on_success;
  4568. for (int i = children->length() - 1; i >= 0; i--) {
  4569. current = children->at(i)->ToNode(compiler, current);
  4570. }
  4571. return current;
  4572. }
  4573. static void AddClass(const int* elmv,
  4574. int elmc,
  4575. ZoneList<CharacterRange>* ranges,
  4576. Zone* zone) {
  4577. elmc--;
  4578. DCHECK(elmv[elmc] == 0x10000);
  4579. for (int i = 0; i < elmc; i += 2) {
  4580. DCHECK(elmv[i] < elmv[i + 1]);
  4581. ranges->Add(CharacterRange(elmv[i], elmv[i + 1] - 1), zone);
  4582. }
  4583. }
  4584. static void AddClassNegated(const int *elmv,
  4585. int elmc,
  4586. ZoneList<CharacterRange>* ranges,
  4587. Zone* zone) {
  4588. elmc--;
  4589. DCHECK(elmv[elmc] == 0x10000);
  4590. DCHECK(elmv[0] != 0x0000);
  4591. DCHECK(elmv[elmc-1] != String::kMaxUtf16CodeUnit);
  4592. uc16 last = 0x0000;
  4593. for (int i = 0; i < elmc; i += 2) {
  4594. DCHECK(last <= elmv[i] - 1);
  4595. DCHECK(elmv[i] < elmv[i + 1]);
  4596. ranges->Add(CharacterRange(last, elmv[i] - 1), zone);
  4597. last = elmv[i + 1];
  4598. }
  4599. ranges->Add(CharacterRange(last, String::kMaxUtf16CodeUnit), zone);
  4600. }
  4601. void CharacterRange::AddClassEscape(uc16 type,
  4602. ZoneList<CharacterRange>* ranges,
  4603. Zone* zone) {
  4604. switch (type) {
  4605. case 's':
  4606. AddClass(kSpaceRanges, kSpaceRangeCount, ranges, zone);
  4607. break;
  4608. case 'S':
  4609. AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges, zone);
  4610. break;
  4611. case 'w':
  4612. AddClass(kWordRanges, kWordRangeCount, ranges, zone);
  4613. break;
  4614. case 'W':
  4615. AddClassNegated(kWordRanges, kWordRangeCount, ranges, zone);
  4616. break;
  4617. case 'd':
  4618. AddClass(kDigitRanges, kDigitRangeCount, ranges, zone);
  4619. break;
  4620. case 'D':
  4621. AddClassNegated(kDigitRanges, kDigitRangeCount, ranges, zone);
  4622. break;
  4623. case '.':
  4624. AddClassNegated(kLineTerminatorRanges,
  4625. kLineTerminatorRangeCount,
  4626. ranges,
  4627. zone);
  4628. break;
  4629. // This is not a character range as defined by the spec but a
  4630. // convenient shorthand for a character class that matches any
  4631. // character.
  4632. case '*':
  4633. ranges->Add(CharacterRange::Everything(), zone);
  4634. break;
  4635. // This is the set of characters matched by the $ and ^ symbols
  4636. // in multiline mode.
  4637. case 'n':
  4638. AddClass(kLineTerminatorRanges,
  4639. kLineTerminatorRangeCount,
  4640. ranges,
  4641. zone);
  4642. break;
  4643. default:
  4644. UNREACHABLE();
  4645. }
  4646. }
  4647. Vector<const int> CharacterRange::GetWordBounds() {
  4648. return Vector<const int>(kWordRanges, kWordRangeCount - 1);
  4649. }
  4650. class CharacterRangeSplitter {
  4651. public:
  4652. CharacterRangeSplitter(ZoneList<CharacterRange>** included,
  4653. ZoneList<CharacterRange>** excluded,
  4654. Zone* zone)
  4655. : included_(included),
  4656. excluded_(excluded),
  4657. zone_(zone) { }
  4658. void Call(uc16 from, DispatchTable::Entry entry);
  4659. static const int kInBase = 0;
  4660. static const int kInOverlay = 1;
  4661. private:
  4662. ZoneList<CharacterRange>** included_;
  4663. ZoneList<CharacterRange>** excluded_;
  4664. Zone* zone_;
  4665. };
  4666. void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) {
  4667. if (!entry.out_set()->Get(kInBase)) return;
  4668. ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay)
  4669. ? included_
  4670. : excluded_;
  4671. if (*target == NULL) *target = new(zone_) ZoneList<CharacterRange>(2, zone_);
  4672. (*target)->Add(CharacterRange(entry.from(), entry.to()), zone_);
  4673. }
  4674. void CharacterRange::Split(ZoneList<CharacterRange>* base,
  4675. Vector<const int> overlay,
  4676. ZoneList<CharacterRange>** included,
  4677. ZoneList<CharacterRange>** excluded,
  4678. Zone* zone) {
  4679. DCHECK_EQ(NULL, *included);
  4680. DCHECK_EQ(NULL, *excluded);
  4681. DispatchTable table(zone);
  4682. for (int i = 0; i < base->length(); i++)
  4683. table.AddRange(base->at(i), CharacterRangeSplitter::kInBase, zone);
  4684. for (int i = 0; i < overlay.length(); i += 2) {
  4685. table.AddRange(CharacterRange(overlay[i], overlay[i + 1] - 1),
  4686. CharacterRangeSplitter::kInOverlay, zone);
  4687. }
  4688. CharacterRangeSplitter callback(included, excluded, zone);
  4689. table.ForEach(&callback);
  4690. }
  4691. void CharacterRange::AddCaseEquivalents(ZoneList<CharacterRange>* ranges,
  4692. bool is_ascii,
  4693. Zone* zone) {
  4694. Isolate* isolate = zone->isolate();
  4695. uc16 bottom = from();
  4696. uc16 top = to();
  4697. if (is_ascii && !RangeContainsLatin1Equivalents(*this)) {
  4698. if (bottom > String::kMaxOneByteCharCode) return;
  4699. if (top > String::kMaxOneByteCharCode) top = String::kMaxOneByteCharCode;
  4700. }
  4701. unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
  4702. if (top == bottom) {
  4703. // If this is a singleton we just expand the one character.
  4704. int length = isolate->jsregexp_uncanonicalize()->get(bottom, '\0', chars);
  4705. for (int i = 0; i < length; i++) {
  4706. uc32 chr = chars[i];
  4707. if (chr != bottom) {
  4708. ranges->Add(CharacterRange::Singleton(chars[i]), zone);
  4709. }
  4710. }
  4711. } else {
  4712. // If this is a range we expand the characters block by block,
  4713. // expanding contiguous subranges (blocks) one at a time.
  4714. // The approach is as follows. For a given start character we
  4715. // look up the remainder of the block that contains it (represented
  4716. // by the end point), for instance we find 'z' if the character
  4717. // is 'c'. A block is characterized by the property
  4718. // that all characters uncanonicalize in the same way, except that
  4719. // each entry in the result is incremented by the distance from the first
  4720. // element. So a-z is a block because 'a' uncanonicalizes to ['a', 'A'] and
  4721. // the k'th letter uncanonicalizes to ['a' + k, 'A' + k].
  4722. // Once we've found the end point we look up its uncanonicalization
  4723. // and produce a range for each element. For instance for [c-f]
  4724. // we look up ['z', 'Z'] and produce [c-f] and [C-F]. We then only
  4725. // add a range if it is not already contained in the input, so [c-f]
  4726. // will be skipped but [C-F] will be added. If this range is not
  4727. // completely contained in a block we do this for all the blocks
  4728. // covered by the range (handling characters that is not in a block
  4729. // as a "singleton block").
  4730. unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth];
  4731. int pos = bottom;
  4732. while (pos <= top) {
  4733. int length = isolate->jsregexp_canonrange()->get(pos, '\0', range);
  4734. uc16 block_end;
  4735. if (length == 0) {
  4736. block_end = pos;
  4737. } else {
  4738. DCHECK_EQ(1, length);
  4739. block_end = range[0];
  4740. }
  4741. int end = (block_end > top) ? top : block_end;
  4742. length = isolate->jsregexp_uncanonicalize()->get(block_end, '\0', range);
  4743. for (int i = 0; i < length; i++) {
  4744. uc32 c = range[i];
  4745. uc16 range_from = c - (block_end - pos);
  4746. uc16 range_to = c - (block_end - end);
  4747. if (!(bottom <= range_from && range_to <= top)) {
  4748. ranges->Add(CharacterRange(range_from, range_to), zone);
  4749. }
  4750. }
  4751. pos = end + 1;
  4752. }
  4753. }
  4754. }
  4755. bool CharacterRange::IsCanonical(ZoneList<CharacterRange>* ranges) {
  4756. DCHECK_NOT_NULL(ranges);
  4757. int n = ranges->length();
  4758. if (n <= 1) return true;
  4759. int max = ranges->at(0).to();
  4760. for (int i = 1; i < n; i++) {
  4761. CharacterRange next_range = ranges->at(i);
  4762. if (next_range.from() <= max + 1) return false;
  4763. max = next_range.to();
  4764. }
  4765. return true;
  4766. }
  4767. ZoneList<CharacterRange>* CharacterSet::ranges(Zone* zone) {
  4768. if (ranges_ == NULL) {
  4769. ranges_ = new(zone) ZoneList<CharacterRange>(2, zone);
  4770. CharacterRange::AddClassEscape(standard_set_type_, ranges_, zone);
  4771. }
  4772. return ranges_;
  4773. }
  4774. // Move a number of elements in a zonelist to another position
  4775. // in the same list. Handles overlapping source and target areas.
  4776. static void MoveRanges(ZoneList<CharacterRange>* list,
  4777. int from,
  4778. int to,
  4779. int count) {
  4780. // Ranges are potentially overlapping.
  4781. if (from < to) {
  4782. for (int i = count - 1; i >= 0; i--) {
  4783. list->at(to + i) = list->at(from + i);
  4784. }
  4785. } else {
  4786. for (int i = 0; i < count; i++) {
  4787. list->at(to + i) = list->at(from + i);
  4788. }
  4789. }
  4790. }
  4791. static int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list,
  4792. int count,
  4793. CharacterRange insert) {
  4794. // Inserts a range into list[0..count[, which must be sorted
  4795. // by from value and non-overlapping and non-adjacent, using at most
  4796. // list[0..count] for the result. Returns the number of resulting
  4797. // canonicalized ranges. Inserting a range may collapse existing ranges into
  4798. // fewer ranges, so the return value can be anything in the range 1..count+1.
  4799. uc16 from = insert.from();
  4800. uc16 to = insert.to();
  4801. int start_pos = 0;
  4802. int end_pos = count;
  4803. for (int i = count - 1; i >= 0; i--) {
  4804. CharacterRange current = list->at(i);
  4805. if (current.from() > to + 1) {
  4806. end_pos = i;
  4807. } else if (current.to() + 1 < from) {
  4808. start_pos = i + 1;
  4809. break;
  4810. }
  4811. }
  4812. // Inserted range overlaps, or is adjacent to, ranges at positions
  4813. // [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are
  4814. // not affected by the insertion.
  4815. // If start_pos == end_pos, the range must be inserted before start_pos.
  4816. // if start_pos < end_pos, the entire range from start_pos to end_pos
  4817. // must be merged with the insert range.
  4818. if (start_pos == end_pos) {
  4819. // Insert between existing ranges at position start_pos.
  4820. if (start_pos < count) {
  4821. MoveRanges(list, start_pos, start_pos + 1, count - start_pos);
  4822. }
  4823. list->at(start_pos) = insert;
  4824. return count + 1;
  4825. }
  4826. if (start_pos + 1 == end_pos) {
  4827. // Replace single existing range at position start_pos.
  4828. CharacterRange to_replace = list->at(start_pos);
  4829. int new_from = Min(to_replace.from(), from);
  4830. int new_to = Max(to_replace.to(), to);
  4831. list->at(start_pos) = CharacterRange(new_from, new_to);
  4832. return count;
  4833. }
  4834. // Replace a number of existing ranges from start_pos to end_pos - 1.
  4835. // Move the remaining ranges down.
  4836. int new_from = Min(list->at(start_pos).from(), from);
  4837. int new_to = Max(list->at(end_pos - 1).to(), to);
  4838. if (end_pos < count) {
  4839. MoveRanges(list, end_pos, start_pos + 1, count - end_pos);
  4840. }
  4841. list->at(start_pos) = CharacterRange(new_from, new_to);
  4842. return count - (end_pos - start_pos) + 1;
  4843. }
  4844. void CharacterSet::Canonicalize() {
  4845. // Special/default classes are always considered canonical. The result
  4846. // of calling ranges() will be sorted.
  4847. if (ranges_ == NULL) return;
  4848. CharacterRange::Canonicalize(ranges_);
  4849. }
  4850. void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) {
  4851. if (character_ranges->length() <= 1) return;
  4852. // Check whether ranges are already canonical (increasing, non-overlapping,
  4853. // non-adjacent).
  4854. int n = character_ranges->length();
  4855. int max = character_ranges->at(0).to();
  4856. int i = 1;
  4857. while (i < n) {
  4858. CharacterRange current = character_ranges->at(i);
  4859. if (current.from() <= max + 1) {
  4860. break;
  4861. }
  4862. max = current.to();
  4863. i++;
  4864. }
  4865. // Canonical until the i'th range. If that's all of them, we are done.
  4866. if (i == n) return;
  4867. // The ranges at index i and forward are not canonicalized. Make them so by
  4868. // doing the equivalent of insertion sort (inserting each into the previous
  4869. // list, in order).
  4870. // Notice that inserting a range can reduce the number of ranges in the
  4871. // result due to combining of adjacent and overlapping ranges.
  4872. int read = i; // Range to insert.
  4873. int num_canonical = i; // Length of canonicalized part of list.
  4874. do {
  4875. num_canonical = InsertRangeInCanonicalList(character_ranges,
  4876. num_canonical,
  4877. character_ranges->at(read));
  4878. read++;
  4879. } while (read < n);
  4880. character_ranges->Rewind(num_canonical);
  4881. DCHECK(CharacterRange::IsCanonical(character_ranges));
  4882. }
  4883. void CharacterRange::Negate(ZoneList<CharacterRange>* ranges,
  4884. ZoneList<CharacterRange>* negated_ranges,
  4885. Zone* zone) {
  4886. DCHECK(CharacterRange::IsCanonical(ranges));
  4887. DCHECK_EQ(0, negated_ranges->length());
  4888. int range_count = ranges->length();
  4889. uc16 from = 0;
  4890. int i = 0;
  4891. if (range_count > 0 && ranges->at(0).from() == 0) {
  4892. from = ranges->at(0).to();
  4893. i = 1;
  4894. }
  4895. while (i < range_count) {
  4896. CharacterRange range = ranges->at(i);
  4897. negated_ranges->Add(CharacterRange(from + 1, range.from() - 1), zone);
  4898. from = range.to();
  4899. i++;
  4900. }
  4901. if (from < String::kMaxUtf16CodeUnit) {
  4902. negated_ranges->Add(CharacterRange(from + 1, String::kMaxUtf16CodeUnit),
  4903. zone);
  4904. }
  4905. }
  4906. // -------------------------------------------------------------------
  4907. // Splay tree
  4908. OutSet* OutSet::Extend(unsigned value, Zone* zone) {
  4909. if (Get(value))
  4910. return this;
  4911. if (successors(zone) != NULL) {
  4912. for (int i = 0; i < successors(zone)->length(); i++) {
  4913. OutSet* successor = successors(zone)->at(i);
  4914. if (successor->Get(value))
  4915. return successor;
  4916. }
  4917. } else {
  4918. successors_ = new(zone) ZoneList<OutSet*>(2, zone);
  4919. }
  4920. OutSet* result = new(zone) OutSet(first_, remaining_);
  4921. result->Set(value, zone);
  4922. successors(zone)->Add(result, zone);
  4923. return result;
  4924. }
  4925. void OutSet::Set(unsigned value, Zone *zone) {
  4926. if (value < kFirstLimit) {
  4927. first_ |= (1 << value);
  4928. } else {
  4929. if (remaining_ == NULL)
  4930. remaining_ = new(zone) ZoneList<unsigned>(1, zone);
  4931. if (remaining_->is_empty() || !remaining_->Contains(value))
  4932. remaining_->Add(value, zone);
  4933. }
  4934. }
  4935. bool OutSet::Get(unsigned value) const {
  4936. if (value < kFirstLimit) {
  4937. return (first_ & (1 << value)) != 0;
  4938. } else if (remaining_ == NULL) {
  4939. return false;
  4940. } else {
  4941. return remaining_->Contains(value);
  4942. }
  4943. }
  4944. const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
  4945. void DispatchTable::AddRange(CharacterRange full_range, int value,
  4946. Zone* zone) {
  4947. CharacterRange current = full_range;
  4948. if (tree()->is_empty()) {
  4949. // If this is the first range we just insert into the table.
  4950. ZoneSplayTree<Config>::Locator loc;
  4951. DCHECK_RESULT(tree()->Insert(current.from(), &loc));
  4952. loc.set_value(Entry(current.from(), current.to(),
  4953. empty()->Extend(value, zone)));
  4954. return;
  4955. }
  4956. // First see if there is a range to the left of this one that
  4957. // overlaps.
  4958. ZoneSplayTree<Config>::Locator loc;
  4959. if (tree()->FindGreatestLessThan(current.from(), &loc)) {
  4960. Entry* entry = &loc.value();
  4961. // If we've found a range that overlaps with this one, and it
  4962. // starts strictly to the left of this one, we have to fix it
  4963. // because the following code only handles ranges that start on
  4964. // or after the start point of the range we're adding.
  4965. if (entry->from() < current.from() && entry->to() >= current.from()) {
  4966. // Snap the overlapping range in half around the start point of
  4967. // the range we're adding.
  4968. CharacterRange left(entry->from(), current.from() - 1);
  4969. CharacterRange right(current.from(), entry->to());
  4970. // The left part of the overlapping range doesn't overlap.
  4971. // Truncate the whole entry to be just the left part.
  4972. entry->set_to(left.to());
  4973. // The right part is the one that overlaps. We add this part
  4974. // to the map and let the next step deal with merging it with
  4975. // the range we're adding.
  4976. ZoneSplayTree<Config>::Locator loc;
  4977. DCHECK_RESULT(tree()->Insert(right.from(), &loc));
  4978. loc.set_value(Entry(right.from(),
  4979. right.to(),
  4980. entry->out_set()));
  4981. }
  4982. }
  4983. while (current.is_valid()) {
  4984. if (tree()->FindLeastGreaterThan(current.from(), &loc) &&
  4985. (loc.value().from() <= current.to()) &&
  4986. (loc.value().to() >= current.from())) {
  4987. Entry* entry = &loc.value();
  4988. // We have overlap. If there is space between the start point of
  4989. // the range we're adding and where the overlapping range starts
  4990. // then we have to add a range covering just that space.
  4991. if (current.from() < entry->from()) {
  4992. ZoneSplayTree<Config>::Locator ins;
  4993. DCHECK_RESULT(tree()->Insert(current.from(), &ins));
  4994. ins.set_value(Entry(current.from(),
  4995. entry->from() - 1,
  4996. empty()->Extend(value, zone)));
  4997. current.set_from(entry->from());
  4998. }
  4999. DCHECK_EQ(current.from(), entry->from());
  5000. // If the overlapping range extends beyond the one we want to add
  5001. // we have to snap the right part off and add it separately.
  5002. if (entry->to() > current.to()) {
  5003. ZoneSplayTree<Config>::Locator ins;
  5004. DCHECK_RESULT(tree()->Insert(current.to() + 1, &ins));
  5005. ins.set_value(Entry(current.to() + 1,
  5006. entry->to(),
  5007. entry->out_set()));
  5008. entry->set_to(current.to());
  5009. }
  5010. DCHECK(entry->to() <= current.to());
  5011. // The overlapping range is now completely contained by the range
  5012. // we're adding so we can just update it and move the start point
  5013. // of the range we're adding just past it.
  5014. entry->AddValue(value, zone);
  5015. // Bail out if the last interval ended at 0xFFFF since otherwise
  5016. // adding 1 will wrap around to 0.
  5017. if (entry->to() == String::kMaxUtf16CodeUnit)
  5018. break;
  5019. DCHECK(entry->to() + 1 > current.from());
  5020. current.set_from(entry->to() + 1);
  5021. } else {
  5022. // There is no overlap so we can just add the range
  5023. ZoneSplayTree<Config>::Locator ins;
  5024. DCHECK_RESULT(tree()->Insert(current.from(), &ins));
  5025. ins.set_value(Entry(current.from(),
  5026. current.to(),
  5027. empty()->Extend(value, zone)));
  5028. break;
  5029. }
  5030. }
  5031. }
  5032. OutSet* DispatchTable::Get(uc16 value) {
  5033. ZoneSplayTree<Config>::Locator loc;
  5034. if (!tree()->FindGreatestLessThan(value, &loc))
  5035. return empty();
  5036. Entry* entry = &loc.value();
  5037. if (value <= entry->to())
  5038. return entry->out_set();
  5039. else
  5040. return empty();
  5041. }
  5042. // -------------------------------------------------------------------
  5043. // Analysis
  5044. void Analysis::EnsureAnalyzed(RegExpNode* that) {
  5045. StackLimitCheck check(that->zone()->isolate());
  5046. if (check.HasOverflowed()) {
  5047. fail("Stack overflow");
  5048. return;
  5049. }
  5050. if (that->info()->been_analyzed || that->info()->being_analyzed)
  5051. return;
  5052. that->info()->being_analyzed = true;
  5053. that->Accept(this);
  5054. that->info()->being_analyzed = false;
  5055. that->info()->been_analyzed = true;
  5056. }
  5057. void Analysis::VisitEnd(EndNode* that) {
  5058. // nothing to do
  5059. }
  5060. void TextNode::CalculateOffsets() {
  5061. int element_count = elements()->length();
  5062. // Set up the offsets of the elements relative to the start. This is a fixed
  5063. // quantity since a TextNode can only contain fixed-width things.
  5064. int cp_offset = 0;
  5065. for (int i = 0; i < element_count; i++) {
  5066. TextElement& elm = elements()->at(i);
  5067. elm.set_cp_offset(cp_offset);
  5068. cp_offset += elm.length();
  5069. }
  5070. }
  5071. void Analysis::VisitText(TextNode* that) {
  5072. if (ignore_case_) {
  5073. that->MakeCaseIndependent(is_ascii_);
  5074. }
  5075. EnsureAnalyzed(that->on_success());
  5076. if (!has_failed()) {
  5077. that->CalculateOffsets();
  5078. }
  5079. }
  5080. void Analysis::VisitAction(ActionNode* that) {
  5081. RegExpNode* target = that->on_success();
  5082. EnsureAnalyzed(target);
  5083. if (!has_failed()) {
  5084. // If the next node is interested in what it follows then this node
  5085. // has to be interested too so it can pass the information on.
  5086. that->info()->AddFromFollowing(target->info());
  5087. }
  5088. }
  5089. void Analysis::VisitChoice(ChoiceNode* that) {
  5090. NodeInfo* info = that->info();
  5091. for (int i = 0; i < that->alternatives()->length(); i++) {
  5092. RegExpNode* node = that->alternatives()->at(i).node();
  5093. EnsureAnalyzed(node);
  5094. if (has_failed()) return;
  5095. // Anything the following nodes need to know has to be known by
  5096. // this node also, so it can pass it on.
  5097. info->AddFromFollowing(node->info());
  5098. }
  5099. }
  5100. void Analysis::VisitLoopChoice(LoopChoiceNode* that) {
  5101. NodeInfo* info = that->info();
  5102. for (int i = 0; i < that->alternatives()->length(); i++) {
  5103. RegExpNode* node = that->alternatives()->at(i).node();
  5104. if (node != that->loop_node()) {
  5105. EnsureAnalyzed(node);
  5106. if (has_failed()) return;
  5107. info->AddFromFollowing(node->info());
  5108. }
  5109. }
  5110. // Check the loop last since it may need the value of this node
  5111. // to get a correct result.
  5112. EnsureAnalyzed(that->loop_node());
  5113. if (!has_failed()) {
  5114. info->AddFromFollowing(that->loop_node()->info());
  5115. }
  5116. }
  5117. void Analysis::VisitBackReference(BackReferenceNode* that) {
  5118. EnsureAnalyzed(that->on_success());
  5119. }
  5120. void Analysis::VisitAssertion(AssertionNode* that) {
  5121. EnsureAnalyzed(that->on_success());
  5122. }
  5123. void BackReferenceNode::FillInBMInfo(int offset,
  5124. int budget,
  5125. BoyerMooreLookahead* bm,
  5126. bool not_at_start) {
  5127. // Working out the set of characters that a backreference can match is too
  5128. // hard, so we just say that any character can match.
  5129. bm->SetRest(offset);
  5130. SaveBMInfo(bm, not_at_start, offset);
  5131. }
  5132. STATIC_ASSERT(BoyerMoorePositionInfo::kMapSize ==
  5133. RegExpMacroAssembler::kTableSize);
  5134. void ChoiceNode::FillInBMInfo(int offset,
  5135. int budget,
  5136. BoyerMooreLookahead* bm,
  5137. bool not_at_start) {
  5138. ZoneList<GuardedAlternative>* alts = alternatives();
  5139. budget = (budget - 1) / alts->length();
  5140. for (int i = 0; i < alts->length(); i++) {
  5141. GuardedAlternative& alt = alts->at(i);
  5142. if (alt.guards() != NULL && alt.guards()->length() != 0) {
  5143. bm->SetRest(offset); // Give up trying to fill in info.
  5144. SaveBMInfo(bm, not_at_start, offset);
  5145. return;
  5146. }
  5147. alt.node()->FillInBMInfo(offset, budget, bm, not_at_start);
  5148. }
  5149. SaveBMInfo(bm, not_at_start, offset);
  5150. }
  5151. void TextNode::FillInBMInfo(int initial_offset,
  5152. int budget,
  5153. BoyerMooreLookahead* bm,
  5154. bool not_at_start) {
  5155. if (initial_offset >= bm->length()) return;
  5156. int offset = initial_offset;
  5157. int max_char = bm->max_char();
  5158. for (int i = 0; i < elements()->length(); i++) {
  5159. if (offset >= bm->length()) {
  5160. if (initial_offset == 0) set_bm_info(not_at_start, bm);
  5161. return;
  5162. }
  5163. TextElement text = elements()->at(i);
  5164. if (text.text_type() == TextElement::ATOM) {
  5165. RegExpAtom* atom = text.atom();
  5166. for (int j = 0; j < atom->length(); j++, offset++) {
  5167. if (offset >= bm->length()) {
  5168. if (initial_offset == 0) set_bm_info(not_at_start, bm);
  5169. return;
  5170. }
  5171. uc16 character = atom->data()[j];
  5172. if (bm->compiler()->ignore_case()) {
  5173. unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
  5174. int length = GetCaseIndependentLetters(
  5175. Isolate::Current(),
  5176. character,
  5177. bm->max_char() == String::kMaxOneByteCharCode,
  5178. chars);
  5179. for (int j = 0; j < length; j++) {
  5180. bm->Set(offset, chars[j]);
  5181. }
  5182. } else {
  5183. if (character <= max_char) bm->Set(offset, character);
  5184. }
  5185. }
  5186. } else {
  5187. DCHECK_EQ(TextElement::CHAR_CLASS, text.text_type());
  5188. RegExpCharacterClass* char_class = text.char_class();
  5189. ZoneList<CharacterRange>* ranges = char_class->ranges(zone());
  5190. if (char_class->is_negated()) {
  5191. bm->SetAll(offset);
  5192. } else {
  5193. for (int k = 0; k < ranges->length(); k++) {
  5194. CharacterRange& range = ranges->at(k);
  5195. if (range.from() > max_char) continue;
  5196. int to = Min(max_char, static_cast<int>(range.to()));
  5197. bm->SetInterval(offset, Interval(range.from(), to));
  5198. }
  5199. }
  5200. offset++;
  5201. }
  5202. }
  5203. if (offset >= bm->length()) {
  5204. if (initial_offset == 0) set_bm_info(not_at_start, bm);
  5205. return;
  5206. }
  5207. on_success()->FillInBMInfo(offset,
  5208. budget - 1,
  5209. bm,
  5210. true); // Not at start after a text node.
  5211. if (initial_offset == 0) set_bm_info(not_at_start, bm);
  5212. }
  5213. // -------------------------------------------------------------------
  5214. // Dispatch table construction
  5215. void DispatchTableConstructor::VisitEnd(EndNode* that) {
  5216. AddRange(CharacterRange::Everything());
  5217. }
  5218. void DispatchTableConstructor::BuildTable(ChoiceNode* node) {
  5219. node->set_being_calculated(true);
  5220. ZoneList<GuardedAlternative>* alternatives = node->alternatives();
  5221. for (int i = 0; i < alternatives->length(); i++) {
  5222. set_choice_index(i);
  5223. alternatives->at(i).node()->Accept(this);
  5224. }
  5225. node->set_being_calculated(false);
  5226. }
  5227. class AddDispatchRange {
  5228. public:
  5229. explicit AddDispatchRange(DispatchTableConstructor* constructor)
  5230. : constructor_(constructor) { }
  5231. void Call(uc32 from, DispatchTable::Entry entry);
  5232. private:
  5233. DispatchTableConstructor* constructor_;
  5234. };
  5235. void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
  5236. CharacterRange range(from, entry.to());
  5237. constructor_->AddRange(range);
  5238. }
  5239. void DispatchTableConstructor::VisitChoice(ChoiceNode* node) {
  5240. if (node->being_calculated())
  5241. return;
  5242. DispatchTable* table = node->GetTable(ignore_case_);
  5243. AddDispatchRange adder(this);
  5244. table->ForEach(&adder);
  5245. }
  5246. void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) {
  5247. // TODO(160): Find the node that we refer back to and propagate its start
  5248. // set back to here. For now we just accept anything.
  5249. AddRange(CharacterRange::Everything());
  5250. }
  5251. void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
  5252. RegExpNode* target = that->on_success();
  5253. target->Accept(this);
  5254. }
  5255. static int CompareRangeByFrom(const CharacterRange* a,
  5256. const CharacterRange* b) {
  5257. return Compare<uc16>(a->from(), b->from());
  5258. }
  5259. void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) {
  5260. ranges->Sort(CompareRangeByFrom);
  5261. uc16 last = 0;
  5262. for (int i = 0; i < ranges->length(); i++) {
  5263. CharacterRange range = ranges->at(i);
  5264. if (last < range.from())
  5265. AddRange(CharacterRange(last, range.from() - 1));
  5266. if (range.to() >= last) {
  5267. if (range.to() == String::kMaxUtf16CodeUnit) {
  5268. return;
  5269. } else {
  5270. last = range.to() + 1;
  5271. }
  5272. }
  5273. }
  5274. AddRange(CharacterRange(last, String::kMaxUtf16CodeUnit));
  5275. }
  5276. void DispatchTableConstructor::VisitText(TextNode* that) {
  5277. TextElement elm = that->elements()->at(0);
  5278. switch (elm.text_type()) {
  5279. case TextElement::ATOM: {
  5280. uc16 c = elm.atom()->data()[0];
  5281. AddRange(CharacterRange(c, c));
  5282. break;
  5283. }
  5284. case TextElement::CHAR_CLASS: {
  5285. RegExpCharacterClass* tree = elm.char_class();
  5286. ZoneList<CharacterRange>* ranges = tree->ranges(that->zone());
  5287. if (tree->is_negated()) {
  5288. AddInverse(ranges);
  5289. } else {
  5290. for (int i = 0; i < ranges->length(); i++)
  5291. AddRange(ranges->at(i));
  5292. }
  5293. break;
  5294. }
  5295. default: {
  5296. UNIMPLEMENTED();
  5297. }
  5298. }
  5299. }
  5300. void DispatchTableConstructor::VisitAction(ActionNode* that) {
  5301. RegExpNode* target = that->on_success();
  5302. target->Accept(this);
  5303. }
  5304. RegExpEngine::CompilationResult RegExpEngine::Compile(
  5305. RegExpCompileData* data,
  5306. bool ignore_case,
  5307. bool is_global,
  5308. bool is_multiline,
  5309. Handle<String> pattern,
  5310. Handle<String> sample_subject,
  5311. bool is_ascii,
  5312. Zone* zone) {
  5313. if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) {
  5314. return IrregexpRegExpTooBig(zone->isolate());
  5315. }
  5316. RegExpCompiler compiler(data->capture_count, ignore_case, is_ascii, zone);
  5317. // Sample some characters from the middle of the string.
  5318. static const int kSampleSize = 128;
  5319. sample_subject = String::Flatten(sample_subject);
  5320. int chars_sampled = 0;
  5321. int half_way = (sample_subject->length() - kSampleSize) / 2;
  5322. for (int i = Max(0, half_way);
  5323. i < sample_subject->length() && chars_sampled < kSampleSize;
  5324. i++, chars_sampled++) {
  5325. compiler.frequency_collator()->CountCharacter(sample_subject->Get(i));
  5326. }
  5327. // Wrap the body of the regexp in capture #0.
  5328. RegExpNode* captured_body = RegExpCapture::ToNode(data->tree,
  5329. 0,
  5330. &compiler,
  5331. compiler.accept());
  5332. RegExpNode* node = captured_body;
  5333. bool is_end_anchored = data->tree->IsAnchoredAtEnd();
  5334. bool is_start_anchored = data->tree->IsAnchoredAtStart();
  5335. int max_length = data->tree->max_match();
  5336. if (!is_start_anchored) {
  5337. // Add a .*? at the beginning, outside the body capture, unless
  5338. // this expression is anchored at the beginning.
  5339. RegExpNode* loop_node =
  5340. RegExpQuantifier::ToNode(0,
  5341. RegExpTree::kInfinity,
  5342. false,
  5343. new(zone) RegExpCharacterClass('*'),
  5344. &compiler,
  5345. captured_body,
  5346. data->contains_anchor);
  5347. if (data->contains_anchor) {
  5348. // Unroll loop once, to take care of the case that might start
  5349. // at the start of input.
  5350. ChoiceNode* first_step_node = new(zone) ChoiceNode(2, zone);
  5351. first_step_node->AddAlternative(GuardedAlternative(captured_body));
  5352. first_step_node->AddAlternative(GuardedAlternative(
  5353. new(zone) TextNode(new(zone) RegExpCharacterClass('*'), loop_node)));
  5354. node = first_step_node;
  5355. } else {
  5356. node = loop_node;
  5357. }
  5358. }
  5359. if (is_ascii) {
  5360. node = node->FilterASCII(RegExpCompiler::kMaxRecursion, ignore_case);
  5361. // Do it again to propagate the new nodes to places where they were not
  5362. // put because they had not been calculated yet.
  5363. if (node != NULL) {
  5364. node = node->FilterASCII(RegExpCompiler::kMaxRecursion, ignore_case);
  5365. }
  5366. }
  5367. if (node == NULL) node = new(zone) EndNode(EndNode::BACKTRACK, zone);
  5368. data->node = node;
  5369. Analysis analysis(ignore_case, is_ascii);
  5370. analysis.EnsureAnalyzed(node);
  5371. if (analysis.has_failed()) {
  5372. const char* error_message = analysis.error_message();
  5373. return CompilationResult(zone->isolate(), error_message);
  5374. }
  5375. // Create the correct assembler for the architecture.
  5376. #ifndef V8_INTERPRETED_REGEXP
  5377. // Native regexp implementation.
  5378. NativeRegExpMacroAssembler::Mode mode =
  5379. is_ascii ? NativeRegExpMacroAssembler::ASCII
  5380. : NativeRegExpMacroAssembler::UC16;
  5381. #if V8_TARGET_ARCH_IA32
  5382. RegExpMacroAssemblerIA32 macro_assembler(mode, (data->capture_count + 1) * 2,
  5383. zone);
  5384. #elif V8_TARGET_ARCH_X64
  5385. RegExpMacroAssemblerX64 macro_assembler(mode, (data->capture_count + 1) * 2,
  5386. zone);
  5387. #elif V8_TARGET_ARCH_ARM
  5388. RegExpMacroAssemblerARM macro_assembler(mode, (data->capture_count + 1) * 2,
  5389. zone);
  5390. #elif V8_TARGET_ARCH_ARM64
  5391. RegExpMacroAssemblerARM64 macro_assembler(mode, (data->capture_count + 1) * 2,
  5392. zone);
  5393. #elif V8_TARGET_ARCH_MIPS
  5394. RegExpMacroAssemblerMIPS macro_assembler(mode, (data->capture_count + 1) * 2,
  5395. zone);
  5396. #elif V8_TARGET_ARCH_MIPS64
  5397. RegExpMacroAssemblerMIPS macro_assembler(mode, (data->capture_count + 1) * 2,
  5398. zone);
  5399. #elif V8_TARGET_ARCH_X87
  5400. RegExpMacroAssemblerX87 macro_assembler(mode, (data->capture_count + 1) * 2,
  5401. zone);
  5402. #else
  5403. #error "Unsupported architecture"
  5404. #endif
  5405. #else // V8_INTERPRETED_REGEXP
  5406. // Interpreted regexp implementation.
  5407. EmbeddedVector<byte, 1024> codes;
  5408. RegExpMacroAssemblerIrregexp macro_assembler(codes, zone);
  5409. #endif // V8_INTERPRETED_REGEXP
  5410. // Inserted here, instead of in Assembler, because it depends on information
  5411. // in the AST that isn't replicated in the Node structure.
  5412. static const int kMaxBacksearchLimit = 1024;
  5413. if (is_end_anchored &&
  5414. !is_start_anchored &&
  5415. max_length < kMaxBacksearchLimit) {
  5416. macro_assembler.SetCurrentPositionFromEnd(max_length);
  5417. }
  5418. if (is_global) {
  5419. macro_assembler.set_global_mode(
  5420. (data->tree->min_match() > 0)
  5421. ? RegExpMacroAssembler::GLOBAL_NO_ZERO_LENGTH_CHECK
  5422. : RegExpMacroAssembler::GLOBAL);
  5423. }
  5424. return compiler.Assemble(&macro_assembler,
  5425. node,
  5426. data->capture_count,
  5427. pattern);
  5428. }
  5429. }} // namespace v8::internal