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.
8 #include "src/base/platform/platform.h"
9 #include "src/compilation-cache.h"
10 #include "src/compiler.h"
11 #include "src/execution.h"
12 #include "src/factory.h"
13 #include "src/jsregexp-inl.h"
14 #include "src/jsregexp.h"
15 #include "src/ostreams.h"
16 #include "src/parser.h"
17 #include "src/regexp-macro-assembler.h"
18 #include "src/regexp-macro-assembler-irregexp.h"
19 #include "src/regexp-macro-assembler-tracer.h"
20 #include "src/regexp-stack.h"
21 #include "src/runtime/runtime.h"
22 #include "src/string-search.h"
23 #include "src/unicode-decoder.h"
25 #ifndef V8_INTERPRETED_REGEXP
26 #if V8_TARGET_ARCH_IA32
27 #include "src/ia32/regexp-macro-assembler-ia32.h" // NOLINT
28 #elif V8_TARGET_ARCH_X64
29 #include "src/x64/regexp-macro-assembler-x64.h" // NOLINT
30 #elif V8_TARGET_ARCH_ARM64
31 #include "src/arm64/regexp-macro-assembler-arm64.h" // NOLINT
32 #elif V8_TARGET_ARCH_ARM
33 #include "src/arm/regexp-macro-assembler-arm.h" // NOLINT
34 #elif V8_TARGET_ARCH_MIPS
35 #include "src/mips/regexp-macro-assembler-mips.h" // NOLINT
36 #elif V8_TARGET_ARCH_MIPS64
37 #include "src/mips64/regexp-macro-assembler-mips64.h" // NOLINT
38 #elif V8_TARGET_ARCH_X87
39 #include "src/x87/regexp-macro-assembler-x87.h" // NOLINT
41 #error Unsupported target architecture.
45 #include "src/interpreter-irregexp.h"
51 MaybeHandle<Object> RegExpImpl::CreateRegExpLiteral(
52 Handle<JSFunction> constructor,
53 Handle<String> pattern,
54 Handle<String> flags) {
55 // Call the construct code with 2 arguments.
56 Handle<Object> argv[] = { pattern, flags };
57 return Execution::New(constructor, arraysize(argv), argv);
61 static JSRegExp::Flags RegExpFlagsFromString(Handle<String> str) {
62 int flags = JSRegExp::NONE;
63 for (int i = 0; i < str->length(); i++) {
64 switch (str->Get(i)) {
66 flags |= JSRegExp::IGNORE_CASE;
69 flags |= JSRegExp::GLOBAL;
72 flags |= JSRegExp::MULTILINE;
75 if (FLAG_harmony_regexps) flags |= JSRegExp::STICKY;
79 return JSRegExp::Flags(flags);
84 static inline MaybeHandle<Object> ThrowRegExpException(
86 Handle<String> pattern,
87 Handle<String> error_text,
88 const char* message) {
89 Isolate* isolate = re->GetIsolate();
90 Factory* factory = isolate->factory();
91 Handle<FixedArray> elements = factory->NewFixedArray(2);
92 elements->set(0, *pattern);
93 elements->set(1, *error_text);
94 Handle<JSArray> array = factory->NewJSArrayWithElements(elements);
95 Handle<Object> regexp_err;
96 THROW_NEW_ERROR(isolate, NewSyntaxError(message, array), Object);
100 ContainedInLattice AddRange(ContainedInLattice containment,
103 Interval new_range) {
104 DCHECK((ranges_length & 1) == 1);
105 DCHECK(ranges[ranges_length - 1] == String::kMaxUtf16CodeUnit + 1);
106 if (containment == kLatticeUnknown) return containment;
109 for (int i = 0; i < ranges_length; inside = !inside, last = ranges[i], i++) {
110 // Consider the range from last to ranges[i].
111 // We haven't got to the new range yet.
112 if (ranges[i] <= new_range.from()) continue;
113 // New range is wholly inside last-ranges[i]. Note that new_range.to() is
114 // inclusive, but the values in ranges are not.
115 if (last <= new_range.from() && new_range.to() < ranges[i]) {
116 return Combine(containment, inside ? kLatticeIn : kLatticeOut);
118 return kLatticeUnknown;
124 // More makes code generation slower, less makes V8 benchmark score lower.
125 const int kMaxLookaheadForBoyerMoore = 8;
126 // In a 3-character pattern you can maximally step forwards 3 characters
127 // at a time, which is not always enough to pay for the extra logic.
128 const int kPatternTooShortForBoyerMoore = 2;
131 // Identifies the sort of regexps where the regexp engine is faster
132 // than the code used for atom matches.
133 static bool HasFewDifferentCharacters(Handle<String> pattern) {
134 int length = Min(kMaxLookaheadForBoyerMoore, pattern->length());
135 if (length <= kPatternTooShortForBoyerMoore) return false;
136 const int kMod = 128;
137 bool character_found[kMod];
139 memset(&character_found[0], 0, sizeof(character_found));
140 for (int i = 0; i < length; i++) {
141 int ch = (pattern->Get(i) & (kMod - 1));
142 if (!character_found[ch]) {
143 character_found[ch] = true;
145 // We declare a regexp low-alphabet if it has at least 3 times as many
146 // characters as it has different characters.
147 if (different * 3 > length) return false;
154 // Generic RegExp methods. Dispatches to implementation specific methods.
157 MaybeHandle<Object> RegExpImpl::Compile(Handle<JSRegExp> re,
158 Handle<String> pattern,
159 Handle<String> flag_str) {
160 Isolate* isolate = re->GetIsolate();
162 JSRegExp::Flags flags = RegExpFlagsFromString(flag_str);
163 CompilationCache* compilation_cache = isolate->compilation_cache();
164 MaybeHandle<FixedArray> maybe_cached =
165 compilation_cache->LookupRegExp(pattern, flags);
166 Handle<FixedArray> cached;
167 bool in_cache = maybe_cached.ToHandle(&cached);
168 LOG(isolate, RegExpCompileEvent(re, in_cache));
170 Handle<Object> result;
172 re->set_data(*cached);
175 pattern = String::Flatten(pattern);
176 PostponeInterruptsScope postpone(isolate);
177 RegExpCompileData parse_result;
178 FlatStringReader reader(isolate, pattern);
179 if (!RegExpParser::ParseRegExp(&reader, flags.is_multiline(),
180 &parse_result, &zone)) {
181 // Throw an exception if we fail to parse the pattern.
182 return ThrowRegExpException(re,
188 bool has_been_compiled = false;
190 if (parse_result.simple &&
191 !flags.is_ignore_case() &&
192 !flags.is_sticky() &&
193 !HasFewDifferentCharacters(pattern)) {
194 // Parse-tree is a single atom that is equal to the pattern.
195 AtomCompile(re, pattern, flags, pattern);
196 has_been_compiled = true;
197 } else if (parse_result.tree->IsAtom() &&
198 !flags.is_ignore_case() &&
199 !flags.is_sticky() &&
200 parse_result.capture_count == 0) {
201 RegExpAtom* atom = parse_result.tree->AsAtom();
202 Vector<const uc16> atom_pattern = atom->data();
203 Handle<String> atom_string;
204 ASSIGN_RETURN_ON_EXCEPTION(
205 isolate, atom_string,
206 isolate->factory()->NewStringFromTwoByte(atom_pattern),
208 if (!HasFewDifferentCharacters(atom_string)) {
209 AtomCompile(re, pattern, flags, atom_string);
210 has_been_compiled = true;
213 if (!has_been_compiled) {
214 IrregexpInitialize(re, pattern, flags, parse_result.capture_count);
216 DCHECK(re->data()->IsFixedArray());
217 // Compilation succeeded so the data is set on the regexp
218 // and we can store it in the cache.
219 Handle<FixedArray> data(FixedArray::cast(re->data()));
220 compilation_cache->PutRegExp(pattern, flags, data);
226 MaybeHandle<Object> RegExpImpl::Exec(Handle<JSRegExp> regexp,
227 Handle<String> subject,
229 Handle<JSArray> last_match_info) {
230 switch (regexp->TypeTag()) {
232 return AtomExec(regexp, subject, index, last_match_info);
233 case JSRegExp::IRREGEXP: {
234 return IrregexpExec(regexp, subject, index, last_match_info);
238 return MaybeHandle<Object>();
243 // RegExp Atom implementation: Simple string search using indexOf.
246 void RegExpImpl::AtomCompile(Handle<JSRegExp> re,
247 Handle<String> pattern,
248 JSRegExp::Flags flags,
249 Handle<String> match_pattern) {
250 re->GetIsolate()->factory()->SetRegExpAtomData(re,
258 static void SetAtomLastCapture(FixedArray* array,
262 SealHandleScope shs(array->GetIsolate());
263 RegExpImpl::SetLastCaptureCount(array, 2);
264 RegExpImpl::SetLastSubject(array, subject);
265 RegExpImpl::SetLastInput(array, subject);
266 RegExpImpl::SetCapture(array, 0, from);
267 RegExpImpl::SetCapture(array, 1, to);
271 int RegExpImpl::AtomExecRaw(Handle<JSRegExp> regexp,
272 Handle<String> subject,
276 Isolate* isolate = regexp->GetIsolate();
279 DCHECK(index <= subject->length());
281 subject = String::Flatten(subject);
282 DisallowHeapAllocation no_gc; // ensure vectors stay valid
284 String* needle = String::cast(regexp->DataAt(JSRegExp::kAtomPatternIndex));
285 int needle_len = needle->length();
286 DCHECK(needle->IsFlat());
287 DCHECK_LT(0, needle_len);
289 if (index + needle_len > subject->length()) {
290 return RegExpImpl::RE_FAILURE;
293 for (int i = 0; i < output_size; i += 2) {
294 String::FlatContent needle_content = needle->GetFlatContent();
295 String::FlatContent subject_content = subject->GetFlatContent();
296 DCHECK(needle_content.IsFlat());
297 DCHECK(subject_content.IsFlat());
298 // dispatch on type of strings
300 (needle_content.IsOneByte()
301 ? (subject_content.IsOneByte()
302 ? SearchString(isolate, subject_content.ToOneByteVector(),
303 needle_content.ToOneByteVector(), index)
304 : SearchString(isolate, subject_content.ToUC16Vector(),
305 needle_content.ToOneByteVector(), index))
306 : (subject_content.IsOneByte()
307 ? SearchString(isolate, subject_content.ToOneByteVector(),
308 needle_content.ToUC16Vector(), index)
309 : SearchString(isolate, subject_content.ToUC16Vector(),
310 needle_content.ToUC16Vector(), index)));
312 return i / 2; // Return number of matches.
315 output[i+1] = index + needle_len;
319 return output_size / 2;
323 Handle<Object> RegExpImpl::AtomExec(Handle<JSRegExp> re,
324 Handle<String> subject,
326 Handle<JSArray> last_match_info) {
327 Isolate* isolate = re->GetIsolate();
329 static const int kNumRegisters = 2;
330 STATIC_ASSERT(kNumRegisters <= Isolate::kJSRegexpStaticOffsetsVectorSize);
331 int32_t* output_registers = isolate->jsregexp_static_offsets_vector();
333 int res = AtomExecRaw(re, subject, index, output_registers, kNumRegisters);
335 if (res == RegExpImpl::RE_FAILURE) return isolate->factory()->null_value();
337 DCHECK_EQ(res, RegExpImpl::RE_SUCCESS);
338 SealHandleScope shs(isolate);
339 FixedArray* array = FixedArray::cast(last_match_info->elements());
340 SetAtomLastCapture(array, *subject, output_registers[0], output_registers[1]);
341 return last_match_info;
345 // Irregexp implementation.
347 // Ensures that the regexp object contains a compiled version of the
348 // source for either one-byte or two-byte subject strings.
349 // If the compiled version doesn't already exist, it is compiled
350 // from the source pattern.
351 // If compilation fails, an exception is thrown and this function
353 bool RegExpImpl::EnsureCompiledIrregexp(Handle<JSRegExp> re,
354 Handle<String> sample_subject,
356 Object* compiled_code = re->DataAt(JSRegExp::code_index(is_one_byte));
357 #ifdef V8_INTERPRETED_REGEXP
358 if (compiled_code->IsByteArray()) return true;
359 #else // V8_INTERPRETED_REGEXP (RegExp native code)
360 if (compiled_code->IsCode()) return true;
362 // We could potentially have marked this as flushable, but have kept
363 // a saved version if we did not flush it yet.
364 Object* saved_code = re->DataAt(JSRegExp::saved_code_index(is_one_byte));
365 if (saved_code->IsCode()) {
366 // Reinstate the code in the original place.
367 re->SetDataAt(JSRegExp::code_index(is_one_byte), saved_code);
368 DCHECK(compiled_code->IsSmi());
371 return CompileIrregexp(re, sample_subject, is_one_byte);
375 static void CreateRegExpErrorObjectAndThrow(Handle<JSRegExp> re,
376 Handle<String> error_message,
378 Factory* factory = isolate->factory();
379 Handle<FixedArray> elements = factory->NewFixedArray(2);
380 elements->set(0, re->Pattern());
381 elements->set(1, *error_message);
382 Handle<JSArray> array = factory->NewJSArrayWithElements(elements);
383 Handle<Object> error;
384 MaybeHandle<Object> maybe_error =
385 factory->NewSyntaxError("malformed_regexp", array);
386 if (maybe_error.ToHandle(&error)) isolate->Throw(*error);
390 bool RegExpImpl::CompileIrregexp(Handle<JSRegExp> re,
391 Handle<String> sample_subject,
393 // Compile the RegExp.
394 Isolate* isolate = re->GetIsolate();
396 PostponeInterruptsScope postpone(isolate);
397 // If we had a compilation error the last time this is saved at the
399 Object* entry = re->DataAt(JSRegExp::code_index(is_one_byte));
400 // When arriving here entry can only be a smi, either representing an
401 // uncompiled regexp, a previous compilation error, or code that has
403 DCHECK(entry->IsSmi());
404 int entry_value = Smi::cast(entry)->value();
405 DCHECK(entry_value == JSRegExp::kUninitializedValue ||
406 entry_value == JSRegExp::kCompilationErrorValue ||
407 (entry_value < JSRegExp::kCodeAgeMask && entry_value >= 0));
409 if (entry_value == JSRegExp::kCompilationErrorValue) {
410 // A previous compilation failed and threw an error which we store in
411 // the saved code index (we store the error message, not the actual
412 // error). Recreate the error object and throw it.
413 Object* error_string = re->DataAt(JSRegExp::saved_code_index(is_one_byte));
414 DCHECK(error_string->IsString());
415 Handle<String> error_message(String::cast(error_string));
416 CreateRegExpErrorObjectAndThrow(re, error_message, isolate);
420 JSRegExp::Flags flags = re->GetFlags();
422 Handle<String> pattern(re->Pattern());
423 pattern = String::Flatten(pattern);
424 RegExpCompileData compile_data;
425 FlatStringReader reader(isolate, pattern);
426 if (!RegExpParser::ParseRegExp(&reader, flags.is_multiline(),
429 // Throw an exception if we fail to parse the pattern.
430 // THIS SHOULD NOT HAPPEN. We already pre-parsed it successfully once.
431 USE(ThrowRegExpException(re,
434 "malformed_regexp"));
437 RegExpEngine::CompilationResult result = RegExpEngine::Compile(
438 &compile_data, flags.is_ignore_case(), flags.is_global(),
439 flags.is_multiline(), flags.is_sticky(), pattern, sample_subject,
441 if (result.error_message != NULL) {
442 // Unable to compile regexp.
443 Handle<String> error_message = isolate->factory()->NewStringFromUtf8(
444 CStrVector(result.error_message)).ToHandleChecked();
445 CreateRegExpErrorObjectAndThrow(re, error_message, isolate);
449 Handle<FixedArray> data = Handle<FixedArray>(FixedArray::cast(re->data()));
450 data->set(JSRegExp::code_index(is_one_byte), result.code);
451 int register_max = IrregexpMaxRegisterCount(*data);
452 if (result.num_registers > register_max) {
453 SetIrregexpMaxRegisterCount(*data, result.num_registers);
460 int RegExpImpl::IrregexpMaxRegisterCount(FixedArray* re) {
462 re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
466 void RegExpImpl::SetIrregexpMaxRegisterCount(FixedArray* re, int value) {
467 re->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(value));
471 int RegExpImpl::IrregexpNumberOfCaptures(FixedArray* re) {
472 return Smi::cast(re->get(JSRegExp::kIrregexpCaptureCountIndex))->value();
476 int RegExpImpl::IrregexpNumberOfRegisters(FixedArray* re) {
477 return Smi::cast(re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
481 ByteArray* RegExpImpl::IrregexpByteCode(FixedArray* re, bool is_one_byte) {
482 return ByteArray::cast(re->get(JSRegExp::code_index(is_one_byte)));
486 Code* RegExpImpl::IrregexpNativeCode(FixedArray* re, bool is_one_byte) {
487 return Code::cast(re->get(JSRegExp::code_index(is_one_byte)));
491 void RegExpImpl::IrregexpInitialize(Handle<JSRegExp> re,
492 Handle<String> pattern,
493 JSRegExp::Flags flags,
495 // Initialize compiled code entries to null.
496 re->GetIsolate()->factory()->SetRegExpIrregexpData(re,
504 int RegExpImpl::IrregexpPrepare(Handle<JSRegExp> regexp,
505 Handle<String> subject) {
506 subject = String::Flatten(subject);
508 // Check representation of the underlying storage.
509 bool is_one_byte = subject->IsOneByteRepresentationUnderneath();
510 if (!EnsureCompiledIrregexp(regexp, subject, is_one_byte)) return -1;
512 #ifdef V8_INTERPRETED_REGEXP
513 // Byte-code regexp needs space allocated for all its registers.
514 // The result captures are copied to the start of the registers array
515 // if the match succeeds. This way those registers are not clobbered
516 // when we set the last match info from last successful match.
517 return IrregexpNumberOfRegisters(FixedArray::cast(regexp->data())) +
518 (IrregexpNumberOfCaptures(FixedArray::cast(regexp->data())) + 1) * 2;
519 #else // V8_INTERPRETED_REGEXP
520 // Native regexp only needs room to output captures. Registers are handled
522 return (IrregexpNumberOfCaptures(FixedArray::cast(regexp->data())) + 1) * 2;
523 #endif // V8_INTERPRETED_REGEXP
527 int RegExpImpl::IrregexpExecRaw(Handle<JSRegExp> regexp,
528 Handle<String> subject,
532 Isolate* isolate = regexp->GetIsolate();
534 Handle<FixedArray> irregexp(FixedArray::cast(regexp->data()), isolate);
537 DCHECK(index <= subject->length());
538 DCHECK(subject->IsFlat());
540 bool is_one_byte = subject->IsOneByteRepresentationUnderneath();
542 #ifndef V8_INTERPRETED_REGEXP
543 DCHECK(output_size >= (IrregexpNumberOfCaptures(*irregexp) + 1) * 2);
545 EnsureCompiledIrregexp(regexp, subject, is_one_byte);
546 Handle<Code> code(IrregexpNativeCode(*irregexp, is_one_byte), isolate);
547 // The stack is used to allocate registers for the compiled regexp code.
548 // This means that in case of failure, the output registers array is left
549 // untouched and contains the capture results from the previous successful
550 // match. We can use that to set the last match info lazily.
551 NativeRegExpMacroAssembler::Result res =
552 NativeRegExpMacroAssembler::Match(code,
558 if (res != NativeRegExpMacroAssembler::RETRY) {
559 DCHECK(res != NativeRegExpMacroAssembler::EXCEPTION ||
560 isolate->has_pending_exception());
562 static_cast<int>(NativeRegExpMacroAssembler::SUCCESS) == RE_SUCCESS);
564 static_cast<int>(NativeRegExpMacroAssembler::FAILURE) == RE_FAILURE);
565 STATIC_ASSERT(static_cast<int>(NativeRegExpMacroAssembler::EXCEPTION)
567 return static_cast<IrregexpResult>(res);
569 // If result is RETRY, the string has changed representation, and we
570 // must restart from scratch.
571 // In this case, it means we must make sure we are prepared to handle
572 // the, potentially, different subject (the string can switch between
573 // being internal and external, and even between being Latin1 and UC16,
574 // but the characters are always the same).
575 IrregexpPrepare(regexp, subject);
576 is_one_byte = subject->IsOneByteRepresentationUnderneath();
580 #else // V8_INTERPRETED_REGEXP
582 DCHECK(output_size >= IrregexpNumberOfRegisters(*irregexp));
583 // We must have done EnsureCompiledIrregexp, so we can get the number of
585 int number_of_capture_registers =
586 (IrregexpNumberOfCaptures(*irregexp) + 1) * 2;
587 int32_t* raw_output = &output[number_of_capture_registers];
588 // We do not touch the actual capture result registers until we know there
589 // has been a match so that we can use those capture results to set the
591 for (int i = number_of_capture_registers - 1; i >= 0; i--) {
594 Handle<ByteArray> byte_codes(IrregexpByteCode(*irregexp, is_one_byte),
597 IrregexpResult result = IrregexpInterpreter::Match(isolate,
602 if (result == RE_SUCCESS) {
603 // Copy capture results to the start of the registers array.
604 MemCopy(output, raw_output, number_of_capture_registers * sizeof(int32_t));
606 if (result == RE_EXCEPTION) {
607 DCHECK(!isolate->has_pending_exception());
608 isolate->StackOverflow();
611 #endif // V8_INTERPRETED_REGEXP
615 MaybeHandle<Object> RegExpImpl::IrregexpExec(Handle<JSRegExp> regexp,
616 Handle<String> subject,
618 Handle<JSArray> last_match_info) {
619 Isolate* isolate = regexp->GetIsolate();
620 DCHECK_EQ(regexp->TypeTag(), JSRegExp::IRREGEXP);
622 // Prepare space for the return values.
623 #if defined(V8_INTERPRETED_REGEXP) && defined(DEBUG)
624 if (FLAG_trace_regexp_bytecodes) {
625 String* pattern = regexp->Pattern();
626 PrintF("\n\nRegexp match: /%s/\n\n", pattern->ToCString().get());
627 PrintF("\n\nSubject string: '%s'\n\n", subject->ToCString().get());
630 int required_registers = RegExpImpl::IrregexpPrepare(regexp, subject);
631 if (required_registers < 0) {
632 // Compiling failed with an exception.
633 DCHECK(isolate->has_pending_exception());
634 return MaybeHandle<Object>();
637 int32_t* output_registers = NULL;
638 if (required_registers > Isolate::kJSRegexpStaticOffsetsVectorSize) {
639 output_registers = NewArray<int32_t>(required_registers);
641 SmartArrayPointer<int32_t> auto_release(output_registers);
642 if (output_registers == NULL) {
643 output_registers = isolate->jsregexp_static_offsets_vector();
646 int res = RegExpImpl::IrregexpExecRaw(
647 regexp, subject, previous_index, output_registers, required_registers);
648 if (res == RE_SUCCESS) {
650 IrregexpNumberOfCaptures(FixedArray::cast(regexp->data()));
651 return SetLastMatchInfo(
652 last_match_info, subject, capture_count, output_registers);
654 if (res == RE_EXCEPTION) {
655 DCHECK(isolate->has_pending_exception());
656 return MaybeHandle<Object>();
658 DCHECK(res == RE_FAILURE);
659 return isolate->factory()->null_value();
663 Handle<JSArray> RegExpImpl::SetLastMatchInfo(Handle<JSArray> last_match_info,
664 Handle<String> subject,
667 DCHECK(last_match_info->HasFastObjectElements());
668 int capture_register_count = (capture_count + 1) * 2;
669 JSArray::EnsureSize(last_match_info,
670 capture_register_count + kLastMatchOverhead);
671 DisallowHeapAllocation no_allocation;
672 FixedArray* array = FixedArray::cast(last_match_info->elements());
674 for (int i = 0; i < capture_register_count; i += 2) {
675 SetCapture(array, i, match[i]);
676 SetCapture(array, i + 1, match[i + 1]);
679 SetLastCaptureCount(array, capture_register_count);
680 SetLastSubject(array, *subject);
681 SetLastInput(array, *subject);
682 return last_match_info;
686 RegExpImpl::GlobalCache::GlobalCache(Handle<JSRegExp> regexp,
687 Handle<String> subject,
690 : register_array_(NULL),
691 register_array_size_(0),
694 #ifdef V8_INTERPRETED_REGEXP
695 bool interpreted = true;
697 bool interpreted = false;
698 #endif // V8_INTERPRETED_REGEXP
700 if (regexp_->TypeTag() == JSRegExp::ATOM) {
701 static const int kAtomRegistersPerMatch = 2;
702 registers_per_match_ = kAtomRegistersPerMatch;
703 // There is no distinction between interpreted and native for atom regexps.
706 registers_per_match_ = RegExpImpl::IrregexpPrepare(regexp_, subject_);
707 if (registers_per_match_ < 0) {
708 num_matches_ = -1; // Signal exception.
713 if (is_global && !interpreted) {
714 register_array_size_ =
715 Max(registers_per_match_, Isolate::kJSRegexpStaticOffsetsVectorSize);
716 max_matches_ = register_array_size_ / registers_per_match_;
718 // Global loop in interpreted regexp is not implemented. We choose
719 // the size of the offsets vector so that it can only store one match.
720 register_array_size_ = registers_per_match_;
724 if (register_array_size_ > Isolate::kJSRegexpStaticOffsetsVectorSize) {
725 register_array_ = NewArray<int32_t>(register_array_size_);
727 register_array_ = isolate->jsregexp_static_offsets_vector();
730 // Set state so that fetching the results the first time triggers a call
731 // to the compiled regexp.
732 current_match_index_ = max_matches_ - 1;
733 num_matches_ = max_matches_;
734 DCHECK(registers_per_match_ >= 2); // Each match has at least one capture.
735 DCHECK_GE(register_array_size_, registers_per_match_);
736 int32_t* last_match =
737 ®ister_array_[current_match_index_ * registers_per_match_];
743 // -------------------------------------------------------------------
744 // Implementation of the Irregexp regular expression engine.
746 // The Irregexp regular expression engine is intended to be a complete
747 // implementation of ECMAScript regular expressions. It generates either
748 // bytecodes or native code.
750 // The Irregexp regexp engine is structured in three steps.
751 // 1) The parser generates an abstract syntax tree. See ast.cc.
752 // 2) From the AST a node network is created. The nodes are all
753 // subclasses of RegExpNode. The nodes represent states when
754 // executing a regular expression. Several optimizations are
755 // performed on the node network.
756 // 3) From the nodes we generate either byte codes or native code
757 // that can actually execute the regular expression (perform
758 // the search). The code generation step is described in more
763 // The nodes are divided into four main categories.
765 // These represent places where the regular expression can
766 // match in more than one way. For example on entry to an
767 // alternation (foo|bar) or a repetition (*, +, ? or {}).
769 // These represent places where some action should be
770 // performed. Examples include recording the current position
771 // in the input string to a register (in order to implement
772 // captures) or other actions on register for example in order
773 // to implement the counters needed for {} repetitions.
775 // These attempt to match some element part of the input string.
776 // Examples of elements include character classes, plain strings
777 // or back references.
779 // These are used to implement the actions required on finding
780 // a successful match or failing to find a match.
782 // The code generated (whether as byte codes or native code) maintains
783 // some state as it runs. This consists of the following elements:
785 // * The capture registers. Used for string captures.
786 // * Other registers. Used for counters etc.
787 // * The current position.
788 // * The stack of backtracking information. Used when a matching node
789 // fails to find a match and needs to try an alternative.
791 // Conceptual regular expression execution model:
793 // There is a simple conceptual model of regular expression execution
794 // which will be presented first. The actual code generated is a more
795 // efficient simulation of the simple conceptual model:
797 // * Choice nodes are implemented as follows:
798 // For each choice except the last {
799 // push current position
800 // push backtrack code location
801 // <generate code to test for choice>
802 // backtrack code location:
803 // pop current position
805 // <generate code to test for last choice>
807 // * Actions nodes are generated as follows
808 // <push affected registers on backtrack stack>
809 // <generate code to perform action>
810 // push backtrack code location
811 // <generate code to test for following nodes>
812 // backtrack code location:
813 // <pop affected registers to restore their state>
814 // <pop backtrack location from stack and go to it>
816 // * Matching nodes are generated as follows:
817 // if input string matches at current position
818 // update current position
819 // <generate code to test for following nodes>
821 // <pop backtrack location from stack and go to it>
823 // Thus it can be seen that the current position is saved and restored
824 // by the choice nodes, whereas the registers are saved and restored by
825 // by the action nodes that manipulate them.
827 // The other interesting aspect of this model is that nodes are generated
828 // at the point where they are needed by a recursive call to Emit(). If
829 // the node has already been code generated then the Emit() call will
830 // generate a jump to the previously generated code instead. In order to
831 // limit recursion it is possible for the Emit() function to put the node
832 // on a work list for later generation and instead generate a jump. The
833 // destination of the jump is resolved later when the code is generated.
835 // Actual regular expression code generation.
837 // Code generation is actually more complicated than the above. In order
838 // to improve the efficiency of the generated code some optimizations are
841 // * Choice nodes have 1-character lookahead.
842 // A choice node looks at the following character and eliminates some of
843 // the choices immediately based on that character. This is not yet
845 // * Simple greedy loops store reduced backtracking information.
846 // A quantifier like /.*foo/m will greedily match the whole input. It will
847 // then need to backtrack to a point where it can match "foo". The naive
848 // implementation of this would push each character position onto the
849 // backtracking stack, then pop them off one by one. This would use space
850 // proportional to the length of the input string. However since the "."
851 // can only match in one way and always has a constant length (in this case
852 // of 1) it suffices to store the current position on the top of the stack
853 // once. Matching now becomes merely incrementing the current position and
854 // backtracking becomes decrementing the current position and checking the
855 // result against the stored current position. This is faster and saves
857 // * The current state is virtualized.
858 // This is used to defer expensive operations until it is clear that they
859 // are needed and to generate code for a node more than once, allowing
860 // specialized an efficient versions of the code to be created. This is
861 // explained in the section below.
863 // Execution state virtualization.
865 // Instead of emitting code, nodes that manipulate the state can record their
866 // manipulation in an object called the Trace. The Trace object can record a
867 // current position offset, an optional backtrack code location on the top of
868 // the virtualized backtrack stack and some register changes. When a node is
869 // to be emitted it can flush the Trace or update it. Flushing the Trace
870 // will emit code to bring the actual state into line with the virtual state.
871 // Avoiding flushing the state can postpone some work (e.g. updates of capture
872 // registers). Postponing work can save time when executing the regular
873 // expression since it may be found that the work never has to be done as a
874 // failure to match can occur. In addition it is much faster to jump to a
875 // known backtrack code location than it is to pop an unknown backtrack
876 // location from the stack and jump there.
878 // The virtual state found in the Trace affects code generation. For example
879 // the virtual state contains the difference between the actual current
880 // position and the virtual current position, and matching code needs to use
881 // this offset to attempt a match in the correct location of the input
882 // string. Therefore code generated for a non-trivial trace is specialized
883 // to that trace. The code generator therefore has the ability to generate
884 // code for each node several times. In order to limit the size of the
885 // generated code there is an arbitrary limit on how many specialized sets of
886 // code may be generated for a given node. If the limit is reached, the
887 // trace is flushed and a generic version of the code for a node is emitted.
888 // This is subsequently used for that node. The code emitted for non-generic
889 // trace is not recorded in the node and so it cannot currently be reused in
890 // the event that code generation is requested for an identical trace.
893 void RegExpTree::AppendToText(RegExpText* text, Zone* zone) {
898 void RegExpAtom::AppendToText(RegExpText* text, Zone* zone) {
899 text->AddElement(TextElement::Atom(this), zone);
903 void RegExpCharacterClass::AppendToText(RegExpText* text, Zone* zone) {
904 text->AddElement(TextElement::CharClass(this), zone);
908 void RegExpText::AppendToText(RegExpText* text, Zone* zone) {
909 for (int i = 0; i < elements()->length(); i++)
910 text->AddElement(elements()->at(i), zone);
914 TextElement TextElement::Atom(RegExpAtom* atom) {
915 return TextElement(ATOM, atom);
919 TextElement TextElement::CharClass(RegExpCharacterClass* char_class) {
920 return TextElement(CHAR_CLASS, char_class);
924 int TextElement::length() const {
925 switch (text_type()) {
927 return atom()->length();
937 DispatchTable* ChoiceNode::GetTable(bool ignore_case) {
938 if (table_ == NULL) {
939 table_ = new(zone()) DispatchTable(zone());
940 DispatchTableConstructor cons(table_, ignore_case, zone());
941 cons.BuildTable(this);
947 class FrequencyCollator {
949 FrequencyCollator() : total_samples_(0) {
950 for (int i = 0; i < RegExpMacroAssembler::kTableSize; i++) {
951 frequencies_[i] = CharacterFrequency(i);
955 void CountCharacter(int character) {
956 int index = (character & RegExpMacroAssembler::kTableMask);
957 frequencies_[index].Increment();
961 // Does not measure in percent, but rather per-128 (the table size from the
962 // regexp macro assembler).
963 int Frequency(int in_character) {
964 DCHECK((in_character & RegExpMacroAssembler::kTableMask) == in_character);
965 if (total_samples_ < 1) return 1; // Division by zero.
967 (frequencies_[in_character].counter() * 128) / total_samples_;
968 return freq_in_per128;
972 class CharacterFrequency {
974 CharacterFrequency() : counter_(0), character_(-1) { }
975 explicit CharacterFrequency(int character)
976 : counter_(0), character_(character) { }
978 void Increment() { counter_++; }
979 int counter() { return counter_; }
980 int character() { return character_; }
989 CharacterFrequency frequencies_[RegExpMacroAssembler::kTableSize];
994 class RegExpCompiler {
996 RegExpCompiler(int capture_count, bool ignore_case, bool is_one_byte,
999 int AllocateRegister() {
1000 if (next_register_ >= RegExpMacroAssembler::kMaxRegister) {
1001 reg_exp_too_big_ = true;
1002 return next_register_;
1004 return next_register_++;
1007 RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler,
1010 Handle<String> pattern);
1012 inline void AddWork(RegExpNode* node) { work_list_->Add(node); }
1014 static const int kImplementationOffset = 0;
1015 static const int kNumberOfRegistersOffset = 0;
1016 static const int kCodeOffset = 1;
1018 RegExpMacroAssembler* macro_assembler() { return macro_assembler_; }
1019 EndNode* accept() { return accept_; }
1021 static const int kMaxRecursion = 100;
1022 inline int recursion_depth() { return recursion_depth_; }
1023 inline void IncrementRecursionDepth() { recursion_depth_++; }
1024 inline void DecrementRecursionDepth() { recursion_depth_--; }
1026 void SetRegExpTooBig() { reg_exp_too_big_ = true; }
1028 inline bool ignore_case() { return ignore_case_; }
1029 inline bool one_byte() { return one_byte_; }
1030 FrequencyCollator* frequency_collator() { return &frequency_collator_; }
1032 int current_expansion_factor() { return current_expansion_factor_; }
1033 void set_current_expansion_factor(int value) {
1034 current_expansion_factor_ = value;
1037 Zone* zone() const { return zone_; }
1039 static const int kNoRegister = -1;
1044 List<RegExpNode*>* work_list_;
1045 int recursion_depth_;
1046 RegExpMacroAssembler* macro_assembler_;
1049 bool reg_exp_too_big_;
1050 int current_expansion_factor_;
1051 FrequencyCollator frequency_collator_;
1056 class RecursionCheck {
1058 explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
1059 compiler->IncrementRecursionDepth();
1061 ~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
1063 RegExpCompiler* compiler_;
1067 static RegExpEngine::CompilationResult IrregexpRegExpTooBig(Isolate* isolate) {
1068 return RegExpEngine::CompilationResult(isolate, "RegExp too big");
1072 // Attempts to compile the regexp using an Irregexp code generator. Returns
1073 // a fixed array or a null handle depending on whether it succeeded.
1074 RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case,
1075 bool one_byte, Zone* zone)
1076 : next_register_(2 * (capture_count + 1)),
1078 recursion_depth_(0),
1079 ignore_case_(ignore_case),
1080 one_byte_(one_byte),
1081 reg_exp_too_big_(false),
1082 current_expansion_factor_(1),
1083 frequency_collator_(),
1085 accept_ = new(zone) EndNode(EndNode::ACCEPT, zone);
1086 DCHECK(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
1090 RegExpEngine::CompilationResult RegExpCompiler::Assemble(
1091 RegExpMacroAssembler* macro_assembler,
1094 Handle<String> pattern) {
1095 Heap* heap = pattern->GetHeap();
1097 bool use_slow_safe_regexp_compiler = false;
1098 if (heap->total_regexp_code_generated() >
1099 RegExpImpl::kRegWxpCompiledLimit &&
1100 heap->isolate()->memory_allocator()->SizeExecutable() >
1101 RegExpImpl::kRegExpExecutableMemoryLimit) {
1102 use_slow_safe_regexp_compiler = true;
1105 macro_assembler->set_slow_safe(use_slow_safe_regexp_compiler);
1108 if (FLAG_trace_regexp_assembler)
1109 macro_assembler_ = new RegExpMacroAssemblerTracer(macro_assembler);
1112 macro_assembler_ = macro_assembler;
1114 List <RegExpNode*> work_list(0);
1115 work_list_ = &work_list;
1117 macro_assembler_->PushBacktrack(&fail);
1119 start->Emit(this, &new_trace);
1120 macro_assembler_->Bind(&fail);
1121 macro_assembler_->Fail();
1122 while (!work_list.is_empty()) {
1123 work_list.RemoveLast()->Emit(this, &new_trace);
1125 if (reg_exp_too_big_) return IrregexpRegExpTooBig(zone_->isolate());
1127 Handle<HeapObject> code = macro_assembler_->GetCode(pattern);
1128 heap->IncreaseTotalRegexpCodeGenerated(code->Size());
1131 if (FLAG_print_code) {
1132 CodeTracer::Scope trace_scope(heap->isolate()->GetCodeTracer());
1133 OFStream os(trace_scope.file());
1134 Handle<Code>::cast(code)->Disassemble(pattern->ToCString().get(), os);
1136 if (FLAG_trace_regexp_assembler) {
1137 delete macro_assembler_;
1140 return RegExpEngine::CompilationResult(*code, next_register_);
1144 bool Trace::DeferredAction::Mentions(int that) {
1145 if (action_type() == ActionNode::CLEAR_CAPTURES) {
1146 Interval range = static_cast<DeferredClearCaptures*>(this)->range();
1147 return range.Contains(that);
1149 return reg() == that;
1154 bool Trace::mentions_reg(int reg) {
1155 for (DeferredAction* action = actions_;
1157 action = action->next()) {
1158 if (action->Mentions(reg))
1165 bool Trace::GetStoredPosition(int reg, int* cp_offset) {
1166 DCHECK_EQ(0, *cp_offset);
1167 for (DeferredAction* action = actions_;
1169 action = action->next()) {
1170 if (action->Mentions(reg)) {
1171 if (action->action_type() == ActionNode::STORE_POSITION) {
1172 *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
1183 int Trace::FindAffectedRegisters(OutSet* affected_registers,
1185 int max_register = RegExpCompiler::kNoRegister;
1186 for (DeferredAction* action = actions_;
1188 action = action->next()) {
1189 if (action->action_type() == ActionNode::CLEAR_CAPTURES) {
1190 Interval range = static_cast<DeferredClearCaptures*>(action)->range();
1191 for (int i = range.from(); i <= range.to(); i++)
1192 affected_registers->Set(i, zone);
1193 if (range.to() > max_register) max_register = range.to();
1195 affected_registers->Set(action->reg(), zone);
1196 if (action->reg() > max_register) max_register = action->reg();
1199 return max_register;
1203 void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
1205 const OutSet& registers_to_pop,
1206 const OutSet& registers_to_clear) {
1207 for (int reg = max_register; reg >= 0; reg--) {
1208 if (registers_to_pop.Get(reg)) {
1209 assembler->PopRegister(reg);
1210 } else if (registers_to_clear.Get(reg)) {
1212 while (reg > 0 && registers_to_clear.Get(reg - 1)) {
1215 assembler->ClearRegisters(reg, clear_to);
1221 void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
1223 const OutSet& affected_registers,
1224 OutSet* registers_to_pop,
1225 OutSet* registers_to_clear,
1227 // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
1228 const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
1230 // Count pushes performed to force a stack limit check occasionally.
1233 for (int reg = 0; reg <= max_register; reg++) {
1234 if (!affected_registers.Get(reg)) {
1238 // The chronologically first deferred action in the trace
1239 // is used to infer the action needed to restore a register
1240 // to its previous state (or not, if it's safe to ignore it).
1241 enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
1242 DeferredActionUndoType undo_action = IGNORE;
1245 bool absolute = false;
1247 int store_position = -1;
1248 // This is a little tricky because we are scanning the actions in reverse
1249 // historical order (newest first).
1250 for (DeferredAction* action = actions_;
1252 action = action->next()) {
1253 if (action->Mentions(reg)) {
1254 switch (action->action_type()) {
1255 case ActionNode::SET_REGISTER: {
1256 Trace::DeferredSetRegister* psr =
1257 static_cast<Trace::DeferredSetRegister*>(action);
1259 value += psr->value();
1262 // SET_REGISTER is currently only used for newly introduced loop
1263 // counters. They can have a significant previous value if they
1264 // occour in a loop. TODO(lrn): Propagate this information, so
1265 // we can set undo_action to IGNORE if we know there is no value to
1267 undo_action = RESTORE;
1268 DCHECK_EQ(store_position, -1);
1272 case ActionNode::INCREMENT_REGISTER:
1276 DCHECK_EQ(store_position, -1);
1278 undo_action = RESTORE;
1280 case ActionNode::STORE_POSITION: {
1281 Trace::DeferredCapture* pc =
1282 static_cast<Trace::DeferredCapture*>(action);
1283 if (!clear && store_position == -1) {
1284 store_position = pc->cp_offset();
1287 // For captures we know that stores and clears alternate.
1288 // Other register, are never cleared, and if the occur
1289 // inside a loop, they might be assigned more than once.
1291 // Registers zero and one, aka "capture zero", is
1292 // always set correctly if we succeed. There is no
1293 // need to undo a setting on backtrack, because we
1294 // will set it again or fail.
1295 undo_action = IGNORE;
1297 undo_action = pc->is_capture() ? CLEAR : RESTORE;
1300 DCHECK_EQ(value, 0);
1303 case ActionNode::CLEAR_CAPTURES: {
1304 // Since we're scanning in reverse order, if we've already
1305 // set the position we have to ignore historically earlier
1306 // clearing operations.
1307 if (store_position == -1) {
1310 undo_action = RESTORE;
1312 DCHECK_EQ(value, 0);
1321 // Prepare for the undo-action (e.g., push if it's going to be popped).
1322 if (undo_action == RESTORE) {
1324 RegExpMacroAssembler::StackCheckFlag stack_check =
1325 RegExpMacroAssembler::kNoStackLimitCheck;
1326 if (pushes == push_limit) {
1327 stack_check = RegExpMacroAssembler::kCheckStackLimit;
1331 assembler->PushRegister(reg, stack_check);
1332 registers_to_pop->Set(reg, zone);
1333 } else if (undo_action == CLEAR) {
1334 registers_to_clear->Set(reg, zone);
1336 // Perform the chronologically last action (or accumulated increment)
1337 // for the register.
1338 if (store_position != -1) {
1339 assembler->WriteCurrentPositionToRegister(reg, store_position);
1341 assembler->ClearRegisters(reg, reg);
1342 } else if (absolute) {
1343 assembler->SetRegister(reg, value);
1344 } else if (value != 0) {
1345 assembler->AdvanceRegister(reg, value);
1351 // This is called as we come into a loop choice node and some other tricky
1352 // nodes. It normalizes the state of the code generator to ensure we can
1353 // generate generic code.
1354 void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
1355 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1357 DCHECK(!is_trivial());
1359 if (actions_ == NULL && backtrack() == NULL) {
1360 // Here we just have some deferred cp advances to fix and we are back to
1361 // a normal situation. We may also have to forget some information gained
1362 // through a quick check that was already performed.
1363 if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
1364 // Create a new trivial state and generate the node with that.
1366 successor->Emit(compiler, &new_state);
1370 // Generate deferred actions here along with code to undo them again.
1371 OutSet affected_registers;
1373 if (backtrack() != NULL) {
1374 // Here we have a concrete backtrack location. These are set up by choice
1375 // nodes and so they indicate that we have a deferred save of the current
1376 // position which we may need to emit here.
1377 assembler->PushCurrentPosition();
1380 int max_register = FindAffectedRegisters(&affected_registers,
1382 OutSet registers_to_pop;
1383 OutSet registers_to_clear;
1384 PerformDeferredActions(assembler,
1388 ®isters_to_clear,
1390 if (cp_offset_ != 0) {
1391 assembler->AdvanceCurrentPosition(cp_offset_);
1394 // Create a new trivial state and generate the node with that.
1396 assembler->PushBacktrack(&undo);
1398 successor->Emit(compiler, &new_state);
1400 // On backtrack we need to restore state.
1401 assembler->Bind(&undo);
1402 RestoreAffectedRegisters(assembler,
1405 registers_to_clear);
1406 if (backtrack() == NULL) {
1407 assembler->Backtrack();
1409 assembler->PopCurrentPosition();
1410 assembler->GoTo(backtrack());
1415 void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
1416 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1418 // Omit flushing the trace. We discard the entire stack frame anyway.
1420 if (!label()->is_bound()) {
1421 // We are completely independent of the trace, since we ignore it,
1422 // so this code can be used as the generic version.
1423 assembler->Bind(label());
1426 // Throw away everything on the backtrack stack since the start
1427 // of the negative submatch and restore the character position.
1428 assembler->ReadCurrentPositionFromRegister(current_position_register_);
1429 assembler->ReadStackPointerFromRegister(stack_pointer_register_);
1430 if (clear_capture_count_ > 0) {
1431 // Clear any captures that might have been performed during the success
1432 // of the body of the negative look-ahead.
1433 int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
1434 assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
1436 // Now that we have unwound the stack we find at the top of the stack the
1437 // backtrack that the BeginSubmatch node got.
1438 assembler->Backtrack();
1442 void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
1443 if (!trace->is_trivial()) {
1444 trace->Flush(compiler, this);
1447 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1448 if (!label()->is_bound()) {
1449 assembler->Bind(label());
1453 assembler->Succeed();
1456 assembler->GoTo(trace->backtrack());
1458 case NEGATIVE_SUBMATCH_SUCCESS:
1459 // This case is handled in a different virtual method.
1466 void GuardedAlternative::AddGuard(Guard* guard, Zone* zone) {
1467 if (guards_ == NULL)
1468 guards_ = new(zone) ZoneList<Guard*>(1, zone);
1469 guards_->Add(guard, zone);
1473 ActionNode* ActionNode::SetRegister(int reg,
1475 RegExpNode* on_success) {
1476 ActionNode* result =
1477 new(on_success->zone()) ActionNode(SET_REGISTER, on_success);
1478 result->data_.u_store_register.reg = reg;
1479 result->data_.u_store_register.value = val;
1484 ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
1485 ActionNode* result =
1486 new(on_success->zone()) ActionNode(INCREMENT_REGISTER, on_success);
1487 result->data_.u_increment_register.reg = reg;
1492 ActionNode* ActionNode::StorePosition(int reg,
1494 RegExpNode* on_success) {
1495 ActionNode* result =
1496 new(on_success->zone()) ActionNode(STORE_POSITION, on_success);
1497 result->data_.u_position_register.reg = reg;
1498 result->data_.u_position_register.is_capture = is_capture;
1503 ActionNode* ActionNode::ClearCaptures(Interval range,
1504 RegExpNode* on_success) {
1505 ActionNode* result =
1506 new(on_success->zone()) ActionNode(CLEAR_CAPTURES, on_success);
1507 result->data_.u_clear_captures.range_from = range.from();
1508 result->data_.u_clear_captures.range_to = range.to();
1513 ActionNode* ActionNode::BeginSubmatch(int stack_reg,
1515 RegExpNode* on_success) {
1516 ActionNode* result =
1517 new(on_success->zone()) ActionNode(BEGIN_SUBMATCH, on_success);
1518 result->data_.u_submatch.stack_pointer_register = stack_reg;
1519 result->data_.u_submatch.current_position_register = position_reg;
1524 ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
1526 int clear_register_count,
1527 int clear_register_from,
1528 RegExpNode* on_success) {
1529 ActionNode* result =
1530 new(on_success->zone()) ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
1531 result->data_.u_submatch.stack_pointer_register = stack_reg;
1532 result->data_.u_submatch.current_position_register = position_reg;
1533 result->data_.u_submatch.clear_register_count = clear_register_count;
1534 result->data_.u_submatch.clear_register_from = clear_register_from;
1539 ActionNode* ActionNode::EmptyMatchCheck(int start_register,
1540 int repetition_register,
1541 int repetition_limit,
1542 RegExpNode* on_success) {
1543 ActionNode* result =
1544 new(on_success->zone()) ActionNode(EMPTY_MATCH_CHECK, on_success);
1545 result->data_.u_empty_match_check.start_register = start_register;
1546 result->data_.u_empty_match_check.repetition_register = repetition_register;
1547 result->data_.u_empty_match_check.repetition_limit = repetition_limit;
1552 #define DEFINE_ACCEPT(Type) \
1553 void Type##Node::Accept(NodeVisitor* visitor) { \
1554 visitor->Visit##Type(this); \
1556 FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
1557 #undef DEFINE_ACCEPT
1560 void LoopChoiceNode::Accept(NodeVisitor* visitor) {
1561 visitor->VisitLoopChoice(this);
1565 // -------------------------------------------------------------------
1569 void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
1572 switch (guard->op()) {
1574 DCHECK(!trace->mentions_reg(guard->reg()));
1575 macro_assembler->IfRegisterGE(guard->reg(),
1577 trace->backtrack());
1580 DCHECK(!trace->mentions_reg(guard->reg()));
1581 macro_assembler->IfRegisterLT(guard->reg(),
1583 trace->backtrack());
1589 // Returns the number of characters in the equivalence class, omitting those
1590 // that cannot occur in the source string because it is ASCII.
1591 static int GetCaseIndependentLetters(Isolate* isolate, uc16 character,
1592 bool one_byte_subject,
1593 unibrow::uchar* letters) {
1595 isolate->jsregexp_uncanonicalize()->get(character, '\0', letters);
1596 // Unibrow returns 0 or 1 for characters where case independence is
1599 letters[0] = character;
1602 if (!one_byte_subject || character <= String::kMaxOneByteCharCode) {
1606 // The standard requires that non-ASCII characters cannot have ASCII
1607 // character codes in their equivalence class.
1608 // TODO(dcarney): issue 3550 this is not actually true for Latin1 anymore,
1609 // is it? For example, \u00C5 is equivalent to \u212B.
1614 static inline bool EmitSimpleCharacter(Isolate* isolate,
1615 RegExpCompiler* compiler,
1621 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1622 bool bound_checked = false;
1624 assembler->LoadCurrentCharacter(
1628 bound_checked = true;
1630 assembler->CheckNotCharacter(c, on_failure);
1631 return bound_checked;
1635 // Only emits non-letters (things that don't have case). Only used for case
1636 // independent matches.
1637 static inline bool EmitAtomNonLetter(Isolate* isolate,
1638 RegExpCompiler* compiler,
1644 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1645 bool one_byte = compiler->one_byte();
1646 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
1647 int length = GetCaseIndependentLetters(isolate, c, one_byte, chars);
1649 // This can't match. Must be an one-byte subject and a non-one-byte
1650 // character. We do not need to do anything since the one-byte pass
1651 // already handled this.
1652 return false; // Bounds not checked.
1654 bool checked = false;
1655 // We handle the length > 1 case in a later pass.
1657 if (one_byte && c > String::kMaxOneByteCharCodeU) {
1658 // Can't match - see above.
1659 return false; // Bounds not checked.
1662 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1665 macro_assembler->CheckNotCharacter(c, on_failure);
1671 static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
1672 bool one_byte, uc16 c1, uc16 c2,
1673 Label* on_failure) {
1676 char_mask = String::kMaxOneByteCharCode;
1678 char_mask = String::kMaxUtf16CodeUnit;
1680 uc16 exor = c1 ^ c2;
1681 // Check whether exor has only one bit set.
1682 if (((exor - 1) & exor) == 0) {
1683 // If c1 and c2 differ only by one bit.
1684 // Ecma262UnCanonicalize always gives the highest number last.
1686 uc16 mask = char_mask ^ exor;
1687 macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
1691 uc16 diff = c2 - c1;
1692 if (((diff - 1) & diff) == 0 && c1 >= diff) {
1693 // If the characters differ by 2^n but don't differ by one bit then
1694 // subtract the difference from the found character, then do the or
1695 // trick. We avoid the theoretical case where negative numbers are
1696 // involved in order to simplify code generation.
1697 uc16 mask = char_mask ^ diff;
1698 macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff,
1708 typedef bool EmitCharacterFunction(Isolate* isolate,
1709 RegExpCompiler* compiler,
1716 // Only emits letters (things that have case). Only used for case independent
1718 static inline bool EmitAtomLetter(Isolate* isolate,
1719 RegExpCompiler* compiler,
1725 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1726 bool one_byte = compiler->one_byte();
1727 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
1728 int length = GetCaseIndependentLetters(isolate, c, one_byte, chars);
1729 if (length <= 1) return false;
1730 // We may not need to check against the end of the input string
1731 // if this character lies before a character that matched.
1733 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1736 DCHECK(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4);
1739 if (ShortCutEmitCharacterPair(macro_assembler, one_byte, chars[0],
1740 chars[1], on_failure)) {
1742 macro_assembler->CheckCharacter(chars[0], &ok);
1743 macro_assembler->CheckNotCharacter(chars[1], on_failure);
1744 macro_assembler->Bind(&ok);
1749 macro_assembler->CheckCharacter(chars[3], &ok);
1752 macro_assembler->CheckCharacter(chars[0], &ok);
1753 macro_assembler->CheckCharacter(chars[1], &ok);
1754 macro_assembler->CheckNotCharacter(chars[2], on_failure);
1755 macro_assembler->Bind(&ok);
1765 static void EmitBoundaryTest(RegExpMacroAssembler* masm,
1767 Label* fall_through,
1768 Label* above_or_equal,
1770 if (below != fall_through) {
1771 masm->CheckCharacterLT(border, below);
1772 if (above_or_equal != fall_through) masm->GoTo(above_or_equal);
1774 masm->CheckCharacterGT(border - 1, above_or_equal);
1779 static void EmitDoubleBoundaryTest(RegExpMacroAssembler* masm,
1782 Label* fall_through,
1784 Label* out_of_range) {
1785 if (in_range == fall_through) {
1786 if (first == last) {
1787 masm->CheckNotCharacter(first, out_of_range);
1789 masm->CheckCharacterNotInRange(first, last, out_of_range);
1792 if (first == last) {
1793 masm->CheckCharacter(first, in_range);
1795 masm->CheckCharacterInRange(first, last, in_range);
1797 if (out_of_range != fall_through) masm->GoTo(out_of_range);
1802 // even_label is for ranges[i] to ranges[i + 1] where i - start_index is even.
1803 // odd_label is for ranges[i] to ranges[i + 1] where i - start_index is odd.
1804 static void EmitUseLookupTable(
1805 RegExpMacroAssembler* masm,
1806 ZoneList<int>* ranges,
1810 Label* fall_through,
1813 static const int kSize = RegExpMacroAssembler::kTableSize;
1814 static const int kMask = RegExpMacroAssembler::kTableMask;
1816 int base = (min_char & ~kMask);
1819 // Assert that everything is on one kTableSize page.
1820 for (int i = start_index; i <= end_index; i++) {
1821 DCHECK_EQ(ranges->at(i) & ~kMask, base);
1823 DCHECK(start_index == 0 || (ranges->at(start_index - 1) & ~kMask) <= base);
1827 Label* on_bit_clear;
1829 if (even_label == fall_through) {
1830 on_bit_set = odd_label;
1831 on_bit_clear = even_label;
1834 on_bit_set = even_label;
1835 on_bit_clear = odd_label;
1838 for (int i = 0; i < (ranges->at(start_index) & kMask) && i < kSize; i++) {
1843 for (int i = start_index; i < end_index; i++) {
1844 for (j = (ranges->at(i) & kMask); j < (ranges->at(i + 1) & kMask); j++) {
1849 for (int i = j; i < kSize; i++) {
1852 Factory* factory = masm->zone()->isolate()->factory();
1853 // TODO(erikcorry): Cache these.
1854 Handle<ByteArray> ba = factory->NewByteArray(kSize, TENURED);
1855 for (int i = 0; i < kSize; i++) {
1856 ba->set(i, templ[i]);
1858 masm->CheckBitInTable(ba, on_bit_set);
1859 if (on_bit_clear != fall_through) masm->GoTo(on_bit_clear);
1863 static void CutOutRange(RegExpMacroAssembler* masm,
1864 ZoneList<int>* ranges,
1870 bool odd = (((cut_index - start_index) & 1) == 1);
1871 Label* in_range_label = odd ? odd_label : even_label;
1873 EmitDoubleBoundaryTest(masm,
1874 ranges->at(cut_index),
1875 ranges->at(cut_index + 1) - 1,
1879 DCHECK(!dummy.is_linked());
1880 // Cut out the single range by rewriting the array. This creates a new
1881 // range that is a merger of the two ranges on either side of the one we
1882 // are cutting out. The oddity of the labels is preserved.
1883 for (int j = cut_index; j > start_index; j--) {
1884 ranges->at(j) = ranges->at(j - 1);
1886 for (int j = cut_index + 1; j < end_index; j++) {
1887 ranges->at(j) = ranges->at(j + 1);
1892 // Unicode case. Split the search space into kSize spaces that are handled
1894 static void SplitSearchSpace(ZoneList<int>* ranges,
1897 int* new_start_index,
1900 static const int kSize = RegExpMacroAssembler::kTableSize;
1901 static const int kMask = RegExpMacroAssembler::kTableMask;
1903 int first = ranges->at(start_index);
1904 int last = ranges->at(end_index) - 1;
1906 *new_start_index = start_index;
1907 *border = (ranges->at(start_index) & ~kMask) + kSize;
1908 while (*new_start_index < end_index) {
1909 if (ranges->at(*new_start_index) > *border) break;
1910 (*new_start_index)++;
1912 // new_start_index is the index of the first edge that is beyond the
1913 // current kSize space.
1915 // For very large search spaces we do a binary chop search of the non-Latin1
1916 // space instead of just going to the end of the current kSize space. The
1917 // heuristics are complicated a little by the fact that any 128-character
1918 // encoding space can be quickly tested with a table lookup, so we don't
1919 // wish to do binary chop search at a smaller granularity than that. A
1920 // 128-character space can take up a lot of space in the ranges array if,
1921 // for example, we only want to match every second character (eg. the lower
1922 // case characters on some Unicode pages).
1923 int binary_chop_index = (end_index + start_index) / 2;
1924 // The first test ensures that we get to the code that handles the Latin1
1925 // range with a single not-taken branch, speeding up this important
1926 // character range (even non-Latin1 charset-based text has spaces and
1928 if (*border - 1 > String::kMaxOneByteCharCode && // Latin1 case.
1929 end_index - start_index > (*new_start_index - start_index) * 2 &&
1930 last - first > kSize * 2 && binary_chop_index > *new_start_index &&
1931 ranges->at(binary_chop_index) >= first + 2 * kSize) {
1932 int scan_forward_for_section_border = binary_chop_index;;
1933 int new_border = (ranges->at(binary_chop_index) | kMask) + 1;
1935 while (scan_forward_for_section_border < end_index) {
1936 if (ranges->at(scan_forward_for_section_border) > new_border) {
1937 *new_start_index = scan_forward_for_section_border;
1938 *border = new_border;
1941 scan_forward_for_section_border++;
1945 DCHECK(*new_start_index > start_index);
1946 *new_end_index = *new_start_index - 1;
1947 if (ranges->at(*new_end_index) == *border) {
1950 if (*border >= ranges->at(end_index)) {
1951 *border = ranges->at(end_index);
1952 *new_start_index = end_index; // Won't be used.
1953 *new_end_index = end_index - 1;
1958 // Gets a series of segment boundaries representing a character class. If the
1959 // character is in the range between an even and an odd boundary (counting from
1960 // start_index) then go to even_label, otherwise go to odd_label. We already
1961 // know that the character is in the range of min_char to max_char inclusive.
1962 // Either label can be NULL indicating backtracking. Either label can also be
1963 // equal to the fall_through label.
1964 static void GenerateBranches(RegExpMacroAssembler* masm,
1965 ZoneList<int>* ranges,
1970 Label* fall_through,
1973 int first = ranges->at(start_index);
1974 int last = ranges->at(end_index) - 1;
1976 DCHECK_LT(min_char, first);
1978 // Just need to test if the character is before or on-or-after
1979 // a particular character.
1980 if (start_index == end_index) {
1981 EmitBoundaryTest(masm, first, fall_through, even_label, odd_label);
1985 // Another almost trivial case: There is one interval in the middle that is
1986 // different from the end intervals.
1987 if (start_index + 1 == end_index) {
1988 EmitDoubleBoundaryTest(
1989 masm, first, last, fall_through, even_label, odd_label);
1993 // It's not worth using table lookup if there are very few intervals in the
1995 if (end_index - start_index <= 6) {
1996 // It is faster to test for individual characters, so we look for those
1997 // first, then try arbitrary ranges in the second round.
1998 static int kNoCutIndex = -1;
1999 int cut = kNoCutIndex;
2000 for (int i = start_index; i < end_index; i++) {
2001 if (ranges->at(i) == ranges->at(i + 1) - 1) {
2006 if (cut == kNoCutIndex) cut = start_index;
2008 masm, ranges, start_index, end_index, cut, even_label, odd_label);
2009 DCHECK_GE(end_index - start_index, 2);
2010 GenerateBranches(masm,
2022 // If there are a lot of intervals in the regexp, then we will use tables to
2023 // determine whether the character is inside or outside the character class.
2024 static const int kBits = RegExpMacroAssembler::kTableSizeBits;
2026 if ((max_char >> kBits) == (min_char >> kBits)) {
2027 EmitUseLookupTable(masm,
2038 if ((min_char >> kBits) != (first >> kBits)) {
2039 masm->CheckCharacterLT(first, odd_label);
2040 GenerateBranches(masm,
2052 int new_start_index = 0;
2053 int new_end_index = 0;
2056 SplitSearchSpace(ranges,
2064 Label* above = &handle_rest;
2065 if (border == last + 1) {
2066 // We didn't find any section that started after the limit, so everything
2067 // above the border is one of the terminal labels.
2068 above = (end_index & 1) != (start_index & 1) ? odd_label : even_label;
2069 DCHECK(new_end_index == end_index - 1);
2072 DCHECK_LE(start_index, new_end_index);
2073 DCHECK_LE(new_start_index, end_index);
2074 DCHECK_LT(start_index, new_start_index);
2075 DCHECK_LT(new_end_index, end_index);
2076 DCHECK(new_end_index + 1 == new_start_index ||
2077 (new_end_index + 2 == new_start_index &&
2078 border == ranges->at(new_end_index + 1)));
2079 DCHECK_LT(min_char, border - 1);
2080 DCHECK_LT(border, max_char);
2081 DCHECK_LT(ranges->at(new_end_index), border);
2082 DCHECK(border < ranges->at(new_start_index) ||
2083 (border == ranges->at(new_start_index) &&
2084 new_start_index == end_index &&
2085 new_end_index == end_index - 1 &&
2086 border == last + 1));
2087 DCHECK(new_start_index == 0 || border >= ranges->at(new_start_index - 1));
2089 masm->CheckCharacterGT(border - 1, above);
2091 GenerateBranches(masm,
2100 if (handle_rest.is_linked()) {
2101 masm->Bind(&handle_rest);
2102 bool flip = (new_start_index & 1) != (start_index & 1);
2103 GenerateBranches(masm,
2110 flip ? odd_label : even_label,
2111 flip ? even_label : odd_label);
2116 static void EmitCharClass(RegExpMacroAssembler* macro_assembler,
2117 RegExpCharacterClass* cc, bool one_byte,
2118 Label* on_failure, int cp_offset, bool check_offset,
2119 bool preloaded, Zone* zone) {
2120 ZoneList<CharacterRange>* ranges = cc->ranges(zone);
2121 if (!CharacterRange::IsCanonical(ranges)) {
2122 CharacterRange::Canonicalize(ranges);
2127 max_char = String::kMaxOneByteCharCode;
2129 max_char = String::kMaxUtf16CodeUnit;
2132 int range_count = ranges->length();
2134 int last_valid_range = range_count - 1;
2135 while (last_valid_range >= 0) {
2136 CharacterRange& range = ranges->at(last_valid_range);
2137 if (range.from() <= max_char) {
2143 if (last_valid_range < 0) {
2144 if (!cc->is_negated()) {
2145 macro_assembler->GoTo(on_failure);
2148 macro_assembler->CheckPosition(cp_offset, on_failure);
2153 if (last_valid_range == 0 &&
2154 ranges->at(0).IsEverything(max_char)) {
2155 if (cc->is_negated()) {
2156 macro_assembler->GoTo(on_failure);
2158 // This is a common case hit by non-anchored expressions.
2160 macro_assembler->CheckPosition(cp_offset, on_failure);
2165 if (last_valid_range == 0 &&
2166 !cc->is_negated() &&
2167 ranges->at(0).IsEverything(max_char)) {
2168 // This is a common case hit by non-anchored expressions.
2170 macro_assembler->CheckPosition(cp_offset, on_failure);
2176 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset);
2179 if (cc->is_standard(zone) &&
2180 macro_assembler->CheckSpecialCharacterClass(cc->standard_type(),
2186 // A new list with ascending entries. Each entry is a code unit
2187 // where there is a boundary between code units that are part of
2188 // the class and code units that are not. Normally we insert an
2189 // entry at zero which goes to the failure label, but if there
2190 // was already one there we fall through for success on that entry.
2191 // Subsequent entries have alternating meaning (success/failure).
2192 ZoneList<int>* range_boundaries =
2193 new(zone) ZoneList<int>(last_valid_range, zone);
2195 bool zeroth_entry_is_failure = !cc->is_negated();
2197 for (int i = 0; i <= last_valid_range; i++) {
2198 CharacterRange& range = ranges->at(i);
2199 if (range.from() == 0) {
2201 zeroth_entry_is_failure = !zeroth_entry_is_failure;
2203 range_boundaries->Add(range.from(), zone);
2205 range_boundaries->Add(range.to() + 1, zone);
2207 int end_index = range_boundaries->length() - 1;
2208 if (range_boundaries->at(end_index) > max_char) {
2213 GenerateBranches(macro_assembler,
2220 zeroth_entry_is_failure ? &fall_through : on_failure,
2221 zeroth_entry_is_failure ? on_failure : &fall_through);
2222 macro_assembler->Bind(&fall_through);
2226 RegExpNode::~RegExpNode() {
2230 RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler,
2232 // If we are generating a greedy loop then don't stop and don't reuse code.
2233 if (trace->stop_node() != NULL) {
2237 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2238 if (trace->is_trivial()) {
2239 if (label_.is_bound()) {
2240 // We are being asked to generate a generic version, but that's already
2241 // been done so just go to it.
2242 macro_assembler->GoTo(&label_);
2245 if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) {
2246 // To avoid too deep recursion we push the node to the work queue and just
2247 // generate a goto here.
2248 compiler->AddWork(this);
2249 macro_assembler->GoTo(&label_);
2252 // Generate generic version of the node and bind the label for later use.
2253 macro_assembler->Bind(&label_);
2257 // We are being asked to make a non-generic version. Keep track of how many
2258 // non-generic versions we generate so as not to overdo it.
2260 if (FLAG_regexp_optimization &&
2261 trace_count_ < kMaxCopiesCodeGenerated &&
2262 compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) {
2266 // If we get here code has been generated for this node too many times or
2267 // recursion is too deep. Time to switch to a generic version. The code for
2268 // generic versions above can handle deep recursion properly.
2269 trace->Flush(compiler, this);
2274 int ActionNode::EatsAtLeast(int still_to_find,
2276 bool not_at_start) {
2277 if (budget <= 0) return 0;
2278 if (action_type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input!
2279 return on_success()->EatsAtLeast(still_to_find,
2285 void ActionNode::FillInBMInfo(int offset,
2287 BoyerMooreLookahead* bm,
2288 bool not_at_start) {
2289 if (action_type_ == BEGIN_SUBMATCH) {
2290 bm->SetRest(offset);
2291 } else if (action_type_ != POSITIVE_SUBMATCH_SUCCESS) {
2292 on_success()->FillInBMInfo(offset, budget - 1, bm, not_at_start);
2294 SaveBMInfo(bm, not_at_start, offset);
2298 int AssertionNode::EatsAtLeast(int still_to_find,
2300 bool not_at_start) {
2301 if (budget <= 0) return 0;
2302 // If we know we are not at the start and we are asked "how many characters
2303 // will you match if you succeed?" then we can answer anything since false
2304 // implies false. So lets just return the max answer (still_to_find) since
2305 // that won't prevent us from preloading a lot of characters for the other
2306 // branches in the node graph.
2307 if (assertion_type() == AT_START && not_at_start) return still_to_find;
2308 return on_success()->EatsAtLeast(still_to_find,
2314 void AssertionNode::FillInBMInfo(int offset,
2316 BoyerMooreLookahead* bm,
2317 bool not_at_start) {
2318 // Match the behaviour of EatsAtLeast on this node.
2319 if (assertion_type() == AT_START && not_at_start) return;
2320 on_success()->FillInBMInfo(offset, budget - 1, bm, not_at_start);
2321 SaveBMInfo(bm, not_at_start, offset);
2325 int BackReferenceNode::EatsAtLeast(int still_to_find,
2327 bool not_at_start) {
2328 if (budget <= 0) return 0;
2329 return on_success()->EatsAtLeast(still_to_find,
2335 int TextNode::EatsAtLeast(int still_to_find,
2337 bool not_at_start) {
2338 int answer = Length();
2339 if (answer >= still_to_find) return answer;
2340 if (budget <= 0) return answer;
2341 // We are not at start after this node so we set the last argument to 'true'.
2342 return answer + on_success()->EatsAtLeast(still_to_find - answer,
2348 int NegativeLookaheadChoiceNode::EatsAtLeast(int still_to_find,
2350 bool not_at_start) {
2351 if (budget <= 0) return 0;
2352 // Alternative 0 is the negative lookahead, alternative 1 is what comes
2354 RegExpNode* node = alternatives_->at(1).node();
2355 return node->EatsAtLeast(still_to_find, budget - 1, not_at_start);
2359 void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
2360 QuickCheckDetails* details,
2361 RegExpCompiler* compiler,
2363 bool not_at_start) {
2364 // Alternative 0 is the negative lookahead, alternative 1 is what comes
2366 RegExpNode* node = alternatives_->at(1).node();
2367 return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
2371 int ChoiceNode::EatsAtLeastHelper(int still_to_find,
2373 RegExpNode* ignore_this_node,
2374 bool not_at_start) {
2375 if (budget <= 0) return 0;
2377 int choice_count = alternatives_->length();
2378 budget = (budget - 1) / choice_count;
2379 for (int i = 0; i < choice_count; i++) {
2380 RegExpNode* node = alternatives_->at(i).node();
2381 if (node == ignore_this_node) continue;
2382 int node_eats_at_least =
2383 node->EatsAtLeast(still_to_find, budget, not_at_start);
2384 if (node_eats_at_least < min) min = node_eats_at_least;
2385 if (min == 0) return 0;
2391 int LoopChoiceNode::EatsAtLeast(int still_to_find,
2393 bool not_at_start) {
2394 return EatsAtLeastHelper(still_to_find,
2401 int ChoiceNode::EatsAtLeast(int still_to_find,
2403 bool not_at_start) {
2404 return EatsAtLeastHelper(still_to_find,
2411 // Takes the left-most 1-bit and smears it out, setting all bits to its right.
2412 static inline uint32_t SmearBitsRight(uint32_t v) {
2422 bool QuickCheckDetails::Rationalize(bool asc) {
2423 bool found_useful_op = false;
2426 char_mask = String::kMaxOneByteCharCode;
2428 char_mask = String::kMaxUtf16CodeUnit;
2433 for (int i = 0; i < characters_; i++) {
2434 Position* pos = &positions_[i];
2435 if ((pos->mask & String::kMaxOneByteCharCode) != 0) {
2436 found_useful_op = true;
2438 mask_ |= (pos->mask & char_mask) << char_shift;
2439 value_ |= (pos->value & char_mask) << char_shift;
2440 char_shift += asc ? 8 : 16;
2442 return found_useful_op;
2446 bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
2447 Trace* bounds_check_trace,
2449 bool preload_has_checked_bounds,
2450 Label* on_possible_success,
2451 QuickCheckDetails* details,
2452 bool fall_through_on_failure) {
2453 if (details->characters() == 0) return false;
2454 GetQuickCheckDetails(
2455 details, compiler, 0, trace->at_start() == Trace::FALSE_VALUE);
2456 if (details->cannot_match()) return false;
2457 if (!details->Rationalize(compiler->one_byte())) return false;
2458 DCHECK(details->characters() == 1 ||
2459 compiler->macro_assembler()->CanReadUnaligned());
2460 uint32_t mask = details->mask();
2461 uint32_t value = details->value();
2463 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2465 if (trace->characters_preloaded() != details->characters()) {
2466 DCHECK(trace->cp_offset() == bounds_check_trace->cp_offset());
2467 // We are attempting to preload the minimum number of characters
2468 // any choice would eat, so if the bounds check fails, then none of the
2469 // choices can succeed, so we can just immediately backtrack, rather
2470 // than go to the next choice.
2471 assembler->LoadCurrentCharacter(trace->cp_offset(),
2472 bounds_check_trace->backtrack(),
2473 !preload_has_checked_bounds,
2474 details->characters());
2478 bool need_mask = true;
2480 if (details->characters() == 1) {
2481 // If number of characters preloaded is 1 then we used a byte or 16 bit
2482 // load so the value is already masked down.
2484 if (compiler->one_byte()) {
2485 char_mask = String::kMaxOneByteCharCode;
2487 char_mask = String::kMaxUtf16CodeUnit;
2489 if ((mask & char_mask) == char_mask) need_mask = false;
2492 // For 2-character preloads in one-byte mode or 1-character preloads in
2493 // two-byte mode we also use a 16 bit load with zero extend.
2494 if (details->characters() == 2 && compiler->one_byte()) {
2495 if ((mask & 0xffff) == 0xffff) need_mask = false;
2496 } else if (details->characters() == 1 && !compiler->one_byte()) {
2497 if ((mask & 0xffff) == 0xffff) need_mask = false;
2499 if (mask == 0xffffffff) need_mask = false;
2503 if (fall_through_on_failure) {
2505 assembler->CheckCharacterAfterAnd(value, mask, on_possible_success);
2507 assembler->CheckCharacter(value, on_possible_success);
2511 assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack());
2513 assembler->CheckNotCharacter(value, trace->backtrack());
2520 // Here is the meat of GetQuickCheckDetails (see also the comment on the
2521 // super-class in the .h file).
2523 // We iterate along the text object, building up for each character a
2524 // mask and value that can be used to test for a quick failure to match.
2525 // The masks and values for the positions will be combined into a single
2526 // machine word for the current character width in order to be used in
2527 // generating a quick check.
2528 void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
2529 RegExpCompiler* compiler,
2530 int characters_filled_in,
2531 bool not_at_start) {
2532 Isolate* isolate = compiler->macro_assembler()->zone()->isolate();
2533 DCHECK(characters_filled_in < details->characters());
2534 int characters = details->characters();
2536 if (compiler->one_byte()) {
2537 char_mask = String::kMaxOneByteCharCode;
2539 char_mask = String::kMaxUtf16CodeUnit;
2541 for (int k = 0; k < elms_->length(); k++) {
2542 TextElement elm = elms_->at(k);
2543 if (elm.text_type() == TextElement::ATOM) {
2544 Vector<const uc16> quarks = elm.atom()->data();
2545 for (int i = 0; i < characters && i < quarks.length(); i++) {
2546 QuickCheckDetails::Position* pos =
2547 details->positions(characters_filled_in);
2549 if (c > char_mask) {
2550 // If we expect a non-Latin1 character from an one-byte string,
2551 // there is no way we can match. Not even case-independent
2552 // matching can turn an Latin1 character into non-Latin1 or
2554 // TODO(dcarney): issue 3550. Verify that this works as expected.
2555 // For example, \u0178 is uppercase of \u00ff (y-umlaut).
2556 details->set_cannot_match();
2557 pos->determines_perfectly = false;
2560 if (compiler->ignore_case()) {
2561 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
2562 int length = GetCaseIndependentLetters(isolate, c,
2563 compiler->one_byte(), chars);
2564 DCHECK(length != 0); // Can only happen if c > char_mask (see above).
2566 // This letter has no case equivalents, so it's nice and simple
2567 // and the mask-compare will determine definitely whether we have
2568 // a match at this character position.
2569 pos->mask = char_mask;
2571 pos->determines_perfectly = true;
2573 uint32_t common_bits = char_mask;
2574 uint32_t bits = chars[0];
2575 for (int j = 1; j < length; j++) {
2576 uint32_t differing_bits = ((chars[j] & common_bits) ^ bits);
2577 common_bits ^= differing_bits;
2578 bits &= common_bits;
2580 // If length is 2 and common bits has only one zero in it then
2581 // our mask and compare instruction will determine definitely
2582 // whether we have a match at this character position. Otherwise
2583 // it can only be an approximate check.
2584 uint32_t one_zero = (common_bits | ~char_mask);
2585 if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) {
2586 pos->determines_perfectly = true;
2588 pos->mask = common_bits;
2592 // Don't ignore case. Nice simple case where the mask-compare will
2593 // determine definitely whether we have a match at this character
2595 pos->mask = char_mask;
2597 pos->determines_perfectly = true;
2599 characters_filled_in++;
2600 DCHECK(characters_filled_in <= details->characters());
2601 if (characters_filled_in == details->characters()) {
2606 QuickCheckDetails::Position* pos =
2607 details->positions(characters_filled_in);
2608 RegExpCharacterClass* tree = elm.char_class();
2609 ZoneList<CharacterRange>* ranges = tree->ranges(zone());
2610 if (tree->is_negated()) {
2611 // A quick check uses multi-character mask and compare. There is no
2612 // useful way to incorporate a negative char class into this scheme
2613 // so we just conservatively create a mask and value that will always
2618 int first_range = 0;
2619 while (ranges->at(first_range).from() > char_mask) {
2621 if (first_range == ranges->length()) {
2622 details->set_cannot_match();
2623 pos->determines_perfectly = false;
2627 CharacterRange range = ranges->at(first_range);
2628 uc16 from = range.from();
2629 uc16 to = range.to();
2630 if (to > char_mask) {
2633 uint32_t differing_bits = (from ^ to);
2634 // A mask and compare is only perfect if the differing bits form a
2635 // number like 00011111 with one single block of trailing 1s.
2636 if ((differing_bits & (differing_bits + 1)) == 0 &&
2637 from + differing_bits == to) {
2638 pos->determines_perfectly = true;
2640 uint32_t common_bits = ~SmearBitsRight(differing_bits);
2641 uint32_t bits = (from & common_bits);
2642 for (int i = first_range + 1; i < ranges->length(); i++) {
2643 CharacterRange range = ranges->at(i);
2644 uc16 from = range.from();
2645 uc16 to = range.to();
2646 if (from > char_mask) continue;
2647 if (to > char_mask) to = char_mask;
2648 // Here we are combining more ranges into the mask and compare
2649 // value. With each new range the mask becomes more sparse and
2650 // so the chances of a false positive rise. A character class
2651 // with multiple ranges is assumed never to be equivalent to a
2652 // mask and compare operation.
2653 pos->determines_perfectly = false;
2654 uint32_t new_common_bits = (from ^ to);
2655 new_common_bits = ~SmearBitsRight(new_common_bits);
2656 common_bits &= new_common_bits;
2657 bits &= new_common_bits;
2658 uint32_t differing_bits = (from & common_bits) ^ bits;
2659 common_bits ^= differing_bits;
2660 bits &= common_bits;
2662 pos->mask = common_bits;
2665 characters_filled_in++;
2666 DCHECK(characters_filled_in <= details->characters());
2667 if (characters_filled_in == details->characters()) {
2672 DCHECK(characters_filled_in != details->characters());
2673 if (!details->cannot_match()) {
2674 on_success()-> GetQuickCheckDetails(details,
2676 characters_filled_in,
2682 void QuickCheckDetails::Clear() {
2683 for (int i = 0; i < characters_; i++) {
2684 positions_[i].mask = 0;
2685 positions_[i].value = 0;
2686 positions_[i].determines_perfectly = false;
2692 void QuickCheckDetails::Advance(int by, bool one_byte) {
2694 if (by >= characters_) {
2698 for (int i = 0; i < characters_ - by; i++) {
2699 positions_[i] = positions_[by + i];
2701 for (int i = characters_ - by; i < characters_; i++) {
2702 positions_[i].mask = 0;
2703 positions_[i].value = 0;
2704 positions_[i].determines_perfectly = false;
2707 // We could change mask_ and value_ here but we would never advance unless
2708 // they had already been used in a check and they won't be used again because
2709 // it would gain us nothing. So there's no point.
2713 void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) {
2714 DCHECK(characters_ == other->characters_);
2715 if (other->cannot_match_) {
2718 if (cannot_match_) {
2722 for (int i = from_index; i < characters_; i++) {
2723 QuickCheckDetails::Position* pos = positions(i);
2724 QuickCheckDetails::Position* other_pos = other->positions(i);
2725 if (pos->mask != other_pos->mask ||
2726 pos->value != other_pos->value ||
2727 !other_pos->determines_perfectly) {
2728 // Our mask-compare operation will be approximate unless we have the
2729 // exact same operation on both sides of the alternation.
2730 pos->determines_perfectly = false;
2732 pos->mask &= other_pos->mask;
2733 pos->value &= pos->mask;
2734 other_pos->value &= pos->mask;
2735 uc16 differing_bits = (pos->value ^ other_pos->value);
2736 pos->mask &= ~differing_bits;
2737 pos->value &= pos->mask;
2744 explicit VisitMarker(NodeInfo* info) : info_(info) {
2745 DCHECK(!info->visited);
2746 info->visited = true;
2749 info_->visited = false;
2756 RegExpNode* SeqRegExpNode::FilterOneByte(int depth, bool ignore_case) {
2757 if (info()->replacement_calculated) return replacement();
2758 if (depth < 0) return this;
2759 DCHECK(!info()->visited);
2760 VisitMarker marker(info());
2761 return FilterSuccessor(depth - 1, ignore_case);
2765 RegExpNode* SeqRegExpNode::FilterSuccessor(int depth, bool ignore_case) {
2766 RegExpNode* next = on_success_->FilterOneByte(depth - 1, ignore_case);
2767 if (next == NULL) return set_replacement(NULL);
2769 return set_replacement(this);
2773 // We need to check for the following characters: 0x39c 0x3bc 0x178.
2774 static inline bool RangeContainsLatin1Equivalents(CharacterRange range) {
2775 // TODO(dcarney): this could be a lot more efficient.
2776 return range.Contains(0x39c) ||
2777 range.Contains(0x3bc) || range.Contains(0x178);
2781 static bool RangesContainLatin1Equivalents(ZoneList<CharacterRange>* ranges) {
2782 for (int i = 0; i < ranges->length(); i++) {
2783 // TODO(dcarney): this could be a lot more efficient.
2784 if (RangeContainsLatin1Equivalents(ranges->at(i))) return true;
2790 RegExpNode* TextNode::FilterOneByte(int depth, bool ignore_case) {
2791 if (info()->replacement_calculated) return replacement();
2792 if (depth < 0) return this;
2793 DCHECK(!info()->visited);
2794 VisitMarker marker(info());
2795 int element_count = elms_->length();
2796 for (int i = 0; i < element_count; i++) {
2797 TextElement elm = elms_->at(i);
2798 if (elm.text_type() == TextElement::ATOM) {
2799 Vector<const uc16> quarks = elm.atom()->data();
2800 for (int j = 0; j < quarks.length(); j++) {
2801 uint16_t c = quarks[j];
2802 if (c <= String::kMaxOneByteCharCode) continue;
2803 if (!ignore_case) return set_replacement(NULL);
2804 // Here, we need to check for characters whose upper and lower cases
2805 // are outside the Latin-1 range.
2806 uint16_t converted = unibrow::Latin1::ConvertNonLatin1ToLatin1(c);
2807 // Character is outside Latin-1 completely
2808 if (converted == 0) return set_replacement(NULL);
2809 // Convert quark to Latin-1 in place.
2810 uint16_t* copy = const_cast<uint16_t*>(quarks.start());
2811 copy[j] = converted;
2814 DCHECK(elm.text_type() == TextElement::CHAR_CLASS);
2815 RegExpCharacterClass* cc = elm.char_class();
2816 ZoneList<CharacterRange>* ranges = cc->ranges(zone());
2817 if (!CharacterRange::IsCanonical(ranges)) {
2818 CharacterRange::Canonicalize(ranges);
2820 // Now they are in order so we only need to look at the first.
2821 int range_count = ranges->length();
2822 if (cc->is_negated()) {
2823 if (range_count != 0 &&
2824 ranges->at(0).from() == 0 &&
2825 ranges->at(0).to() >= String::kMaxOneByteCharCode) {
2826 // This will be handled in a later filter.
2827 if (ignore_case && RangesContainLatin1Equivalents(ranges)) continue;
2828 return set_replacement(NULL);
2831 if (range_count == 0 ||
2832 ranges->at(0).from() > String::kMaxOneByteCharCode) {
2833 // This will be handled in a later filter.
2834 if (ignore_case && RangesContainLatin1Equivalents(ranges)) continue;
2835 return set_replacement(NULL);
2840 return FilterSuccessor(depth - 1, ignore_case);
2844 RegExpNode* LoopChoiceNode::FilterOneByte(int depth, bool ignore_case) {
2845 if (info()->replacement_calculated) return replacement();
2846 if (depth < 0) return this;
2847 if (info()->visited) return this;
2849 VisitMarker marker(info());
2851 RegExpNode* continue_replacement =
2852 continue_node_->FilterOneByte(depth - 1, ignore_case);
2853 // If we can't continue after the loop then there is no sense in doing the
2855 if (continue_replacement == NULL) return set_replacement(NULL);
2858 return ChoiceNode::FilterOneByte(depth - 1, ignore_case);
2862 RegExpNode* ChoiceNode::FilterOneByte(int depth, bool ignore_case) {
2863 if (info()->replacement_calculated) return replacement();
2864 if (depth < 0) return this;
2865 if (info()->visited) return this;
2866 VisitMarker marker(info());
2867 int choice_count = alternatives_->length();
2869 for (int i = 0; i < choice_count; i++) {
2870 GuardedAlternative alternative = alternatives_->at(i);
2871 if (alternative.guards() != NULL && alternative.guards()->length() != 0) {
2872 set_replacement(this);
2878 RegExpNode* survivor = NULL;
2879 for (int i = 0; i < choice_count; i++) {
2880 GuardedAlternative alternative = alternatives_->at(i);
2881 RegExpNode* replacement =
2882 alternative.node()->FilterOneByte(depth - 1, ignore_case);
2883 DCHECK(replacement != this); // No missing EMPTY_MATCH_CHECK.
2884 if (replacement != NULL) {
2885 alternatives_->at(i).set_node(replacement);
2887 survivor = replacement;
2890 if (surviving < 2) return set_replacement(survivor);
2892 set_replacement(this);
2893 if (surviving == choice_count) {
2896 // Only some of the nodes survived the filtering. We need to rebuild the
2897 // alternatives list.
2898 ZoneList<GuardedAlternative>* new_alternatives =
2899 new(zone()) ZoneList<GuardedAlternative>(surviving, zone());
2900 for (int i = 0; i < choice_count; i++) {
2901 RegExpNode* replacement =
2902 alternatives_->at(i).node()->FilterOneByte(depth - 1, ignore_case);
2903 if (replacement != NULL) {
2904 alternatives_->at(i).set_node(replacement);
2905 new_alternatives->Add(alternatives_->at(i), zone());
2908 alternatives_ = new_alternatives;
2913 RegExpNode* NegativeLookaheadChoiceNode::FilterOneByte(int depth,
2915 if (info()->replacement_calculated) return replacement();
2916 if (depth < 0) return this;
2917 if (info()->visited) return this;
2918 VisitMarker marker(info());
2919 // Alternative 0 is the negative lookahead, alternative 1 is what comes
2921 RegExpNode* node = alternatives_->at(1).node();
2922 RegExpNode* replacement = node->FilterOneByte(depth - 1, ignore_case);
2923 if (replacement == NULL) return set_replacement(NULL);
2924 alternatives_->at(1).set_node(replacement);
2926 RegExpNode* neg_node = alternatives_->at(0).node();
2927 RegExpNode* neg_replacement = neg_node->FilterOneByte(depth - 1, ignore_case);
2928 // If the negative lookahead is always going to fail then
2929 // we don't need to check it.
2930 if (neg_replacement == NULL) return set_replacement(replacement);
2931 alternatives_->at(0).set_node(neg_replacement);
2932 return set_replacement(this);
2936 void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2937 RegExpCompiler* compiler,
2938 int characters_filled_in,
2939 bool not_at_start) {
2940 if (body_can_be_zero_length_ || info()->visited) return;
2941 VisitMarker marker(info());
2942 return ChoiceNode::GetQuickCheckDetails(details,
2944 characters_filled_in,
2949 void LoopChoiceNode::FillInBMInfo(int offset,
2951 BoyerMooreLookahead* bm,
2952 bool not_at_start) {
2953 if (body_can_be_zero_length_ || budget <= 0) {
2954 bm->SetRest(offset);
2955 SaveBMInfo(bm, not_at_start, offset);
2958 ChoiceNode::FillInBMInfo(offset, budget - 1, bm, not_at_start);
2959 SaveBMInfo(bm, not_at_start, offset);
2963 void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2964 RegExpCompiler* compiler,
2965 int characters_filled_in,
2966 bool not_at_start) {
2967 not_at_start = (not_at_start || not_at_start_);
2968 int choice_count = alternatives_->length();
2969 DCHECK(choice_count > 0);
2970 alternatives_->at(0).node()->GetQuickCheckDetails(details,
2972 characters_filled_in,
2974 for (int i = 1; i < choice_count; i++) {
2975 QuickCheckDetails new_details(details->characters());
2976 RegExpNode* node = alternatives_->at(i).node();
2977 node->GetQuickCheckDetails(&new_details, compiler,
2978 characters_filled_in,
2980 // Here we merge the quick match details of the two branches.
2981 details->Merge(&new_details, characters_filled_in);
2986 // Check for [0-9A-Z_a-z].
2987 static void EmitWordCheck(RegExpMacroAssembler* assembler,
2990 bool fall_through_on_word) {
2991 if (assembler->CheckSpecialCharacterClass(
2992 fall_through_on_word ? 'w' : 'W',
2993 fall_through_on_word ? non_word : word)) {
2994 // Optimized implementation available.
2997 assembler->CheckCharacterGT('z', non_word);
2998 assembler->CheckCharacterLT('0', non_word);
2999 assembler->CheckCharacterGT('a' - 1, word);
3000 assembler->CheckCharacterLT('9' + 1, word);
3001 assembler->CheckCharacterLT('A', non_word);
3002 assembler->CheckCharacterLT('Z' + 1, word);
3003 if (fall_through_on_word) {
3004 assembler->CheckNotCharacter('_', non_word);
3006 assembler->CheckCharacter('_', word);
3011 // Emit the code to check for a ^ in multiline mode (1-character lookbehind
3012 // that matches newline or the start of input).
3013 static void EmitHat(RegExpCompiler* compiler,
3014 RegExpNode* on_success,
3016 RegExpMacroAssembler* assembler = compiler->macro_assembler();
3017 // We will be loading the previous character into the current character
3019 Trace new_trace(*trace);
3020 new_trace.InvalidateCurrentCharacter();
3023 if (new_trace.cp_offset() == 0) {
3024 // The start of input counts as a newline in this context, so skip to
3025 // ok if we are at the start.
3026 assembler->CheckAtStart(&ok);
3028 // We already checked that we are not at the start of input so it must be
3029 // OK to load the previous character.
3030 assembler->LoadCurrentCharacter(new_trace.cp_offset() -1,
3031 new_trace.backtrack(),
3033 if (!assembler->CheckSpecialCharacterClass('n',
3034 new_trace.backtrack())) {
3035 // Newline means \n, \r, 0x2028 or 0x2029.
3036 if (!compiler->one_byte()) {
3037 assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok);
3039 assembler->CheckCharacter('\n', &ok);
3040 assembler->CheckNotCharacter('\r', new_trace.backtrack());
3042 assembler->Bind(&ok);
3043 on_success->Emit(compiler, &new_trace);
3047 // Emit the code to handle \b and \B (word-boundary or non-word-boundary).
3048 void AssertionNode::EmitBoundaryCheck(RegExpCompiler* compiler, Trace* trace) {
3049 RegExpMacroAssembler* assembler = compiler->macro_assembler();
3050 Trace::TriBool next_is_word_character = Trace::UNKNOWN;
3051 bool not_at_start = (trace->at_start() == Trace::FALSE_VALUE);
3052 BoyerMooreLookahead* lookahead = bm_info(not_at_start);
3053 if (lookahead == NULL) {
3055 Min(kMaxLookaheadForBoyerMoore, EatsAtLeast(kMaxLookaheadForBoyerMoore,
3058 if (eats_at_least >= 1) {
3059 BoyerMooreLookahead* bm =
3060 new(zone()) BoyerMooreLookahead(eats_at_least, compiler, zone());
3061 FillInBMInfo(0, kRecursionBudget, bm, not_at_start);
3062 if (bm->at(0)->is_non_word())
3063 next_is_word_character = Trace::FALSE_VALUE;
3064 if (bm->at(0)->is_word()) next_is_word_character = Trace::TRUE_VALUE;
3067 if (lookahead->at(0)->is_non_word())
3068 next_is_word_character = Trace::FALSE_VALUE;
3069 if (lookahead->at(0)->is_word())
3070 next_is_word_character = Trace::TRUE_VALUE;
3072 bool at_boundary = (assertion_type_ == AssertionNode::AT_BOUNDARY);
3073 if (next_is_word_character == Trace::UNKNOWN) {
3074 Label before_non_word;
3076 if (trace->characters_preloaded() != 1) {
3077 assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word);
3079 // Fall through on non-word.
3080 EmitWordCheck(assembler, &before_word, &before_non_word, false);
3081 // Next character is not a word character.
3082 assembler->Bind(&before_non_word);
3084 BacktrackIfPrevious(compiler, trace, at_boundary ? kIsNonWord : kIsWord);
3085 assembler->GoTo(&ok);
3087 assembler->Bind(&before_word);
3088 BacktrackIfPrevious(compiler, trace, at_boundary ? kIsWord : kIsNonWord);
3089 assembler->Bind(&ok);
3090 } else if (next_is_word_character == Trace::TRUE_VALUE) {
3091 BacktrackIfPrevious(compiler, trace, at_boundary ? kIsWord : kIsNonWord);
3093 DCHECK(next_is_word_character == Trace::FALSE_VALUE);
3094 BacktrackIfPrevious(compiler, trace, at_boundary ? kIsNonWord : kIsWord);
3099 void AssertionNode::BacktrackIfPrevious(
3100 RegExpCompiler* compiler,
3102 AssertionNode::IfPrevious backtrack_if_previous) {
3103 RegExpMacroAssembler* assembler = compiler->macro_assembler();
3104 Trace new_trace(*trace);
3105 new_trace.InvalidateCurrentCharacter();
3107 Label fall_through, dummy;
3109 Label* non_word = backtrack_if_previous == kIsNonWord ?
3110 new_trace.backtrack() :
3112 Label* word = backtrack_if_previous == kIsNonWord ?
3114 new_trace.backtrack();
3116 if (new_trace.cp_offset() == 0) {
3117 // The start of input counts as a non-word character, so the question is
3118 // decided if we are at the start.
3119 assembler->CheckAtStart(non_word);
3121 // We already checked that we are not at the start of input so it must be
3122 // OK to load the previous character.
3123 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1, &dummy, false);
3124 EmitWordCheck(assembler, word, non_word, backtrack_if_previous == kIsNonWord);
3126 assembler->Bind(&fall_through);
3127 on_success()->Emit(compiler, &new_trace);
3131 void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details,
3132 RegExpCompiler* compiler,
3134 bool not_at_start) {
3135 if (assertion_type_ == AT_START && not_at_start) {
3136 details->set_cannot_match();
3139 return on_success()->GetQuickCheckDetails(details,
3146 void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3147 RegExpMacroAssembler* assembler = compiler->macro_assembler();
3148 switch (assertion_type_) {
3151 assembler->CheckPosition(trace->cp_offset(), &ok);
3152 assembler->GoTo(trace->backtrack());
3153 assembler->Bind(&ok);
3157 if (trace->at_start() == Trace::FALSE_VALUE) {
3158 assembler->GoTo(trace->backtrack());
3161 if (trace->at_start() == Trace::UNKNOWN) {
3162 assembler->CheckNotAtStart(trace->backtrack());
3163 Trace at_start_trace = *trace;
3164 at_start_trace.set_at_start(true);
3165 on_success()->Emit(compiler, &at_start_trace);
3171 EmitHat(compiler, on_success(), trace);
3174 case AT_NON_BOUNDARY: {
3175 EmitBoundaryCheck(compiler, trace);
3179 on_success()->Emit(compiler, trace);
3183 static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) {
3184 if (quick_check == NULL) return false;
3185 if (offset >= quick_check->characters()) return false;
3186 return quick_check->positions(offset)->determines_perfectly;
3190 static void UpdateBoundsCheck(int index, int* checked_up_to) {
3191 if (index > *checked_up_to) {
3192 *checked_up_to = index;
3197 // We call this repeatedly to generate code for each pass over the text node.
3198 // The passes are in increasing order of difficulty because we hope one
3199 // of the first passes will fail in which case we are saved the work of the
3200 // later passes. for example for the case independent regexp /%[asdfghjkl]a/
3201 // we will check the '%' in the first pass, the case independent 'a' in the
3202 // second pass and the character class in the last pass.
3204 // The passes are done from right to left, so for example to test for /bar/
3205 // we will first test for an 'r' with offset 2, then an 'a' with offset 1
3206 // and then a 'b' with offset 0. This means we can avoid the end-of-input
3207 // bounds check most of the time. In the example we only need to check for
3208 // end-of-input when loading the putative 'r'.
3210 // A slight complication involves the fact that the first character may already
3211 // be fetched into a register by the previous node. In this case we want to
3212 // do the test for that character first. We do this in separate passes. The
3213 // 'preloaded' argument indicates that we are doing such a 'pass'. If such a
3214 // pass has been performed then subsequent passes will have true in
3215 // first_element_checked to indicate that that character does not need to be
3218 // In addition to all this we are passed a Trace, which can
3219 // contain an AlternativeGeneration object. In this AlternativeGeneration
3220 // object we can see details of any quick check that was already passed in
3221 // order to get to the code we are now generating. The quick check can involve
3222 // loading characters, which means we do not need to recheck the bounds
3223 // up to the limit the quick check already checked. In addition the quick
3224 // check can have involved a mask and compare operation which may simplify
3225 // or obviate the need for further checks at some character positions.
3226 void TextNode::TextEmitPass(RegExpCompiler* compiler,
3227 TextEmitPassType pass,
3230 bool first_element_checked,
3231 int* checked_up_to) {
3232 RegExpMacroAssembler* assembler = compiler->macro_assembler();
3233 Isolate* isolate = assembler->zone()->isolate();
3234 bool one_byte = compiler->one_byte();
3235 Label* backtrack = trace->backtrack();
3236 QuickCheckDetails* quick_check = trace->quick_check_performed();
3237 int element_count = elms_->length();
3238 for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) {
3239 TextElement elm = elms_->at(i);
3240 int cp_offset = trace->cp_offset() + elm.cp_offset();
3241 if (elm.text_type() == TextElement::ATOM) {
3242 Vector<const uc16> quarks = elm.atom()->data();
3243 for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) {
3244 if (first_element_checked && i == 0 && j == 0) continue;
3245 if (DeterminedAlready(quick_check, elm.cp_offset() + j)) continue;
3246 EmitCharacterFunction* emit_function = NULL;
3248 case NON_LATIN1_MATCH:
3250 if (quarks[j] > String::kMaxOneByteCharCode) {
3251 assembler->GoTo(backtrack);
3255 case NON_LETTER_CHARACTER_MATCH:
3256 emit_function = &EmitAtomNonLetter;
3258 case SIMPLE_CHARACTER_MATCH:
3259 emit_function = &EmitSimpleCharacter;
3261 case CASE_CHARACTER_MATCH:
3262 emit_function = &EmitAtomLetter;
3267 if (emit_function != NULL) {
3268 bool bound_checked = emit_function(isolate,
3273 *checked_up_to < cp_offset + j,
3275 if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
3279 DCHECK_EQ(TextElement::CHAR_CLASS, elm.text_type());
3280 if (pass == CHARACTER_CLASS_MATCH) {
3281 if (first_element_checked && i == 0) continue;
3282 if (DeterminedAlready(quick_check, elm.cp_offset())) continue;
3283 RegExpCharacterClass* cc = elm.char_class();
3284 EmitCharClass(assembler, cc, one_byte, backtrack, cp_offset,
3285 *checked_up_to < cp_offset, preloaded, zone());
3286 UpdateBoundsCheck(cp_offset, checked_up_to);
3293 int TextNode::Length() {
3294 TextElement elm = elms_->last();
3295 DCHECK(elm.cp_offset() >= 0);
3296 return elm.cp_offset() + elm.length();
3300 bool TextNode::SkipPass(int int_pass, bool ignore_case) {
3301 TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass);
3303 return pass == SIMPLE_CHARACTER_MATCH;
3305 return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH;
3310 // This generates the code to match a text node. A text node can contain
3311 // straight character sequences (possibly to be matched in a case-independent
3312 // way) and character classes. For efficiency we do not do this in a single
3313 // pass from left to right. Instead we pass over the text node several times,
3314 // emitting code for some character positions every time. See the comment on
3315 // TextEmitPass for details.
3316 void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3317 LimitResult limit_result = LimitVersions(compiler, trace);
3318 if (limit_result == DONE) return;
3319 DCHECK(limit_result == CONTINUE);
3321 if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
3322 compiler->SetRegExpTooBig();
3326 if (compiler->one_byte()) {
3328 TextEmitPass(compiler, NON_LATIN1_MATCH, false, trace, false, &dummy);
3331 bool first_elt_done = false;
3332 int bound_checked_to = trace->cp_offset() - 1;
3333 bound_checked_to += trace->bound_checked_up_to();
3335 // If a character is preloaded into the current character register then
3337 if (trace->characters_preloaded() == 1) {
3338 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
3339 if (!SkipPass(pass, compiler->ignore_case())) {
3340 TextEmitPass(compiler,
3341 static_cast<TextEmitPassType>(pass),
3348 first_elt_done = true;
3351 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
3352 if (!SkipPass(pass, compiler->ignore_case())) {
3353 TextEmitPass(compiler,
3354 static_cast<TextEmitPassType>(pass),
3362 Trace successor_trace(*trace);
3363 successor_trace.set_at_start(false);
3364 successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler);
3365 RecursionCheck rc(compiler);
3366 on_success()->Emit(compiler, &successor_trace);
3370 void Trace::InvalidateCurrentCharacter() {
3371 characters_preloaded_ = 0;
3375 void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) {
3377 // We don't have an instruction for shifting the current character register
3378 // down or for using a shifted value for anything so lets just forget that
3379 // we preloaded any characters into it.
3380 characters_preloaded_ = 0;
3381 // Adjust the offsets of the quick check performed information. This
3382 // information is used to find out what we already determined about the
3383 // characters by means of mask and compare.
3384 quick_check_performed_.Advance(by, compiler->one_byte());
3386 if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
3387 compiler->SetRegExpTooBig();
3390 bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
3394 void TextNode::MakeCaseIndependent(bool is_one_byte) {
3395 int element_count = elms_->length();
3396 for (int i = 0; i < element_count; i++) {
3397 TextElement elm = elms_->at(i);
3398 if (elm.text_type() == TextElement::CHAR_CLASS) {
3399 RegExpCharacterClass* cc = elm.char_class();
3400 // None of the standard character classes is different in the case
3401 // independent case and it slows us down if we don't know that.
3402 if (cc->is_standard(zone())) continue;
3403 ZoneList<CharacterRange>* ranges = cc->ranges(zone());
3404 int range_count = ranges->length();
3405 for (int j = 0; j < range_count; j++) {
3406 ranges->at(j).AddCaseEquivalents(ranges, is_one_byte, zone());
3413 int TextNode::GreedyLoopTextLength() {
3414 TextElement elm = elms_->at(elms_->length() - 1);
3415 return elm.cp_offset() + elm.length();
3419 RegExpNode* TextNode::GetSuccessorOfOmnivorousTextNode(
3420 RegExpCompiler* compiler) {
3421 if (elms_->length() != 1) return NULL;
3422 TextElement elm = elms_->at(0);
3423 if (elm.text_type() != TextElement::CHAR_CLASS) return NULL;
3424 RegExpCharacterClass* node = elm.char_class();
3425 ZoneList<CharacterRange>* ranges = node->ranges(zone());
3426 if (!CharacterRange::IsCanonical(ranges)) {
3427 CharacterRange::Canonicalize(ranges);
3429 if (node->is_negated()) {
3430 return ranges->length() == 0 ? on_success() : NULL;
3432 if (ranges->length() != 1) return NULL;
3434 if (compiler->one_byte()) {
3435 max_char = String::kMaxOneByteCharCode;
3437 max_char = String::kMaxUtf16CodeUnit;
3439 return ranges->at(0).IsEverything(max_char) ? on_success() : NULL;
3443 // Finds the fixed match length of a sequence of nodes that goes from
3444 // this alternative and back to this choice node. If there are variable
3445 // length nodes or other complications in the way then return a sentinel
3446 // value indicating that a greedy loop cannot be constructed.
3447 int ChoiceNode::GreedyLoopTextLengthForAlternative(
3448 GuardedAlternative* alternative) {
3450 RegExpNode* node = alternative->node();
3451 // Later we will generate code for all these text nodes using recursion
3452 // so we have to limit the max number.
3453 int recursion_depth = 0;
3454 while (node != this) {
3455 if (recursion_depth++ > RegExpCompiler::kMaxRecursion) {
3456 return kNodeIsTooComplexForGreedyLoops;
3458 int node_length = node->GreedyLoopTextLength();
3459 if (node_length == kNodeIsTooComplexForGreedyLoops) {
3460 return kNodeIsTooComplexForGreedyLoops;
3462 length += node_length;
3463 SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node);
3464 node = seq_node->on_success();
3470 void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
3471 DCHECK_EQ(loop_node_, NULL);
3472 AddAlternative(alt);
3473 loop_node_ = alt.node();
3477 void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
3478 DCHECK_EQ(continue_node_, NULL);
3479 AddAlternative(alt);
3480 continue_node_ = alt.node();
3484 void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3485 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
3486 if (trace->stop_node() == this) {
3487 // Back edge of greedy optimized loop node graph.
3489 GreedyLoopTextLengthForAlternative(&(alternatives_->at(0)));
3490 DCHECK(text_length != kNodeIsTooComplexForGreedyLoops);
3491 // Update the counter-based backtracking info on the stack. This is an
3492 // optimization for greedy loops (see below).
3493 DCHECK(trace->cp_offset() == text_length);
3494 macro_assembler->AdvanceCurrentPosition(text_length);
3495 macro_assembler->GoTo(trace->loop_label());
3498 DCHECK(trace->stop_node() == NULL);
3499 if (!trace->is_trivial()) {
3500 trace->Flush(compiler, this);
3503 ChoiceNode::Emit(compiler, trace);
3507 int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler,
3508 int eats_at_least) {
3509 int preload_characters = Min(4, eats_at_least);
3510 if (compiler->macro_assembler()->CanReadUnaligned()) {
3511 bool one_byte = compiler->one_byte();
3513 if (preload_characters > 4) preload_characters = 4;
3514 // We can't preload 3 characters because there is no machine instruction
3515 // to do that. We can't just load 4 because we could be reading
3516 // beyond the end of the string, which could cause a memory fault.
3517 if (preload_characters == 3) preload_characters = 2;
3519 if (preload_characters > 2) preload_characters = 2;
3522 if (preload_characters > 1) preload_characters = 1;
3524 return preload_characters;
3528 // This class is used when generating the alternatives in a choice node. It
3529 // records the way the alternative is being code generated.
3530 class AlternativeGeneration: public Malloced {
3532 AlternativeGeneration()
3533 : possible_success(),
3534 expects_preload(false),
3536 quick_check_details() { }
3537 Label possible_success;
3538 bool expects_preload;
3540 QuickCheckDetails quick_check_details;
3544 // Creates a list of AlternativeGenerations. If the list has a reasonable
3545 // size then it is on the stack, otherwise the excess is on the heap.
3546 class AlternativeGenerationList {
3548 AlternativeGenerationList(int count, Zone* zone)
3549 : alt_gens_(count, zone) {
3550 for (int i = 0; i < count && i < kAFew; i++) {
3551 alt_gens_.Add(a_few_alt_gens_ + i, zone);
3553 for (int i = kAFew; i < count; i++) {
3554 alt_gens_.Add(new AlternativeGeneration(), zone);
3557 ~AlternativeGenerationList() {
3558 for (int i = kAFew; i < alt_gens_.length(); i++) {
3559 delete alt_gens_[i];
3560 alt_gens_[i] = NULL;
3564 AlternativeGeneration* at(int i) {
3565 return alt_gens_[i];
3569 static const int kAFew = 10;
3570 ZoneList<AlternativeGeneration*> alt_gens_;
3571 AlternativeGeneration a_few_alt_gens_[kAFew];
3575 // The '2' variant is has inclusive from and exclusive to.
3576 // This covers \s as defined in ECMA-262 5.1, 15.10.2.12,
3577 // which include WhiteSpace (7.2) or LineTerminator (7.3) values.
3578 static const int kSpaceRanges[] = { '\t', '\r' + 1, ' ', ' ' + 1,
3579 0x00A0, 0x00A1, 0x1680, 0x1681, 0x180E, 0x180F, 0x2000, 0x200B,
3580 0x2028, 0x202A, 0x202F, 0x2030, 0x205F, 0x2060, 0x3000, 0x3001,
3581 0xFEFF, 0xFF00, 0x10000 };
3582 static const int kSpaceRangeCount = arraysize(kSpaceRanges);
3584 static const int kWordRanges[] = {
3585 '0', '9' + 1, 'A', 'Z' + 1, '_', '_' + 1, 'a', 'z' + 1, 0x10000 };
3586 static const int kWordRangeCount = arraysize(kWordRanges);
3587 static const int kDigitRanges[] = { '0', '9' + 1, 0x10000 };
3588 static const int kDigitRangeCount = arraysize(kDigitRanges);
3589 static const int kSurrogateRanges[] = { 0xd800, 0xe000, 0x10000 };
3590 static const int kSurrogateRangeCount = arraysize(kSurrogateRanges);
3591 static const int kLineTerminatorRanges[] = { 0x000A, 0x000B, 0x000D, 0x000E,
3592 0x2028, 0x202A, 0x10000 };
3593 static const int kLineTerminatorRangeCount = arraysize(kLineTerminatorRanges);
3596 void BoyerMoorePositionInfo::Set(int character) {
3597 SetInterval(Interval(character, character));
3601 void BoyerMoorePositionInfo::SetInterval(const Interval& interval) {
3602 s_ = AddRange(s_, kSpaceRanges, kSpaceRangeCount, interval);
3603 w_ = AddRange(w_, kWordRanges, kWordRangeCount, interval);
3604 d_ = AddRange(d_, kDigitRanges, kDigitRangeCount, interval);
3606 AddRange(surrogate_, kSurrogateRanges, kSurrogateRangeCount, interval);
3607 if (interval.to() - interval.from() >= kMapSize - 1) {
3608 if (map_count_ != kMapSize) {
3609 map_count_ = kMapSize;
3610 for (int i = 0; i < kMapSize; i++) map_->at(i) = true;
3614 for (int i = interval.from(); i <= interval.to(); i++) {
3615 int mod_character = (i & kMask);
3616 if (!map_->at(mod_character)) {
3618 map_->at(mod_character) = true;
3620 if (map_count_ == kMapSize) return;
3625 void BoyerMoorePositionInfo::SetAll() {
3626 s_ = w_ = d_ = kLatticeUnknown;
3627 if (map_count_ != kMapSize) {
3628 map_count_ = kMapSize;
3629 for (int i = 0; i < kMapSize; i++) map_->at(i) = true;
3634 BoyerMooreLookahead::BoyerMooreLookahead(
3635 int length, RegExpCompiler* compiler, Zone* zone)
3637 compiler_(compiler) {
3638 if (compiler->one_byte()) {
3639 max_char_ = String::kMaxOneByteCharCode;
3641 max_char_ = String::kMaxUtf16CodeUnit;
3643 bitmaps_ = new(zone) ZoneList<BoyerMoorePositionInfo*>(length, zone);
3644 for (int i = 0; i < length; i++) {
3645 bitmaps_->Add(new(zone) BoyerMoorePositionInfo(zone), zone);
3650 // Find the longest range of lookahead that has the fewest number of different
3651 // characters that can occur at a given position. Since we are optimizing two
3652 // different parameters at once this is a tradeoff.
3653 bool BoyerMooreLookahead::FindWorthwhileInterval(int* from, int* to) {
3654 int biggest_points = 0;
3655 // If more than 32 characters out of 128 can occur it is unlikely that we can
3656 // be lucky enough to step forwards much of the time.
3657 const int kMaxMax = 32;
3658 for (int max_number_of_chars = 4;
3659 max_number_of_chars < kMaxMax;
3660 max_number_of_chars *= 2) {
3662 FindBestInterval(max_number_of_chars, biggest_points, from, to);
3664 if (biggest_points == 0) return false;
3669 // Find the highest-points range between 0 and length_ where the character
3670 // information is not too vague. 'Too vague' means that there are more than
3671 // max_number_of_chars that can occur at this position. Calculates the number
3672 // of points as the product of width-of-the-range and
3673 // probability-of-finding-one-of-the-characters, where the probability is
3674 // calculated using the frequency distribution of the sample subject string.
3675 int BoyerMooreLookahead::FindBestInterval(
3676 int max_number_of_chars, int old_biggest_points, int* from, int* to) {
3677 int biggest_points = old_biggest_points;
3678 static const int kSize = RegExpMacroAssembler::kTableSize;
3679 for (int i = 0; i < length_; ) {
3680 while (i < length_ && Count(i) > max_number_of_chars) i++;
3681 if (i == length_) break;
3682 int remembered_from = i;
3683 bool union_map[kSize];
3684 for (int j = 0; j < kSize; j++) union_map[j] = false;
3685 while (i < length_ && Count(i) <= max_number_of_chars) {
3686 BoyerMoorePositionInfo* map = bitmaps_->at(i);
3687 for (int j = 0; j < kSize; j++) union_map[j] |= map->at(j);
3691 for (int j = 0; j < kSize; j++) {
3693 // Add 1 to the frequency to give a small per-character boost for
3694 // the cases where our sampling is not good enough and many
3695 // characters have a frequency of zero. This means the frequency
3696 // can theoretically be up to 2*kSize though we treat it mostly as
3697 // a fraction of kSize.
3698 frequency += compiler_->frequency_collator()->Frequency(j) + 1;
3701 // We use the probability of skipping times the distance we are skipping to
3702 // judge the effectiveness of this. Actually we have a cut-off: By
3703 // dividing by 2 we switch off the skipping if the probability of skipping
3704 // is less than 50%. This is because the multibyte mask-and-compare
3705 // skipping in quickcheck is more likely to do well on this case.
3706 bool in_quickcheck_range =
3707 ((i - remembered_from < 4) ||
3708 (compiler_->one_byte() ? remembered_from <= 4 : remembered_from <= 2));
3709 // Called 'probability' but it is only a rough estimate and can actually
3710 // be outside the 0-kSize range.
3711 int probability = (in_quickcheck_range ? kSize / 2 : kSize) - frequency;
3712 int points = (i - remembered_from) * probability;
3713 if (points > biggest_points) {
3714 *from = remembered_from;
3716 biggest_points = points;
3719 return biggest_points;
3723 // Take all the characters that will not prevent a successful match if they
3724 // occur in the subject string in the range between min_lookahead and
3725 // max_lookahead (inclusive) measured from the current position. If the
3726 // character at max_lookahead offset is not one of these characters, then we
3727 // can safely skip forwards by the number of characters in the range.
3728 int BoyerMooreLookahead::GetSkipTable(int min_lookahead,
3730 Handle<ByteArray> boolean_skip_table) {
3731 const int kSize = RegExpMacroAssembler::kTableSize;
3733 const int kSkipArrayEntry = 0;
3734 const int kDontSkipArrayEntry = 1;
3736 for (int i = 0; i < kSize; i++) {
3737 boolean_skip_table->set(i, kSkipArrayEntry);
3739 int skip = max_lookahead + 1 - min_lookahead;
3741 for (int i = max_lookahead; i >= min_lookahead; i--) {
3742 BoyerMoorePositionInfo* map = bitmaps_->at(i);
3743 for (int j = 0; j < kSize; j++) {
3745 boolean_skip_table->set(j, kDontSkipArrayEntry);
3754 // See comment above on the implementation of GetSkipTable.
3755 void BoyerMooreLookahead::EmitSkipInstructions(RegExpMacroAssembler* masm) {
3756 const int kSize = RegExpMacroAssembler::kTableSize;
3758 int min_lookahead = 0;
3759 int max_lookahead = 0;
3761 if (!FindWorthwhileInterval(&min_lookahead, &max_lookahead)) return;
3763 bool found_single_character = false;
3764 int single_character = 0;
3765 for (int i = max_lookahead; i >= min_lookahead; i--) {
3766 BoyerMoorePositionInfo* map = bitmaps_->at(i);
3767 if (map->map_count() > 1 ||
3768 (found_single_character && map->map_count() != 0)) {
3769 found_single_character = false;
3772 for (int j = 0; j < kSize; j++) {
3774 found_single_character = true;
3775 single_character = j;
3781 int lookahead_width = max_lookahead + 1 - min_lookahead;
3783 if (found_single_character && lookahead_width == 1 && max_lookahead < 3) {
3784 // The mask-compare can probably handle this better.
3788 if (found_single_character) {
3791 masm->LoadCurrentCharacter(max_lookahead, &cont, true);
3792 if (max_char_ > kSize) {
3793 masm->CheckCharacterAfterAnd(single_character,
3794 RegExpMacroAssembler::kTableMask,
3797 masm->CheckCharacter(single_character, &cont);
3799 masm->AdvanceCurrentPosition(lookahead_width);
3805 Factory* factory = masm->zone()->isolate()->factory();
3806 Handle<ByteArray> boolean_skip_table = factory->NewByteArray(kSize, TENURED);
3807 int skip_distance = GetSkipTable(
3808 min_lookahead, max_lookahead, boolean_skip_table);
3809 DCHECK(skip_distance != 0);
3813 masm->LoadCurrentCharacter(max_lookahead, &cont, true);
3814 masm->CheckBitInTable(boolean_skip_table, &cont);
3815 masm->AdvanceCurrentPosition(skip_distance);
3821 /* Code generation for choice nodes.
3823 * We generate quick checks that do a mask and compare to eliminate a
3824 * choice. If the quick check succeeds then it jumps to the continuation to
3825 * do slow checks and check subsequent nodes. If it fails (the common case)
3826 * it falls through to the next choice.
3828 * Here is the desired flow graph. Nodes directly below each other imply
3829 * fallthrough. Alternatives 1 and 2 have quick checks. Alternative
3830 * 3 doesn't have a quick check so we have to call the slow check.
3831 * Nodes are marked Qn for quick checks and Sn for slow checks. The entire
3832 * regexp continuation is generated directly after the Sn node, up to the
3833 * next GoTo if we decide to reuse some already generated code. Some
3834 * nodes expect preload_characters to be preloaded into the current
3835 * character register. R nodes do this preloading. Vertices are marked
3836 * F for failures and S for success (possible success in the case of quick
3837 * nodes). L, V, < and > are used as arrow heads.
3871 * For greedy loops we push the current position, then generate the code that
3872 * eats the input specially in EmitGreedyLoop. The other choice (the
3873 * continuation) is generated by the normal code in EmitChoices, and steps back
3874 * in the input to the starting position when it fails to match. The loop code
3875 * looks like this (U is the unwind code that steps back in the greedy loop).
3888 * Q2 ---> U----->backtrack
3895 GreedyLoopState::GreedyLoopState(bool not_at_start) {
3896 counter_backtrack_trace_.set_backtrack(&label_);
3897 if (not_at_start) counter_backtrack_trace_.set_at_start(false);
3901 void ChoiceNode::AssertGuardsMentionRegisters(Trace* trace) {
3903 int choice_count = alternatives_->length();
3904 for (int i = 0; i < choice_count - 1; i++) {
3905 GuardedAlternative alternative = alternatives_->at(i);
3906 ZoneList<Guard*>* guards = alternative.guards();
3907 int guard_count = (guards == NULL) ? 0 : guards->length();
3908 for (int j = 0; j < guard_count; j++) {
3909 DCHECK(!trace->mentions_reg(guards->at(j)->reg()));
3916 void ChoiceNode::SetUpPreLoad(RegExpCompiler* compiler,
3917 Trace* current_trace,
3918 PreloadState* state) {
3919 if (state->eats_at_least_ == PreloadState::kEatsAtLeastNotYetInitialized) {
3920 // Save some time by looking at most one machine word ahead.
3921 state->eats_at_least_ =
3922 EatsAtLeast(compiler->one_byte() ? 4 : 2, kRecursionBudget,
3923 current_trace->at_start() == Trace::FALSE_VALUE);
3925 state->preload_characters_ =
3926 CalculatePreloadCharacters(compiler, state->eats_at_least_);
3928 state->preload_is_current_ =
3929 (current_trace->characters_preloaded() == state->preload_characters_);
3930 state->preload_has_checked_bounds_ = state->preload_is_current_;
3934 void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3935 int choice_count = alternatives_->length();
3937 AssertGuardsMentionRegisters(trace);
3939 LimitResult limit_result = LimitVersions(compiler, trace);
3940 if (limit_result == DONE) return;
3941 DCHECK(limit_result == CONTINUE);
3943 // For loop nodes we already flushed (see LoopChoiceNode::Emit), but for
3944 // other choice nodes we only flush if we are out of code size budget.
3945 if (trace->flush_budget() == 0 && trace->actions() != NULL) {
3946 trace->Flush(compiler, this);
3950 RecursionCheck rc(compiler);
3952 PreloadState preload;
3954 GreedyLoopState greedy_loop_state(not_at_start());
3956 int text_length = GreedyLoopTextLengthForAlternative(&alternatives_->at(0));
3957 AlternativeGenerationList alt_gens(choice_count, zone());
3959 if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) {
3960 trace = EmitGreedyLoop(compiler,
3967 // TODO(erikcorry): Delete this. We don't need this label, but it makes us
3968 // match the traces produced pre-cleanup.
3969 Label second_choice;
3970 compiler->macro_assembler()->Bind(&second_choice);
3972 preload.eats_at_least_ = EmitOptimizedUnanchoredSearch(compiler, trace);
3974 EmitChoices(compiler,
3981 // At this point we need to generate slow checks for the alternatives where
3982 // the quick check was inlined. We can recognize these because the associated
3984 int new_flush_budget = trace->flush_budget() / choice_count;
3985 for (int i = 0; i < choice_count; i++) {
3986 AlternativeGeneration* alt_gen = alt_gens.at(i);
3987 Trace new_trace(*trace);
3988 // If there are actions to be flushed we have to limit how many times
3989 // they are flushed. Take the budget of the parent trace and distribute
3990 // it fairly amongst the children.
3991 if (new_trace.actions() != NULL) {
3992 new_trace.set_flush_budget(new_flush_budget);
3994 bool next_expects_preload =
3995 i == choice_count - 1 ? false : alt_gens.at(i + 1)->expects_preload;
3996 EmitOutOfLineContinuation(compiler,
3998 alternatives_->at(i),
4000 preload.preload_characters_,
4001 next_expects_preload);
4006 Trace* ChoiceNode::EmitGreedyLoop(RegExpCompiler* compiler,
4008 AlternativeGenerationList* alt_gens,
4009 PreloadState* preload,
4010 GreedyLoopState* greedy_loop_state,
4012 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
4013 // Here we have special handling for greedy loops containing only text nodes
4014 // and other simple nodes. These are handled by pushing the current
4015 // position on the stack and then incrementing the current position each
4016 // time around the switch. On backtrack we decrement the current position
4017 // and check it against the pushed value. This avoids pushing backtrack
4018 // information for each iteration of the loop, which could take up a lot of
4020 DCHECK(trace->stop_node() == NULL);
4021 macro_assembler->PushCurrentPosition();
4022 Label greedy_match_failed;
4023 Trace greedy_match_trace;
4024 if (not_at_start()) greedy_match_trace.set_at_start(false);
4025 greedy_match_trace.set_backtrack(&greedy_match_failed);
4027 macro_assembler->Bind(&loop_label);
4028 greedy_match_trace.set_stop_node(this);
4029 greedy_match_trace.set_loop_label(&loop_label);
4030 alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
4031 macro_assembler->Bind(&greedy_match_failed);
4033 Label second_choice; // For use in greedy matches.
4034 macro_assembler->Bind(&second_choice);
4036 Trace* new_trace = greedy_loop_state->counter_backtrack_trace();
4038 EmitChoices(compiler,
4044 macro_assembler->Bind(greedy_loop_state->label());
4045 // If we have unwound to the bottom then backtrack.
4046 macro_assembler->CheckGreedyLoop(trace->backtrack());
4047 // Otherwise try the second priority at an earlier position.
4048 macro_assembler->AdvanceCurrentPosition(-text_length);
4049 macro_assembler->GoTo(&second_choice);
4053 int ChoiceNode::EmitOptimizedUnanchoredSearch(RegExpCompiler* compiler,
4055 int eats_at_least = PreloadState::kEatsAtLeastNotYetInitialized;
4056 if (alternatives_->length() != 2) return eats_at_least;
4058 GuardedAlternative alt1 = alternatives_->at(1);
4059 if (alt1.guards() != NULL && alt1.guards()->length() != 0) {
4060 return eats_at_least;
4062 RegExpNode* eats_anything_node = alt1.node();
4063 if (eats_anything_node->GetSuccessorOfOmnivorousTextNode(compiler) != this) {
4064 return eats_at_least;
4067 // Really we should be creating a new trace when we execute this function,
4068 // but there is no need, because the code it generates cannot backtrack, and
4069 // we always arrive here with a trivial trace (since it's the entry to a
4070 // loop. That also implies that there are no preloaded characters, which is
4071 // good, because it means we won't be violating any assumptions by
4072 // overwriting those characters with new load instructions.
4073 DCHECK(trace->is_trivial());
4075 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
4076 // At this point we know that we are at a non-greedy loop that will eat
4077 // any character one at a time. Any non-anchored regexp has such a
4078 // loop prepended to it in order to find where it starts. We look for
4079 // a pattern of the form ...abc... where we can look 6 characters ahead
4080 // and step forwards 3 if the character is not one of abc. Abc need
4081 // not be atoms, they can be any reasonably limited character class or
4082 // small alternation.
4083 BoyerMooreLookahead* bm = bm_info(false);
4085 eats_at_least = Min(kMaxLookaheadForBoyerMoore,
4086 EatsAtLeast(kMaxLookaheadForBoyerMoore,
4089 if (eats_at_least >= 1) {
4090 bm = new(zone()) BoyerMooreLookahead(eats_at_least,
4093 GuardedAlternative alt0 = alternatives_->at(0);
4094 alt0.node()->FillInBMInfo(0, kRecursionBudget, bm, false);
4098 bm->EmitSkipInstructions(macro_assembler);
4100 return eats_at_least;
4104 void ChoiceNode::EmitChoices(RegExpCompiler* compiler,
4105 AlternativeGenerationList* alt_gens,
4108 PreloadState* preload) {
4109 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
4110 SetUpPreLoad(compiler, trace, preload);
4112 // For now we just call all choices one after the other. The idea ultimately
4113 // is to use the Dispatch table to try only the relevant ones.
4114 int choice_count = alternatives_->length();
4116 int new_flush_budget = trace->flush_budget() / choice_count;
4118 for (int i = first_choice; i < choice_count; i++) {
4119 bool is_last = i == choice_count - 1;
4120 bool fall_through_on_failure = !is_last;
4121 GuardedAlternative alternative = alternatives_->at(i);
4122 AlternativeGeneration* alt_gen = alt_gens->at(i);
4123 alt_gen->quick_check_details.set_characters(preload->preload_characters_);
4124 ZoneList<Guard*>* guards = alternative.guards();
4125 int guard_count = (guards == NULL) ? 0 : guards->length();
4126 Trace new_trace(*trace);
4127 new_trace.set_characters_preloaded(preload->preload_is_current_ ?
4128 preload->preload_characters_ :
4130 if (preload->preload_has_checked_bounds_) {
4131 new_trace.set_bound_checked_up_to(preload->preload_characters_);
4133 new_trace.quick_check_performed()->Clear();
4134 if (not_at_start_) new_trace.set_at_start(Trace::FALSE_VALUE);
4136 new_trace.set_backtrack(&alt_gen->after);
4138 alt_gen->expects_preload = preload->preload_is_current_;
4139 bool generate_full_check_inline = false;
4140 if (FLAG_regexp_optimization &&
4141 try_to_emit_quick_check_for_alternative(i == 0) &&
4142 alternative.node()->EmitQuickCheck(compiler,
4145 preload->preload_has_checked_bounds_,
4146 &alt_gen->possible_success,
4147 &alt_gen->quick_check_details,
4148 fall_through_on_failure)) {
4149 // Quick check was generated for this choice.
4150 preload->preload_is_current_ = true;
4151 preload->preload_has_checked_bounds_ = true;
4152 // If we generated the quick check to fall through on possible success,
4153 // we now need to generate the full check inline.
4154 if (!fall_through_on_failure) {
4155 macro_assembler->Bind(&alt_gen->possible_success);
4156 new_trace.set_quick_check_performed(&alt_gen->quick_check_details);
4157 new_trace.set_characters_preloaded(preload->preload_characters_);
4158 new_trace.set_bound_checked_up_to(preload->preload_characters_);
4159 generate_full_check_inline = true;
4161 } else if (alt_gen->quick_check_details.cannot_match()) {
4162 if (!fall_through_on_failure) {
4163 macro_assembler->GoTo(trace->backtrack());
4167 // No quick check was generated. Put the full code here.
4168 // If this is not the first choice then there could be slow checks from
4169 // previous cases that go here when they fail. There's no reason to
4170 // insist that they preload characters since the slow check we are about
4171 // to generate probably can't use it.
4172 if (i != first_choice) {
4173 alt_gen->expects_preload = false;
4174 new_trace.InvalidateCurrentCharacter();
4176 generate_full_check_inline = true;
4178 if (generate_full_check_inline) {
4179 if (new_trace.actions() != NULL) {
4180 new_trace.set_flush_budget(new_flush_budget);
4182 for (int j = 0; j < guard_count; j++) {
4183 GenerateGuard(macro_assembler, guards->at(j), &new_trace);
4185 alternative.node()->Emit(compiler, &new_trace);
4186 preload->preload_is_current_ = false;
4188 macro_assembler->Bind(&alt_gen->after);
4193 void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
4195 GuardedAlternative alternative,
4196 AlternativeGeneration* alt_gen,
4197 int preload_characters,
4198 bool next_expects_preload) {
4199 if (!alt_gen->possible_success.is_linked()) return;
4201 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
4202 macro_assembler->Bind(&alt_gen->possible_success);
4203 Trace out_of_line_trace(*trace);
4204 out_of_line_trace.set_characters_preloaded(preload_characters);
4205 out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details);
4206 if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE_VALUE);
4207 ZoneList<Guard*>* guards = alternative.guards();
4208 int guard_count = (guards == NULL) ? 0 : guards->length();
4209 if (next_expects_preload) {
4210 Label reload_current_char;
4211 out_of_line_trace.set_backtrack(&reload_current_char);
4212 for (int j = 0; j < guard_count; j++) {
4213 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
4215 alternative.node()->Emit(compiler, &out_of_line_trace);
4216 macro_assembler->Bind(&reload_current_char);
4217 // Reload the current character, since the next quick check expects that.
4218 // We don't need to check bounds here because we only get into this
4219 // code through a quick check which already did the checked load.
4220 macro_assembler->LoadCurrentCharacter(trace->cp_offset(),
4223 preload_characters);
4224 macro_assembler->GoTo(&(alt_gen->after));
4226 out_of_line_trace.set_backtrack(&(alt_gen->after));
4227 for (int j = 0; j < guard_count; j++) {
4228 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
4230 alternative.node()->Emit(compiler, &out_of_line_trace);
4235 void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
4236 RegExpMacroAssembler* assembler = compiler->macro_assembler();
4237 LimitResult limit_result = LimitVersions(compiler, trace);
4238 if (limit_result == DONE) return;
4239 DCHECK(limit_result == CONTINUE);
4241 RecursionCheck rc(compiler);
4243 switch (action_type_) {
4244 case STORE_POSITION: {
4245 Trace::DeferredCapture
4246 new_capture(data_.u_position_register.reg,
4247 data_.u_position_register.is_capture,
4249 Trace new_trace = *trace;
4250 new_trace.add_action(&new_capture);
4251 on_success()->Emit(compiler, &new_trace);
4254 case INCREMENT_REGISTER: {
4255 Trace::DeferredIncrementRegister
4256 new_increment(data_.u_increment_register.reg);
4257 Trace new_trace = *trace;
4258 new_trace.add_action(&new_increment);
4259 on_success()->Emit(compiler, &new_trace);
4262 case SET_REGISTER: {
4263 Trace::DeferredSetRegister
4264 new_set(data_.u_store_register.reg, data_.u_store_register.value);
4265 Trace new_trace = *trace;
4266 new_trace.add_action(&new_set);
4267 on_success()->Emit(compiler, &new_trace);
4270 case CLEAR_CAPTURES: {
4271 Trace::DeferredClearCaptures
4272 new_capture(Interval(data_.u_clear_captures.range_from,
4273 data_.u_clear_captures.range_to));
4274 Trace new_trace = *trace;
4275 new_trace.add_action(&new_capture);
4276 on_success()->Emit(compiler, &new_trace);
4279 case BEGIN_SUBMATCH:
4280 if (!trace->is_trivial()) {
4281 trace->Flush(compiler, this);
4283 assembler->WriteCurrentPositionToRegister(
4284 data_.u_submatch.current_position_register, 0);
4285 assembler->WriteStackPointerToRegister(
4286 data_.u_submatch.stack_pointer_register);
4287 on_success()->Emit(compiler, trace);
4290 case EMPTY_MATCH_CHECK: {
4291 int start_pos_reg = data_.u_empty_match_check.start_register;
4293 int rep_reg = data_.u_empty_match_check.repetition_register;
4294 bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister);
4295 bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos);
4296 if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) {
4297 // If we know we haven't advanced and there is no minimum we
4298 // can just backtrack immediately.
4299 assembler->GoTo(trace->backtrack());
4300 } else if (know_dist && stored_pos < trace->cp_offset()) {
4301 // If we know we've advanced we can generate the continuation
4303 on_success()->Emit(compiler, trace);
4304 } else if (!trace->is_trivial()) {
4305 trace->Flush(compiler, this);
4307 Label skip_empty_check;
4308 // If we have a minimum number of repetitions we check the current
4309 // number first and skip the empty check if it's not enough.
4311 int limit = data_.u_empty_match_check.repetition_limit;
4312 assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check);
4314 // If the match is empty we bail out, otherwise we fall through
4315 // to the on-success continuation.
4316 assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register,
4317 trace->backtrack());
4318 assembler->Bind(&skip_empty_check);
4319 on_success()->Emit(compiler, trace);
4323 case POSITIVE_SUBMATCH_SUCCESS: {
4324 if (!trace->is_trivial()) {
4325 trace->Flush(compiler, this);
4328 assembler->ReadCurrentPositionFromRegister(
4329 data_.u_submatch.current_position_register);
4330 assembler->ReadStackPointerFromRegister(
4331 data_.u_submatch.stack_pointer_register);
4332 int clear_register_count = data_.u_submatch.clear_register_count;
4333 if (clear_register_count == 0) {
4334 on_success()->Emit(compiler, trace);
4337 int clear_registers_from = data_.u_submatch.clear_register_from;
4338 Label clear_registers_backtrack;
4339 Trace new_trace = *trace;
4340 new_trace.set_backtrack(&clear_registers_backtrack);
4341 on_success()->Emit(compiler, &new_trace);
4343 assembler->Bind(&clear_registers_backtrack);
4344 int clear_registers_to = clear_registers_from + clear_register_count - 1;
4345 assembler->ClearRegisters(clear_registers_from, clear_registers_to);
4347 DCHECK(trace->backtrack() == NULL);
4348 assembler->Backtrack();
4357 void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
4358 RegExpMacroAssembler* assembler = compiler->macro_assembler();
4359 if (!trace->is_trivial()) {
4360 trace->Flush(compiler, this);
4364 LimitResult limit_result = LimitVersions(compiler, trace);
4365 if (limit_result == DONE) return;
4366 DCHECK(limit_result == CONTINUE);
4368 RecursionCheck rc(compiler);
4370 DCHECK_EQ(start_reg_ + 1, end_reg_);
4371 if (compiler->ignore_case()) {
4372 assembler->CheckNotBackReferenceIgnoreCase(start_reg_,
4373 trace->backtrack());
4375 assembler->CheckNotBackReference(start_reg_, trace->backtrack());
4377 on_success()->Emit(compiler, trace);
4381 // -------------------------------------------------------------------
4388 class DotPrinter: public NodeVisitor {
4390 DotPrinter(std::ostream& os, bool ignore_case) // NOLINT
4392 ignore_case_(ignore_case) {}
4393 void PrintNode(const char* label, RegExpNode* node);
4394 void Visit(RegExpNode* node);
4395 void PrintAttributes(RegExpNode* from);
4396 void PrintOnFailure(RegExpNode* from, RegExpNode* to);
4397 #define DECLARE_VISIT(Type) \
4398 virtual void Visit##Type(Type##Node* that);
4399 FOR_EACH_NODE_TYPE(DECLARE_VISIT)
4400 #undef DECLARE_VISIT
4407 void DotPrinter::PrintNode(const char* label, RegExpNode* node) {
4408 os_ << "digraph G {\n graph [label=\"";
4409 for (int i = 0; label[i]; i++) {
4424 os_ << "}" << std::endl;
4428 void DotPrinter::Visit(RegExpNode* node) {
4429 if (node->info()->visited) return;
4430 node->info()->visited = true;
4435 void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
4436 os_ << " n" << from << " -> n" << on_failure << " [style=dotted];\n";
4441 class TableEntryBodyPrinter {
4443 TableEntryBodyPrinter(std::ostream& os, ChoiceNode* choice) // NOLINT
4446 void Call(uc16 from, DispatchTable::Entry entry) {
4447 OutSet* out_set = entry.out_set();
4448 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
4449 if (out_set->Get(i)) {
4450 os_ << " n" << choice() << ":s" << from << "o" << i << " -> n"
4451 << choice()->alternatives()->at(i).node() << ";\n";
4456 ChoiceNode* choice() { return choice_; }
4458 ChoiceNode* choice_;
4462 class TableEntryHeaderPrinter {
4464 explicit TableEntryHeaderPrinter(std::ostream& os) // NOLINT
4467 void Call(uc16 from, DispatchTable::Entry entry) {
4473 os_ << "{\\" << AsUC16(from) << "-\\" << AsUC16(entry.to()) << "|{";
4474 OutSet* out_set = entry.out_set();
4476 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
4477 if (out_set->Get(i)) {
4478 if (priority > 0) os_ << "|";
4479 os_ << "<s" << from << "o" << i << "> " << priority;
4492 class AttributePrinter {
4494 explicit AttributePrinter(std::ostream& os) // NOLINT
4497 void PrintSeparator() {
4504 void PrintBit(const char* name, bool value) {
4507 os_ << "{" << name << "}";
4509 void PrintPositive(const char* name, int value) {
4510 if (value < 0) return;
4512 os_ << "{" << name << "|" << value << "}";
4521 void DotPrinter::PrintAttributes(RegExpNode* that) {
4522 os_ << " a" << that << " [shape=Mrecord, color=grey, fontcolor=grey, "
4523 << "margin=0.1, fontsize=10, label=\"{";
4524 AttributePrinter printer(os_);
4525 NodeInfo* info = that->info();
4526 printer.PrintBit("NI", info->follows_newline_interest);
4527 printer.PrintBit("WI", info->follows_word_interest);
4528 printer.PrintBit("SI", info->follows_start_interest);
4529 Label* label = that->label();
4530 if (label->is_bound())
4531 printer.PrintPositive("@", label->pos());
4533 << " a" << that << " -> n" << that
4534 << " [style=dashed, color=grey, arrowhead=none];\n";
4538 static const bool kPrintDispatchTable = false;
4539 void DotPrinter::VisitChoice(ChoiceNode* that) {
4540 if (kPrintDispatchTable) {
4541 os_ << " n" << that << " [shape=Mrecord, label=\"";
4542 TableEntryHeaderPrinter header_printer(os_);
4543 that->GetTable(ignore_case_)->ForEach(&header_printer);
4545 PrintAttributes(that);
4546 TableEntryBodyPrinter body_printer(os_, that);
4547 that->GetTable(ignore_case_)->ForEach(&body_printer);
4549 os_ << " n" << that << " [shape=Mrecord, label=\"?\"];\n";
4550 for (int i = 0; i < that->alternatives()->length(); i++) {
4551 GuardedAlternative alt = that->alternatives()->at(i);
4552 os_ << " n" << that << " -> n" << alt.node();
4555 for (int i = 0; i < that->alternatives()->length(); i++) {
4556 GuardedAlternative alt = that->alternatives()->at(i);
4557 alt.node()->Accept(this);
4562 void DotPrinter::VisitText(TextNode* that) {
4563 Zone* zone = that->zone();
4564 os_ << " n" << that << " [label=\"";
4565 for (int i = 0; i < that->elements()->length(); i++) {
4566 if (i > 0) os_ << " ";
4567 TextElement elm = that->elements()->at(i);
4568 switch (elm.text_type()) {
4569 case TextElement::ATOM: {
4570 Vector<const uc16> data = elm.atom()->data();
4571 for (int i = 0; i < data.length(); i++) {
4572 os_ << static_cast<char>(data[i]);
4576 case TextElement::CHAR_CLASS: {
4577 RegExpCharacterClass* node = elm.char_class();
4579 if (node->is_negated()) os_ << "^";
4580 for (int j = 0; j < node->ranges(zone)->length(); j++) {
4581 CharacterRange range = node->ranges(zone)->at(j);
4582 os_ << AsUC16(range.from()) << "-" << AsUC16(range.to());
4591 os_ << "\", shape=box, peripheries=2];\n";
4592 PrintAttributes(that);
4593 os_ << " n" << that << " -> n" << that->on_success() << ";\n";
4594 Visit(that->on_success());
4598 void DotPrinter::VisitBackReference(BackReferenceNode* that) {
4599 os_ << " n" << that << " [label=\"$" << that->start_register() << "..$"
4600 << that->end_register() << "\", shape=doubleoctagon];\n";
4601 PrintAttributes(that);
4602 os_ << " n" << that << " -> n" << that->on_success() << ";\n";
4603 Visit(that->on_success());
4607 void DotPrinter::VisitEnd(EndNode* that) {
4608 os_ << " n" << that << " [style=bold, shape=point];\n";
4609 PrintAttributes(that);
4613 void DotPrinter::VisitAssertion(AssertionNode* that) {
4614 os_ << " n" << that << " [";
4615 switch (that->assertion_type()) {
4616 case AssertionNode::AT_END:
4617 os_ << "label=\"$\", shape=septagon";
4619 case AssertionNode::AT_START:
4620 os_ << "label=\"^\", shape=septagon";
4622 case AssertionNode::AT_BOUNDARY:
4623 os_ << "label=\"\\b\", shape=septagon";
4625 case AssertionNode::AT_NON_BOUNDARY:
4626 os_ << "label=\"\\B\", shape=septagon";
4628 case AssertionNode::AFTER_NEWLINE:
4629 os_ << "label=\"(?<=\\n)\", shape=septagon";
4633 PrintAttributes(that);
4634 RegExpNode* successor = that->on_success();
4635 os_ << " n" << that << " -> n" << successor << ";\n";
4640 void DotPrinter::VisitAction(ActionNode* that) {
4641 os_ << " n" << that << " [";
4642 switch (that->action_type_) {
4643 case ActionNode::SET_REGISTER:
4644 os_ << "label=\"$" << that->data_.u_store_register.reg
4645 << ":=" << that->data_.u_store_register.value << "\", shape=octagon";
4647 case ActionNode::INCREMENT_REGISTER:
4648 os_ << "label=\"$" << that->data_.u_increment_register.reg
4649 << "++\", shape=octagon";
4651 case ActionNode::STORE_POSITION:
4652 os_ << "label=\"$" << that->data_.u_position_register.reg
4653 << ":=$pos\", shape=octagon";
4655 case ActionNode::BEGIN_SUBMATCH:
4656 os_ << "label=\"$" << that->data_.u_submatch.current_position_register
4657 << ":=$pos,begin\", shape=septagon";
4659 case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
4660 os_ << "label=\"escape\", shape=septagon";
4662 case ActionNode::EMPTY_MATCH_CHECK:
4663 os_ << "label=\"$" << that->data_.u_empty_match_check.start_register
4664 << "=$pos?,$" << that->data_.u_empty_match_check.repetition_register
4665 << "<" << that->data_.u_empty_match_check.repetition_limit
4666 << "?\", shape=septagon";
4668 case ActionNode::CLEAR_CAPTURES: {
4669 os_ << "label=\"clear $" << that->data_.u_clear_captures.range_from
4670 << " to $" << that->data_.u_clear_captures.range_to
4671 << "\", shape=septagon";
4676 PrintAttributes(that);
4677 RegExpNode* successor = that->on_success();
4678 os_ << " n" << that << " -> n" << successor << ";\n";
4683 class DispatchTableDumper {
4685 explicit DispatchTableDumper(std::ostream& os) : os_(os) {}
4686 void Call(uc16 key, DispatchTable::Entry entry);
4692 void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) {
4693 os_ << "[" << AsUC16(key) << "-" << AsUC16(entry.to()) << "]: {";
4694 OutSet* set = entry.out_set();
4696 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
4710 void DispatchTable::Dump() {
4711 OFStream os(stderr);
4712 DispatchTableDumper dumper(os);
4713 tree()->ForEach(&dumper);
4717 void RegExpEngine::DotPrint(const char* label,
4720 OFStream os(stdout);
4721 DotPrinter printer(os, ignore_case);
4722 printer.PrintNode(label, node);
4729 // -------------------------------------------------------------------
4730 // Tree to graph conversion
4732 RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
4733 RegExpNode* on_success) {
4734 ZoneList<TextElement>* elms =
4735 new(compiler->zone()) ZoneList<TextElement>(1, compiler->zone());
4736 elms->Add(TextElement::Atom(this), compiler->zone());
4737 return new(compiler->zone()) TextNode(elms, on_success);
4741 RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
4742 RegExpNode* on_success) {
4743 return new(compiler->zone()) TextNode(elements(), on_success);
4747 static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
4748 const int* special_class,
4750 length--; // Remove final 0x10000.
4751 DCHECK(special_class[length] == 0x10000);
4752 DCHECK(ranges->length() != 0);
4753 DCHECK(length != 0);
4754 DCHECK(special_class[0] != 0);
4755 if (ranges->length() != (length >> 1) + 1) {
4758 CharacterRange range = ranges->at(0);
4759 if (range.from() != 0) {
4762 for (int i = 0; i < length; i += 2) {
4763 if (special_class[i] != (range.to() + 1)) {
4766 range = ranges->at((i >> 1) + 1);
4767 if (special_class[i+1] != range.from()) {
4771 if (range.to() != 0xffff) {
4778 static bool CompareRanges(ZoneList<CharacterRange>* ranges,
4779 const int* special_class,
4781 length--; // Remove final 0x10000.
4782 DCHECK(special_class[length] == 0x10000);
4783 if (ranges->length() * 2 != length) {
4786 for (int i = 0; i < length; i += 2) {
4787 CharacterRange range = ranges->at(i >> 1);
4788 if (range.from() != special_class[i] ||
4789 range.to() != special_class[i + 1] - 1) {
4797 bool RegExpCharacterClass::is_standard(Zone* zone) {
4798 // TODO(lrn): Remove need for this function, by not throwing away information
4803 if (set_.is_standard()) {
4806 if (CompareRanges(set_.ranges(zone), kSpaceRanges, kSpaceRangeCount)) {
4807 set_.set_standard_set_type('s');
4810 if (CompareInverseRanges(set_.ranges(zone), kSpaceRanges, kSpaceRangeCount)) {
4811 set_.set_standard_set_type('S');
4814 if (CompareInverseRanges(set_.ranges(zone),
4815 kLineTerminatorRanges,
4816 kLineTerminatorRangeCount)) {
4817 set_.set_standard_set_type('.');
4820 if (CompareRanges(set_.ranges(zone),
4821 kLineTerminatorRanges,
4822 kLineTerminatorRangeCount)) {
4823 set_.set_standard_set_type('n');
4826 if (CompareRanges(set_.ranges(zone), kWordRanges, kWordRangeCount)) {
4827 set_.set_standard_set_type('w');
4830 if (CompareInverseRanges(set_.ranges(zone), kWordRanges, kWordRangeCount)) {
4831 set_.set_standard_set_type('W');
4838 RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
4839 RegExpNode* on_success) {
4840 return new(compiler->zone()) TextNode(this, on_success);
4844 RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
4845 RegExpNode* on_success) {
4846 ZoneList<RegExpTree*>* alternatives = this->alternatives();
4847 int length = alternatives->length();
4848 ChoiceNode* result =
4849 new(compiler->zone()) ChoiceNode(length, compiler->zone());
4850 for (int i = 0; i < length; i++) {
4851 GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler,
4853 result->AddAlternative(alternative);
4859 RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
4860 RegExpNode* on_success) {
4861 return ToNode(min(),
4870 // Scoped object to keep track of how much we unroll quantifier loops in the
4871 // regexp graph generator.
4872 class RegExpExpansionLimiter {
4874 static const int kMaxExpansionFactor = 6;
4875 RegExpExpansionLimiter(RegExpCompiler* compiler, int factor)
4876 : compiler_(compiler),
4877 saved_expansion_factor_(compiler->current_expansion_factor()),
4878 ok_to_expand_(saved_expansion_factor_ <= kMaxExpansionFactor) {
4880 if (ok_to_expand_) {
4881 if (factor > kMaxExpansionFactor) {
4882 // Avoid integer overflow of the current expansion factor.
4883 ok_to_expand_ = false;
4884 compiler->set_current_expansion_factor(kMaxExpansionFactor + 1);
4886 int new_factor = saved_expansion_factor_ * factor;
4887 ok_to_expand_ = (new_factor <= kMaxExpansionFactor);
4888 compiler->set_current_expansion_factor(new_factor);
4893 ~RegExpExpansionLimiter() {
4894 compiler_->set_current_expansion_factor(saved_expansion_factor_);
4897 bool ok_to_expand() { return ok_to_expand_; }
4900 RegExpCompiler* compiler_;
4901 int saved_expansion_factor_;
4904 DISALLOW_IMPLICIT_CONSTRUCTORS(RegExpExpansionLimiter);
4908 RegExpNode* RegExpQuantifier::ToNode(int min,
4912 RegExpCompiler* compiler,
4913 RegExpNode* on_success,
4914 bool not_at_start) {
4915 // x{f, t} becomes this:
4921 // (r=0)-->(?)---/ [if r < t]
4923 // [if r >= f] \----> ...
4926 // 15.10.2.5 RepeatMatcher algorithm.
4927 // The parser has already eliminated the case where max is 0. In the case
4928 // where max_match is zero the parser has removed the quantifier if min was
4929 // > 0 and removed the atom if min was 0. See AddQuantifierToAtom.
4931 // If we know that we cannot match zero length then things are a little
4932 // simpler since we don't need to make the special zero length match check
4933 // from step 2.1. If the min and max are small we can unroll a little in
4935 static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,}
4936 static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3}
4937 if (max == 0) return on_success; // This can happen due to recursion.
4938 bool body_can_be_empty = (body->min_match() == 0);
4939 int body_start_reg = RegExpCompiler::kNoRegister;
4940 Interval capture_registers = body->CaptureRegisters();
4941 bool needs_capture_clearing = !capture_registers.is_empty();
4942 Zone* zone = compiler->zone();
4944 if (body_can_be_empty) {
4945 body_start_reg = compiler->AllocateRegister();
4946 } else if (FLAG_regexp_optimization && !needs_capture_clearing) {
4947 // Only unroll if there are no captures and the body can't be
4950 RegExpExpansionLimiter limiter(
4951 compiler, min + ((max != min) ? 1 : 0));
4952 if (min > 0 && min <= kMaxUnrolledMinMatches && limiter.ok_to_expand()) {
4953 int new_max = (max == kInfinity) ? max : max - min;
4954 // Recurse once to get the loop or optional matches after the fixed
4956 RegExpNode* answer = ToNode(
4957 0, new_max, is_greedy, body, compiler, on_success, true);
4958 // Unroll the forced matches from 0 to min. This can cause chains of
4959 // TextNodes (which the parser does not generate). These should be
4960 // combined if it turns out they hinder good code generation.
4961 for (int i = 0; i < min; i++) {
4962 answer = body->ToNode(compiler, answer);
4967 if (max <= kMaxUnrolledMaxMatches && min == 0) {
4968 DCHECK(max > 0); // Due to the 'if' above.
4969 RegExpExpansionLimiter limiter(compiler, max);
4970 if (limiter.ok_to_expand()) {
4971 // Unroll the optional matches up to max.
4972 RegExpNode* answer = on_success;
4973 for (int i = 0; i < max; i++) {
4974 ChoiceNode* alternation = new(zone) ChoiceNode(2, zone);
4976 alternation->AddAlternative(
4977 GuardedAlternative(body->ToNode(compiler, answer)));
4978 alternation->AddAlternative(GuardedAlternative(on_success));
4980 alternation->AddAlternative(GuardedAlternative(on_success));
4981 alternation->AddAlternative(
4982 GuardedAlternative(body->ToNode(compiler, answer)));
4984 answer = alternation;
4985 if (not_at_start) alternation->set_not_at_start();
4991 bool has_min = min > 0;
4992 bool has_max = max < RegExpTree::kInfinity;
4993 bool needs_counter = has_min || has_max;
4994 int reg_ctr = needs_counter
4995 ? compiler->AllocateRegister()
4996 : RegExpCompiler::kNoRegister;
4997 LoopChoiceNode* center = new(zone) LoopChoiceNode(body->min_match() == 0,
4999 if (not_at_start) center->set_not_at_start();
5000 RegExpNode* loop_return = needs_counter
5001 ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
5002 : static_cast<RegExpNode*>(center);
5003 if (body_can_be_empty) {
5004 // If the body can be empty we need to check if it was and then
5006 loop_return = ActionNode::EmptyMatchCheck(body_start_reg,
5011 RegExpNode* body_node = body->ToNode(compiler, loop_return);
5012 if (body_can_be_empty) {
5013 // If the body can be empty we need to store the start position
5014 // so we can bail out if it was empty.
5015 body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
5017 if (needs_capture_clearing) {
5018 // Before entering the body of this loop we need to clear captures.
5019 body_node = ActionNode::ClearCaptures(capture_registers, body_node);
5021 GuardedAlternative body_alt(body_node);
5024 new(zone) Guard(reg_ctr, Guard::LT, max);
5025 body_alt.AddGuard(body_guard, zone);
5027 GuardedAlternative rest_alt(on_success);
5029 Guard* rest_guard = new(compiler->zone()) Guard(reg_ctr, Guard::GEQ, min);
5030 rest_alt.AddGuard(rest_guard, zone);
5033 center->AddLoopAlternative(body_alt);
5034 center->AddContinueAlternative(rest_alt);
5036 center->AddContinueAlternative(rest_alt);
5037 center->AddLoopAlternative(body_alt);
5039 if (needs_counter) {
5040 return ActionNode::SetRegister(reg_ctr, 0, center);
5047 RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
5048 RegExpNode* on_success) {
5050 Zone* zone = compiler->zone();
5052 switch (assertion_type()) {
5054 return AssertionNode::AfterNewline(on_success);
5055 case START_OF_INPUT:
5056 return AssertionNode::AtStart(on_success);
5058 return AssertionNode::AtBoundary(on_success);
5060 return AssertionNode::AtNonBoundary(on_success);
5062 return AssertionNode::AtEnd(on_success);
5064 // Compile $ in multiline regexps as an alternation with a positive
5065 // lookahead in one side and an end-of-input on the other side.
5066 // We need two registers for the lookahead.
5067 int stack_pointer_register = compiler->AllocateRegister();
5068 int position_register = compiler->AllocateRegister();
5069 // The ChoiceNode to distinguish between a newline and end-of-input.
5070 ChoiceNode* result = new(zone) ChoiceNode(2, zone);
5071 // Create a newline atom.
5072 ZoneList<CharacterRange>* newline_ranges =
5073 new(zone) ZoneList<CharacterRange>(3, zone);
5074 CharacterRange::AddClassEscape('n', newline_ranges, zone);
5075 RegExpCharacterClass* newline_atom = new(zone) RegExpCharacterClass('n');
5076 TextNode* newline_matcher = new(zone) TextNode(
5078 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
5080 0, // No captures inside.
5081 -1, // Ignored if no captures.
5083 // Create an end-of-input matcher.
5084 RegExpNode* end_of_line = ActionNode::BeginSubmatch(
5085 stack_pointer_register,
5088 // Add the two alternatives to the ChoiceNode.
5089 GuardedAlternative eol_alternative(end_of_line);
5090 result->AddAlternative(eol_alternative);
5091 GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
5092 result->AddAlternative(end_alternative);
5102 RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
5103 RegExpNode* on_success) {
5104 return new(compiler->zone())
5105 BackReferenceNode(RegExpCapture::StartRegister(index()),
5106 RegExpCapture::EndRegister(index()),
5111 RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
5112 RegExpNode* on_success) {
5117 RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler,
5118 RegExpNode* on_success) {
5119 int stack_pointer_register = compiler->AllocateRegister();
5120 int position_register = compiler->AllocateRegister();
5122 const int registers_per_capture = 2;
5123 const int register_of_first_capture = 2;
5124 int register_count = capture_count_ * registers_per_capture;
5125 int register_start =
5126 register_of_first_capture + capture_from_ * registers_per_capture;
5128 RegExpNode* success;
5129 if (is_positive()) {
5130 RegExpNode* node = ActionNode::BeginSubmatch(
5131 stack_pointer_register,
5135 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
5142 // We use a ChoiceNode for a negative lookahead because it has most of
5143 // the characteristics we need. It has the body of the lookahead as its
5144 // first alternative and the expression after the lookahead of the second
5145 // alternative. If the first alternative succeeds then the
5146 // NegativeSubmatchSuccess will unwind the stack including everything the
5147 // choice node set up and backtrack. If the first alternative fails then
5148 // the second alternative is tried, which is exactly the desired result
5149 // for a negative lookahead. The NegativeLookaheadChoiceNode is a special
5150 // ChoiceNode that knows to ignore the first exit when calculating quick
5152 Zone* zone = compiler->zone();
5154 GuardedAlternative body_alt(
5157 success = new(zone) NegativeSubmatchSuccess(stack_pointer_register,
5162 ChoiceNode* choice_node =
5163 new(zone) NegativeLookaheadChoiceNode(body_alt,
5164 GuardedAlternative(on_success),
5166 return ActionNode::BeginSubmatch(stack_pointer_register,
5173 RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
5174 RegExpNode* on_success) {
5175 return ToNode(body(), index(), compiler, on_success);
5179 RegExpNode* RegExpCapture::ToNode(RegExpTree* body,
5181 RegExpCompiler* compiler,
5182 RegExpNode* on_success) {
5183 int start_reg = RegExpCapture::StartRegister(index);
5184 int end_reg = RegExpCapture::EndRegister(index);
5185 RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
5186 RegExpNode* body_node = body->ToNode(compiler, store_end);
5187 return ActionNode::StorePosition(start_reg, true, body_node);
5191 RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
5192 RegExpNode* on_success) {
5193 ZoneList<RegExpTree*>* children = nodes();
5194 RegExpNode* current = on_success;
5195 for (int i = children->length() - 1; i >= 0; i--) {
5196 current = children->at(i)->ToNode(compiler, current);
5202 static void AddClass(const int* elmv,
5204 ZoneList<CharacterRange>* ranges,
5207 DCHECK(elmv[elmc] == 0x10000);
5208 for (int i = 0; i < elmc; i += 2) {
5209 DCHECK(elmv[i] < elmv[i + 1]);
5210 ranges->Add(CharacterRange(elmv[i], elmv[i + 1] - 1), zone);
5215 static void AddClassNegated(const int *elmv,
5217 ZoneList<CharacterRange>* ranges,
5220 DCHECK(elmv[elmc] == 0x10000);
5221 DCHECK(elmv[0] != 0x0000);
5222 DCHECK(elmv[elmc-1] != String::kMaxUtf16CodeUnit);
5224 for (int i = 0; i < elmc; i += 2) {
5225 DCHECK(last <= elmv[i] - 1);
5226 DCHECK(elmv[i] < elmv[i + 1]);
5227 ranges->Add(CharacterRange(last, elmv[i] - 1), zone);
5230 ranges->Add(CharacterRange(last, String::kMaxUtf16CodeUnit), zone);
5234 void CharacterRange::AddClassEscape(uc16 type,
5235 ZoneList<CharacterRange>* ranges,
5239 AddClass(kSpaceRanges, kSpaceRangeCount, ranges, zone);
5242 AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges, zone);
5245 AddClass(kWordRanges, kWordRangeCount, ranges, zone);
5248 AddClassNegated(kWordRanges, kWordRangeCount, ranges, zone);
5251 AddClass(kDigitRanges, kDigitRangeCount, ranges, zone);
5254 AddClassNegated(kDigitRanges, kDigitRangeCount, ranges, zone);
5257 AddClassNegated(kLineTerminatorRanges,
5258 kLineTerminatorRangeCount,
5262 // This is not a character range as defined by the spec but a
5263 // convenient shorthand for a character class that matches any
5266 ranges->Add(CharacterRange::Everything(), zone);
5268 // This is the set of characters matched by the $ and ^ symbols
5269 // in multiline mode.
5271 AddClass(kLineTerminatorRanges,
5272 kLineTerminatorRangeCount,
5282 Vector<const int> CharacterRange::GetWordBounds() {
5283 return Vector<const int>(kWordRanges, kWordRangeCount - 1);
5287 class CharacterRangeSplitter {
5289 CharacterRangeSplitter(ZoneList<CharacterRange>** included,
5290 ZoneList<CharacterRange>** excluded,
5292 : included_(included),
5293 excluded_(excluded),
5295 void Call(uc16 from, DispatchTable::Entry entry);
5297 static const int kInBase = 0;
5298 static const int kInOverlay = 1;
5301 ZoneList<CharacterRange>** included_;
5302 ZoneList<CharacterRange>** excluded_;
5307 void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) {
5308 if (!entry.out_set()->Get(kInBase)) return;
5309 ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay)
5312 if (*target == NULL) *target = new(zone_) ZoneList<CharacterRange>(2, zone_);
5313 (*target)->Add(CharacterRange(entry.from(), entry.to()), zone_);
5317 void CharacterRange::Split(ZoneList<CharacterRange>* base,
5318 Vector<const int> overlay,
5319 ZoneList<CharacterRange>** included,
5320 ZoneList<CharacterRange>** excluded,
5322 DCHECK_EQ(NULL, *included);
5323 DCHECK_EQ(NULL, *excluded);
5324 DispatchTable table(zone);
5325 for (int i = 0; i < base->length(); i++)
5326 table.AddRange(base->at(i), CharacterRangeSplitter::kInBase, zone);
5327 for (int i = 0; i < overlay.length(); i += 2) {
5328 table.AddRange(CharacterRange(overlay[i], overlay[i + 1] - 1),
5329 CharacterRangeSplitter::kInOverlay, zone);
5331 CharacterRangeSplitter callback(included, excluded, zone);
5332 table.ForEach(&callback);
5336 void CharacterRange::AddCaseEquivalents(ZoneList<CharacterRange>* ranges,
5337 bool is_one_byte, Zone* zone) {
5338 Isolate* isolate = zone->isolate();
5339 uc16 bottom = from();
5341 if (is_one_byte && !RangeContainsLatin1Equivalents(*this)) {
5342 if (bottom > String::kMaxOneByteCharCode) return;
5343 if (top > String::kMaxOneByteCharCode) top = String::kMaxOneByteCharCode;
5345 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
5346 if (top == bottom) {
5347 // If this is a singleton we just expand the one character.
5348 int length = isolate->jsregexp_uncanonicalize()->get(bottom, '\0', chars);
5349 for (int i = 0; i < length; i++) {
5350 uc32 chr = chars[i];
5351 if (chr != bottom) {
5352 ranges->Add(CharacterRange::Singleton(chars[i]), zone);
5356 // If this is a range we expand the characters block by block,
5357 // expanding contiguous subranges (blocks) one at a time.
5358 // The approach is as follows. For a given start character we
5359 // look up the remainder of the block that contains it (represented
5360 // by the end point), for instance we find 'z' if the character
5361 // is 'c'. A block is characterized by the property
5362 // that all characters uncanonicalize in the same way, except that
5363 // each entry in the result is incremented by the distance from the first
5364 // element. So a-z is a block because 'a' uncanonicalizes to ['a', 'A'] and
5365 // the k'th letter uncanonicalizes to ['a' + k, 'A' + k].
5366 // Once we've found the end point we look up its uncanonicalization
5367 // and produce a range for each element. For instance for [c-f]
5368 // we look up ['z', 'Z'] and produce [c-f] and [C-F]. We then only
5369 // add a range if it is not already contained in the input, so [c-f]
5370 // will be skipped but [C-F] will be added. If this range is not
5371 // completely contained in a block we do this for all the blocks
5372 // covered by the range (handling characters that is not in a block
5373 // as a "singleton block").
5374 unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth];
5376 while (pos <= top) {
5377 int length = isolate->jsregexp_canonrange()->get(pos, '\0', range);
5382 DCHECK_EQ(1, length);
5383 block_end = range[0];
5385 int end = (block_end > top) ? top : block_end;
5386 length = isolate->jsregexp_uncanonicalize()->get(block_end, '\0', range);
5387 for (int i = 0; i < length; i++) {
5389 uc16 range_from = c - (block_end - pos);
5390 uc16 range_to = c - (block_end - end);
5391 if (!(bottom <= range_from && range_to <= top)) {
5392 ranges->Add(CharacterRange(range_from, range_to), zone);
5401 bool CharacterRange::IsCanonical(ZoneList<CharacterRange>* ranges) {
5402 DCHECK_NOT_NULL(ranges);
5403 int n = ranges->length();
5404 if (n <= 1) return true;
5405 int max = ranges->at(0).to();
5406 for (int i = 1; i < n; i++) {
5407 CharacterRange next_range = ranges->at(i);
5408 if (next_range.from() <= max + 1) return false;
5409 max = next_range.to();
5415 ZoneList<CharacterRange>* CharacterSet::ranges(Zone* zone) {
5416 if (ranges_ == NULL) {
5417 ranges_ = new(zone) ZoneList<CharacterRange>(2, zone);
5418 CharacterRange::AddClassEscape(standard_set_type_, ranges_, zone);
5424 // Move a number of elements in a zonelist to another position
5425 // in the same list. Handles overlapping source and target areas.
5426 static void MoveRanges(ZoneList<CharacterRange>* list,
5430 // Ranges are potentially overlapping.
5432 for (int i = count - 1; i >= 0; i--) {
5433 list->at(to + i) = list->at(from + i);
5436 for (int i = 0; i < count; i++) {
5437 list->at(to + i) = list->at(from + i);
5443 static int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list,
5445 CharacterRange insert) {
5446 // Inserts a range into list[0..count[, which must be sorted
5447 // by from value and non-overlapping and non-adjacent, using at most
5448 // list[0..count] for the result. Returns the number of resulting
5449 // canonicalized ranges. Inserting a range may collapse existing ranges into
5450 // fewer ranges, so the return value can be anything in the range 1..count+1.
5451 uc16 from = insert.from();
5452 uc16 to = insert.to();
5454 int end_pos = count;
5455 for (int i = count - 1; i >= 0; i--) {
5456 CharacterRange current = list->at(i);
5457 if (current.from() > to + 1) {
5459 } else if (current.to() + 1 < from) {
5465 // Inserted range overlaps, or is adjacent to, ranges at positions
5466 // [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are
5467 // not affected by the insertion.
5468 // If start_pos == end_pos, the range must be inserted before start_pos.
5469 // if start_pos < end_pos, the entire range from start_pos to end_pos
5470 // must be merged with the insert range.
5472 if (start_pos == end_pos) {
5473 // Insert between existing ranges at position start_pos.
5474 if (start_pos < count) {
5475 MoveRanges(list, start_pos, start_pos + 1, count - start_pos);
5477 list->at(start_pos) = insert;
5480 if (start_pos + 1 == end_pos) {
5481 // Replace single existing range at position start_pos.
5482 CharacterRange to_replace = list->at(start_pos);
5483 int new_from = Min(to_replace.from(), from);
5484 int new_to = Max(to_replace.to(), to);
5485 list->at(start_pos) = CharacterRange(new_from, new_to);
5488 // Replace a number of existing ranges from start_pos to end_pos - 1.
5489 // Move the remaining ranges down.
5491 int new_from = Min(list->at(start_pos).from(), from);
5492 int new_to = Max(list->at(end_pos - 1).to(), to);
5493 if (end_pos < count) {
5494 MoveRanges(list, end_pos, start_pos + 1, count - end_pos);
5496 list->at(start_pos) = CharacterRange(new_from, new_to);
5497 return count - (end_pos - start_pos) + 1;
5501 void CharacterSet::Canonicalize() {
5502 // Special/default classes are always considered canonical. The result
5503 // of calling ranges() will be sorted.
5504 if (ranges_ == NULL) return;
5505 CharacterRange::Canonicalize(ranges_);
5509 void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) {
5510 if (character_ranges->length() <= 1) return;
5511 // Check whether ranges are already canonical (increasing, non-overlapping,
5513 int n = character_ranges->length();
5514 int max = character_ranges->at(0).to();
5517 CharacterRange current = character_ranges->at(i);
5518 if (current.from() <= max + 1) {
5524 // Canonical until the i'th range. If that's all of them, we are done.
5527 // The ranges at index i and forward are not canonicalized. Make them so by
5528 // doing the equivalent of insertion sort (inserting each into the previous
5530 // Notice that inserting a range can reduce the number of ranges in the
5531 // result due to combining of adjacent and overlapping ranges.
5532 int read = i; // Range to insert.
5533 int num_canonical = i; // Length of canonicalized part of list.
5535 num_canonical = InsertRangeInCanonicalList(character_ranges,
5537 character_ranges->at(read));
5540 character_ranges->Rewind(num_canonical);
5542 DCHECK(CharacterRange::IsCanonical(character_ranges));
5546 void CharacterRange::Negate(ZoneList<CharacterRange>* ranges,
5547 ZoneList<CharacterRange>* negated_ranges,
5549 DCHECK(CharacterRange::IsCanonical(ranges));
5550 DCHECK_EQ(0, negated_ranges->length());
5551 int range_count = ranges->length();
5554 if (range_count > 0 && ranges->at(0).from() == 0) {
5555 from = ranges->at(0).to();
5558 while (i < range_count) {
5559 CharacterRange range = ranges->at(i);
5560 negated_ranges->Add(CharacterRange(from + 1, range.from() - 1), zone);
5564 if (from < String::kMaxUtf16CodeUnit) {
5565 negated_ranges->Add(CharacterRange(from + 1, String::kMaxUtf16CodeUnit),
5571 // -------------------------------------------------------------------
5575 OutSet* OutSet::Extend(unsigned value, Zone* zone) {
5578 if (successors(zone) != NULL) {
5579 for (int i = 0; i < successors(zone)->length(); i++) {
5580 OutSet* successor = successors(zone)->at(i);
5581 if (successor->Get(value))
5585 successors_ = new(zone) ZoneList<OutSet*>(2, zone);
5587 OutSet* result = new(zone) OutSet(first_, remaining_);
5588 result->Set(value, zone);
5589 successors(zone)->Add(result, zone);
5594 void OutSet::Set(unsigned value, Zone *zone) {
5595 if (value < kFirstLimit) {
5596 first_ |= (1 << value);
5598 if (remaining_ == NULL)
5599 remaining_ = new(zone) ZoneList<unsigned>(1, zone);
5600 if (remaining_->is_empty() || !remaining_->Contains(value))
5601 remaining_->Add(value, zone);
5606 bool OutSet::Get(unsigned value) const {
5607 if (value < kFirstLimit) {
5608 return (first_ & (1 << value)) != 0;
5609 } else if (remaining_ == NULL) {
5612 return remaining_->Contains(value);
5617 const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
5620 void DispatchTable::AddRange(CharacterRange full_range, int value,
5622 CharacterRange current = full_range;
5623 if (tree()->is_empty()) {
5624 // If this is the first range we just insert into the table.
5625 ZoneSplayTree<Config>::Locator loc;
5626 DCHECK_RESULT(tree()->Insert(current.from(), &loc));
5627 loc.set_value(Entry(current.from(), current.to(),
5628 empty()->Extend(value, zone)));
5631 // First see if there is a range to the left of this one that
5633 ZoneSplayTree<Config>::Locator loc;
5634 if (tree()->FindGreatestLessThan(current.from(), &loc)) {
5635 Entry* entry = &loc.value();
5636 // If we've found a range that overlaps with this one, and it
5637 // starts strictly to the left of this one, we have to fix it
5638 // because the following code only handles ranges that start on
5639 // or after the start point of the range we're adding.
5640 if (entry->from() < current.from() && entry->to() >= current.from()) {
5641 // Snap the overlapping range in half around the start point of
5642 // the range we're adding.
5643 CharacterRange left(entry->from(), current.from() - 1);
5644 CharacterRange right(current.from(), entry->to());
5645 // The left part of the overlapping range doesn't overlap.
5646 // Truncate the whole entry to be just the left part.
5647 entry->set_to(left.to());
5648 // The right part is the one that overlaps. We add this part
5649 // to the map and let the next step deal with merging it with
5650 // the range we're adding.
5651 ZoneSplayTree<Config>::Locator loc;
5652 DCHECK_RESULT(tree()->Insert(right.from(), &loc));
5653 loc.set_value(Entry(right.from(),
5658 while (current.is_valid()) {
5659 if (tree()->FindLeastGreaterThan(current.from(), &loc) &&
5660 (loc.value().from() <= current.to()) &&
5661 (loc.value().to() >= current.from())) {
5662 Entry* entry = &loc.value();
5663 // We have overlap. If there is space between the start point of
5664 // the range we're adding and where the overlapping range starts
5665 // then we have to add a range covering just that space.
5666 if (current.from() < entry->from()) {
5667 ZoneSplayTree<Config>::Locator ins;
5668 DCHECK_RESULT(tree()->Insert(current.from(), &ins));
5669 ins.set_value(Entry(current.from(),
5671 empty()->Extend(value, zone)));
5672 current.set_from(entry->from());
5674 DCHECK_EQ(current.from(), entry->from());
5675 // If the overlapping range extends beyond the one we want to add
5676 // we have to snap the right part off and add it separately.
5677 if (entry->to() > current.to()) {
5678 ZoneSplayTree<Config>::Locator ins;
5679 DCHECK_RESULT(tree()->Insert(current.to() + 1, &ins));
5680 ins.set_value(Entry(current.to() + 1,
5683 entry->set_to(current.to());
5685 DCHECK(entry->to() <= current.to());
5686 // The overlapping range is now completely contained by the range
5687 // we're adding so we can just update it and move the start point
5688 // of the range we're adding just past it.
5689 entry->AddValue(value, zone);
5690 // Bail out if the last interval ended at 0xFFFF since otherwise
5691 // adding 1 will wrap around to 0.
5692 if (entry->to() == String::kMaxUtf16CodeUnit)
5694 DCHECK(entry->to() + 1 > current.from());
5695 current.set_from(entry->to() + 1);
5697 // There is no overlap so we can just add the range
5698 ZoneSplayTree<Config>::Locator ins;
5699 DCHECK_RESULT(tree()->Insert(current.from(), &ins));
5700 ins.set_value(Entry(current.from(),
5702 empty()->Extend(value, zone)));
5709 OutSet* DispatchTable::Get(uc16 value) {
5710 ZoneSplayTree<Config>::Locator loc;
5711 if (!tree()->FindGreatestLessThan(value, &loc))
5713 Entry* entry = &loc.value();
5714 if (value <= entry->to())
5715 return entry->out_set();
5721 // -------------------------------------------------------------------
5725 void Analysis::EnsureAnalyzed(RegExpNode* that) {
5726 StackLimitCheck check(that->zone()->isolate());
5727 if (check.HasOverflowed()) {
5728 fail("Stack overflow");
5731 if (that->info()->been_analyzed || that->info()->being_analyzed)
5733 that->info()->being_analyzed = true;
5735 that->info()->being_analyzed = false;
5736 that->info()->been_analyzed = true;
5740 void Analysis::VisitEnd(EndNode* that) {
5745 void TextNode::CalculateOffsets() {
5746 int element_count = elements()->length();
5747 // Set up the offsets of the elements relative to the start. This is a fixed
5748 // quantity since a TextNode can only contain fixed-width things.
5750 for (int i = 0; i < element_count; i++) {
5751 TextElement& elm = elements()->at(i);
5752 elm.set_cp_offset(cp_offset);
5753 cp_offset += elm.length();
5758 void Analysis::VisitText(TextNode* that) {
5760 that->MakeCaseIndependent(is_one_byte_);
5762 EnsureAnalyzed(that->on_success());
5763 if (!has_failed()) {
5764 that->CalculateOffsets();
5769 void Analysis::VisitAction(ActionNode* that) {
5770 RegExpNode* target = that->on_success();
5771 EnsureAnalyzed(target);
5772 if (!has_failed()) {
5773 // If the next node is interested in what it follows then this node
5774 // has to be interested too so it can pass the information on.
5775 that->info()->AddFromFollowing(target->info());
5780 void Analysis::VisitChoice(ChoiceNode* that) {
5781 NodeInfo* info = that->info();
5782 for (int i = 0; i < that->alternatives()->length(); i++) {
5783 RegExpNode* node = that->alternatives()->at(i).node();
5784 EnsureAnalyzed(node);
5785 if (has_failed()) return;
5786 // Anything the following nodes need to know has to be known by
5787 // this node also, so it can pass it on.
5788 info->AddFromFollowing(node->info());
5793 void Analysis::VisitLoopChoice(LoopChoiceNode* that) {
5794 NodeInfo* info = that->info();
5795 for (int i = 0; i < that->alternatives()->length(); i++) {
5796 RegExpNode* node = that->alternatives()->at(i).node();
5797 if (node != that->loop_node()) {
5798 EnsureAnalyzed(node);
5799 if (has_failed()) return;
5800 info->AddFromFollowing(node->info());
5803 // Check the loop last since it may need the value of this node
5804 // to get a correct result.
5805 EnsureAnalyzed(that->loop_node());
5806 if (!has_failed()) {
5807 info->AddFromFollowing(that->loop_node()->info());
5812 void Analysis::VisitBackReference(BackReferenceNode* that) {
5813 EnsureAnalyzed(that->on_success());
5817 void Analysis::VisitAssertion(AssertionNode* that) {
5818 EnsureAnalyzed(that->on_success());
5822 void BackReferenceNode::FillInBMInfo(int offset,
5824 BoyerMooreLookahead* bm,
5825 bool not_at_start) {
5826 // Working out the set of characters that a backreference can match is too
5827 // hard, so we just say that any character can match.
5828 bm->SetRest(offset);
5829 SaveBMInfo(bm, not_at_start, offset);
5833 STATIC_ASSERT(BoyerMoorePositionInfo::kMapSize ==
5834 RegExpMacroAssembler::kTableSize);
5837 void ChoiceNode::FillInBMInfo(int offset,
5839 BoyerMooreLookahead* bm,
5840 bool not_at_start) {
5841 ZoneList<GuardedAlternative>* alts = alternatives();
5842 budget = (budget - 1) / alts->length();
5843 for (int i = 0; i < alts->length(); i++) {
5844 GuardedAlternative& alt = alts->at(i);
5845 if (alt.guards() != NULL && alt.guards()->length() != 0) {
5846 bm->SetRest(offset); // Give up trying to fill in info.
5847 SaveBMInfo(bm, not_at_start, offset);
5850 alt.node()->FillInBMInfo(offset, budget, bm, not_at_start);
5852 SaveBMInfo(bm, not_at_start, offset);
5856 void TextNode::FillInBMInfo(int initial_offset,
5858 BoyerMooreLookahead* bm,
5859 bool not_at_start) {
5860 if (initial_offset >= bm->length()) return;
5861 int offset = initial_offset;
5862 int max_char = bm->max_char();
5863 for (int i = 0; i < elements()->length(); i++) {
5864 if (offset >= bm->length()) {
5865 if (initial_offset == 0) set_bm_info(not_at_start, bm);
5868 TextElement text = elements()->at(i);
5869 if (text.text_type() == TextElement::ATOM) {
5870 RegExpAtom* atom = text.atom();
5871 for (int j = 0; j < atom->length(); j++, offset++) {
5872 if (offset >= bm->length()) {
5873 if (initial_offset == 0) set_bm_info(not_at_start, bm);
5876 uc16 character = atom->data()[j];
5877 if (bm->compiler()->ignore_case()) {
5878 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
5879 int length = GetCaseIndependentLetters(
5882 bm->max_char() == String::kMaxOneByteCharCode,
5884 for (int j = 0; j < length; j++) {
5885 bm->Set(offset, chars[j]);
5888 if (character <= max_char) bm->Set(offset, character);
5892 DCHECK_EQ(TextElement::CHAR_CLASS, text.text_type());
5893 RegExpCharacterClass* char_class = text.char_class();
5894 ZoneList<CharacterRange>* ranges = char_class->ranges(zone());
5895 if (char_class->is_negated()) {
5898 for (int k = 0; k < ranges->length(); k++) {
5899 CharacterRange& range = ranges->at(k);
5900 if (range.from() > max_char) continue;
5901 int to = Min(max_char, static_cast<int>(range.to()));
5902 bm->SetInterval(offset, Interval(range.from(), to));
5908 if (offset >= bm->length()) {
5909 if (initial_offset == 0) set_bm_info(not_at_start, bm);
5912 on_success()->FillInBMInfo(offset,
5915 true); // Not at start after a text node.
5916 if (initial_offset == 0) set_bm_info(not_at_start, bm);
5920 // -------------------------------------------------------------------
5921 // Dispatch table construction
5924 void DispatchTableConstructor::VisitEnd(EndNode* that) {
5925 AddRange(CharacterRange::Everything());
5929 void DispatchTableConstructor::BuildTable(ChoiceNode* node) {
5930 node->set_being_calculated(true);
5931 ZoneList<GuardedAlternative>* alternatives = node->alternatives();
5932 for (int i = 0; i < alternatives->length(); i++) {
5933 set_choice_index(i);
5934 alternatives->at(i).node()->Accept(this);
5936 node->set_being_calculated(false);
5940 class AddDispatchRange {
5942 explicit AddDispatchRange(DispatchTableConstructor* constructor)
5943 : constructor_(constructor) { }
5944 void Call(uc32 from, DispatchTable::Entry entry);
5946 DispatchTableConstructor* constructor_;
5950 void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
5951 CharacterRange range(from, entry.to());
5952 constructor_->AddRange(range);
5956 void DispatchTableConstructor::VisitChoice(ChoiceNode* node) {
5957 if (node->being_calculated())
5959 DispatchTable* table = node->GetTable(ignore_case_);
5960 AddDispatchRange adder(this);
5961 table->ForEach(&adder);
5965 void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) {
5966 // TODO(160): Find the node that we refer back to and propagate its start
5967 // set back to here. For now we just accept anything.
5968 AddRange(CharacterRange::Everything());
5972 void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
5973 RegExpNode* target = that->on_success();
5974 target->Accept(this);
5978 static int CompareRangeByFrom(const CharacterRange* a,
5979 const CharacterRange* b) {
5980 return Compare<uc16>(a->from(), b->from());
5984 void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) {
5985 ranges->Sort(CompareRangeByFrom);
5987 for (int i = 0; i < ranges->length(); i++) {
5988 CharacterRange range = ranges->at(i);
5989 if (last < range.from())
5990 AddRange(CharacterRange(last, range.from() - 1));
5991 if (range.to() >= last) {
5992 if (range.to() == String::kMaxUtf16CodeUnit) {
5995 last = range.to() + 1;
5999 AddRange(CharacterRange(last, String::kMaxUtf16CodeUnit));
6003 void DispatchTableConstructor::VisitText(TextNode* that) {
6004 TextElement elm = that->elements()->at(0);
6005 switch (elm.text_type()) {
6006 case TextElement::ATOM: {
6007 uc16 c = elm.atom()->data()[0];
6008 AddRange(CharacterRange(c, c));
6011 case TextElement::CHAR_CLASS: {
6012 RegExpCharacterClass* tree = elm.char_class();
6013 ZoneList<CharacterRange>* ranges = tree->ranges(that->zone());
6014 if (tree->is_negated()) {
6017 for (int i = 0; i < ranges->length(); i++)
6018 AddRange(ranges->at(i));
6029 void DispatchTableConstructor::VisitAction(ActionNode* that) {
6030 RegExpNode* target = that->on_success();
6031 target->Accept(this);
6035 RegExpEngine::CompilationResult RegExpEngine::Compile(
6036 RegExpCompileData* data, bool ignore_case, bool is_global,
6037 bool is_multiline, bool is_sticky, Handle<String> pattern,
6038 Handle<String> sample_subject, bool is_one_byte, Zone* zone) {
6039 if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) {
6040 return IrregexpRegExpTooBig(zone->isolate());
6042 RegExpCompiler compiler(data->capture_count, ignore_case, is_one_byte, zone);
6044 // Sample some characters from the middle of the string.
6045 static const int kSampleSize = 128;
6047 sample_subject = String::Flatten(sample_subject);
6048 int chars_sampled = 0;
6049 int half_way = (sample_subject->length() - kSampleSize) / 2;
6050 for (int i = Max(0, half_way);
6051 i < sample_subject->length() && chars_sampled < kSampleSize;
6052 i++, chars_sampled++) {
6053 compiler.frequency_collator()->CountCharacter(sample_subject->Get(i));
6056 // Wrap the body of the regexp in capture #0.
6057 RegExpNode* captured_body = RegExpCapture::ToNode(data->tree,
6061 RegExpNode* node = captured_body;
6062 bool is_end_anchored = data->tree->IsAnchoredAtEnd();
6063 bool is_start_anchored = data->tree->IsAnchoredAtStart();
6064 int max_length = data->tree->max_match();
6065 if (!is_start_anchored && !is_sticky) {
6066 // Add a .*? at the beginning, outside the body capture, unless
6067 // this expression is anchored at the beginning or sticky.
6068 RegExpNode* loop_node =
6069 RegExpQuantifier::ToNode(0,
6070 RegExpTree::kInfinity,
6072 new(zone) RegExpCharacterClass('*'),
6075 data->contains_anchor);
6077 if (data->contains_anchor) {
6078 // Unroll loop once, to take care of the case that might start
6079 // at the start of input.
6080 ChoiceNode* first_step_node = new(zone) ChoiceNode(2, zone);
6081 first_step_node->AddAlternative(GuardedAlternative(captured_body));
6082 first_step_node->AddAlternative(GuardedAlternative(
6083 new(zone) TextNode(new(zone) RegExpCharacterClass('*'), loop_node)));
6084 node = first_step_node;
6090 node = node->FilterOneByte(RegExpCompiler::kMaxRecursion, ignore_case);
6091 // Do it again to propagate the new nodes to places where they were not
6092 // put because they had not been calculated yet.
6094 node = node->FilterOneByte(RegExpCompiler::kMaxRecursion, ignore_case);
6098 if (node == NULL) node = new(zone) EndNode(EndNode::BACKTRACK, zone);
6100 Analysis analysis(ignore_case, is_one_byte);
6101 analysis.EnsureAnalyzed(node);
6102 if (analysis.has_failed()) {
6103 const char* error_message = analysis.error_message();
6104 return CompilationResult(zone->isolate(), error_message);
6107 // Create the correct assembler for the architecture.
6108 #ifndef V8_INTERPRETED_REGEXP
6109 // Native regexp implementation.
6111 NativeRegExpMacroAssembler::Mode mode =
6112 is_one_byte ? NativeRegExpMacroAssembler::LATIN1
6113 : NativeRegExpMacroAssembler::UC16;
6115 #if V8_TARGET_ARCH_IA32
6116 RegExpMacroAssemblerIA32 macro_assembler(mode, (data->capture_count + 1) * 2,
6118 #elif V8_TARGET_ARCH_X64
6119 RegExpMacroAssemblerX64 macro_assembler(mode, (data->capture_count + 1) * 2,
6121 #elif V8_TARGET_ARCH_ARM
6122 RegExpMacroAssemblerARM macro_assembler(mode, (data->capture_count + 1) * 2,
6124 #elif V8_TARGET_ARCH_ARM64
6125 RegExpMacroAssemblerARM64 macro_assembler(mode, (data->capture_count + 1) * 2,
6127 #elif V8_TARGET_ARCH_MIPS
6128 RegExpMacroAssemblerMIPS macro_assembler(mode, (data->capture_count + 1) * 2,
6130 #elif V8_TARGET_ARCH_MIPS64
6131 RegExpMacroAssemblerMIPS macro_assembler(mode, (data->capture_count + 1) * 2,
6133 #elif V8_TARGET_ARCH_X87
6134 RegExpMacroAssemblerX87 macro_assembler(mode, (data->capture_count + 1) * 2,
6137 #error "Unsupported architecture"
6140 #else // V8_INTERPRETED_REGEXP
6141 // Interpreted regexp implementation.
6142 EmbeddedVector<byte, 1024> codes;
6143 RegExpMacroAssemblerIrregexp macro_assembler(codes, zone);
6144 #endif // V8_INTERPRETED_REGEXP
6146 // Inserted here, instead of in Assembler, because it depends on information
6147 // in the AST that isn't replicated in the Node structure.
6148 static const int kMaxBacksearchLimit = 1024;
6149 if (is_end_anchored &&
6150 !is_start_anchored &&
6151 max_length < kMaxBacksearchLimit) {
6152 macro_assembler.SetCurrentPositionFromEnd(max_length);
6156 macro_assembler.set_global_mode(
6157 (data->tree->min_match() > 0)
6158 ? RegExpMacroAssembler::GLOBAL_NO_ZERO_LENGTH_CHECK
6159 : RegExpMacroAssembler::GLOBAL);
6162 return compiler.Assemble(¯o_assembler,
6164 data->capture_count,
6169 }} // namespace v8::internal