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.h"
22 #include "src/string-search.h"
24 #ifndef V8_INTERPRETED_REGEXP
25 #if V8_TARGET_ARCH_IA32
26 #include "src/ia32/regexp-macro-assembler-ia32.h" // NOLINT
27 #elif V8_TARGET_ARCH_X64
28 #include "src/x64/regexp-macro-assembler-x64.h" // NOLINT
29 #elif V8_TARGET_ARCH_ARM64
30 #include "src/arm64/regexp-macro-assembler-arm64.h" // NOLINT
31 #elif V8_TARGET_ARCH_ARM
32 #include "src/arm/regexp-macro-assembler-arm.h" // NOLINT
33 #elif V8_TARGET_ARCH_MIPS
34 #include "src/mips/regexp-macro-assembler-mips.h" // NOLINT
35 #elif V8_TARGET_ARCH_MIPS64
36 #include "src/mips64/regexp-macro-assembler-mips64.h" // NOLINT
37 #elif V8_TARGET_ARCH_X87
38 #include "src/x87/regexp-macro-assembler-x87.h" // NOLINT
40 #error Unsupported target architecture.
44 #include "src/interpreter-irregexp.h"
50 MaybeHandle<Object> RegExpImpl::CreateRegExpLiteral(
51 Handle<JSFunction> constructor,
52 Handle<String> pattern,
53 Handle<String> flags) {
54 // Call the construct code with 2 arguments.
55 Handle<Object> argv[] = { pattern, flags };
56 return Execution::New(constructor, ARRAY_SIZE(argv), argv);
60 static JSRegExp::Flags RegExpFlagsFromString(Handle<String> str) {
61 int flags = JSRegExp::NONE;
62 for (int i = 0; i < str->length(); i++) {
63 switch (str->Get(i)) {
65 flags |= JSRegExp::IGNORE_CASE;
68 flags |= JSRegExp::GLOBAL;
71 flags |= JSRegExp::MULTILINE;
75 return JSRegExp::Flags(flags);
80 static inline MaybeHandle<Object> ThrowRegExpException(
82 Handle<String> pattern,
83 Handle<String> error_text,
84 const char* message) {
85 Isolate* isolate = re->GetIsolate();
86 Factory* factory = isolate->factory();
87 Handle<FixedArray> elements = factory->NewFixedArray(2);
88 elements->set(0, *pattern);
89 elements->set(1, *error_text);
90 Handle<JSArray> array = factory->NewJSArrayWithElements(elements);
91 Handle<Object> regexp_err = factory->NewSyntaxError(message, array);
92 return isolate->Throw<Object>(regexp_err);
96 ContainedInLattice AddRange(ContainedInLattice containment,
100 DCHECK((ranges_length & 1) == 1);
101 DCHECK(ranges[ranges_length - 1] == String::kMaxUtf16CodeUnit + 1);
102 if (containment == kLatticeUnknown) return containment;
105 for (int i = 0; i < ranges_length; inside = !inside, last = ranges[i], i++) {
106 // Consider the range from last to ranges[i].
107 // We haven't got to the new range yet.
108 if (ranges[i] <= new_range.from()) continue;
109 // New range is wholly inside last-ranges[i]. Note that new_range.to() is
110 // inclusive, but the values in ranges are not.
111 if (last <= new_range.from() && new_range.to() < ranges[i]) {
112 return Combine(containment, inside ? kLatticeIn : kLatticeOut);
114 return kLatticeUnknown;
120 // More makes code generation slower, less makes V8 benchmark score lower.
121 const int kMaxLookaheadForBoyerMoore = 8;
122 // In a 3-character pattern you can maximally step forwards 3 characters
123 // at a time, which is not always enough to pay for the extra logic.
124 const int kPatternTooShortForBoyerMoore = 2;
127 // Identifies the sort of regexps where the regexp engine is faster
128 // than the code used for atom matches.
129 static bool HasFewDifferentCharacters(Handle<String> pattern) {
130 int length = Min(kMaxLookaheadForBoyerMoore, pattern->length());
131 if (length <= kPatternTooShortForBoyerMoore) return false;
132 const int kMod = 128;
133 bool character_found[kMod];
135 memset(&character_found[0], 0, sizeof(character_found));
136 for (int i = 0; i < length; i++) {
137 int ch = (pattern->Get(i) & (kMod - 1));
138 if (!character_found[ch]) {
139 character_found[ch] = true;
141 // We declare a regexp low-alphabet if it has at least 3 times as many
142 // characters as it has different characters.
143 if (different * 3 > length) return false;
150 // Generic RegExp methods. Dispatches to implementation specific methods.
153 MaybeHandle<Object> RegExpImpl::Compile(Handle<JSRegExp> re,
154 Handle<String> pattern,
155 Handle<String> flag_str) {
156 Isolate* isolate = re->GetIsolate();
158 JSRegExp::Flags flags = RegExpFlagsFromString(flag_str);
159 CompilationCache* compilation_cache = isolate->compilation_cache();
160 MaybeHandle<FixedArray> maybe_cached =
161 compilation_cache->LookupRegExp(pattern, flags);
162 Handle<FixedArray> cached;
163 bool in_cache = maybe_cached.ToHandle(&cached);
164 LOG(isolate, RegExpCompileEvent(re, in_cache));
166 Handle<Object> result;
168 re->set_data(*cached);
171 pattern = String::Flatten(pattern);
172 PostponeInterruptsScope postpone(isolate);
173 RegExpCompileData parse_result;
174 FlatStringReader reader(isolate, pattern);
175 if (!RegExpParser::ParseRegExp(&reader, flags.is_multiline(),
176 &parse_result, &zone)) {
177 // Throw an exception if we fail to parse the pattern.
178 return ThrowRegExpException(re,
184 bool has_been_compiled = false;
186 if (parse_result.simple &&
187 !flags.is_ignore_case() &&
188 !HasFewDifferentCharacters(pattern)) {
189 // Parse-tree is a single atom that is equal to the pattern.
190 AtomCompile(re, pattern, flags, pattern);
191 has_been_compiled = true;
192 } else if (parse_result.tree->IsAtom() &&
193 !flags.is_ignore_case() &&
194 parse_result.capture_count == 0) {
195 RegExpAtom* atom = parse_result.tree->AsAtom();
196 Vector<const uc16> atom_pattern = atom->data();
197 Handle<String> atom_string;
198 ASSIGN_RETURN_ON_EXCEPTION(
199 isolate, atom_string,
200 isolate->factory()->NewStringFromTwoByte(atom_pattern),
202 if (!HasFewDifferentCharacters(atom_string)) {
203 AtomCompile(re, pattern, flags, atom_string);
204 has_been_compiled = true;
207 if (!has_been_compiled) {
208 IrregexpInitialize(re, pattern, flags, parse_result.capture_count);
210 DCHECK(re->data()->IsFixedArray());
211 // Compilation succeeded so the data is set on the regexp
212 // and we can store it in the cache.
213 Handle<FixedArray> data(FixedArray::cast(re->data()));
214 compilation_cache->PutRegExp(pattern, flags, data);
220 MaybeHandle<Object> RegExpImpl::Exec(Handle<JSRegExp> regexp,
221 Handle<String> subject,
223 Handle<JSArray> last_match_info) {
224 switch (regexp->TypeTag()) {
226 return AtomExec(regexp, subject, index, last_match_info);
227 case JSRegExp::IRREGEXP: {
228 return IrregexpExec(regexp, subject, index, last_match_info);
232 return MaybeHandle<Object>();
237 // RegExp Atom implementation: Simple string search using indexOf.
240 void RegExpImpl::AtomCompile(Handle<JSRegExp> re,
241 Handle<String> pattern,
242 JSRegExp::Flags flags,
243 Handle<String> match_pattern) {
244 re->GetIsolate()->factory()->SetRegExpAtomData(re,
252 static void SetAtomLastCapture(FixedArray* array,
256 SealHandleScope shs(array->GetIsolate());
257 RegExpImpl::SetLastCaptureCount(array, 2);
258 RegExpImpl::SetLastSubject(array, subject);
259 RegExpImpl::SetLastInput(array, subject);
260 RegExpImpl::SetCapture(array, 0, from);
261 RegExpImpl::SetCapture(array, 1, to);
265 int RegExpImpl::AtomExecRaw(Handle<JSRegExp> regexp,
266 Handle<String> subject,
270 Isolate* isolate = regexp->GetIsolate();
273 DCHECK(index <= subject->length());
275 subject = String::Flatten(subject);
276 DisallowHeapAllocation no_gc; // ensure vectors stay valid
278 String* needle = String::cast(regexp->DataAt(JSRegExp::kAtomPatternIndex));
279 int needle_len = needle->length();
280 DCHECK(needle->IsFlat());
281 DCHECK_LT(0, needle_len);
283 if (index + needle_len > subject->length()) {
284 return RegExpImpl::RE_FAILURE;
287 for (int i = 0; i < output_size; i += 2) {
288 String::FlatContent needle_content = needle->GetFlatContent();
289 String::FlatContent subject_content = subject->GetFlatContent();
290 DCHECK(needle_content.IsFlat());
291 DCHECK(subject_content.IsFlat());
292 // dispatch on type of strings
293 index = (needle_content.IsAscii()
294 ? (subject_content.IsAscii()
295 ? SearchString(isolate,
296 subject_content.ToOneByteVector(),
297 needle_content.ToOneByteVector(),
299 : SearchString(isolate,
300 subject_content.ToUC16Vector(),
301 needle_content.ToOneByteVector(),
303 : (subject_content.IsAscii()
304 ? SearchString(isolate,
305 subject_content.ToOneByteVector(),
306 needle_content.ToUC16Vector(),
308 : SearchString(isolate,
309 subject_content.ToUC16Vector(),
310 needle_content.ToUC16Vector(),
313 return i / 2; // Return number of matches.
316 output[i+1] = index + needle_len;
320 return output_size / 2;
324 Handle<Object> RegExpImpl::AtomExec(Handle<JSRegExp> re,
325 Handle<String> subject,
327 Handle<JSArray> last_match_info) {
328 Isolate* isolate = re->GetIsolate();
330 static const int kNumRegisters = 2;
331 STATIC_ASSERT(kNumRegisters <= Isolate::kJSRegexpStaticOffsetsVectorSize);
332 int32_t* output_registers = isolate->jsregexp_static_offsets_vector();
334 int res = AtomExecRaw(re, subject, index, output_registers, kNumRegisters);
336 if (res == RegExpImpl::RE_FAILURE) return isolate->factory()->null_value();
338 DCHECK_EQ(res, RegExpImpl::RE_SUCCESS);
339 SealHandleScope shs(isolate);
340 FixedArray* array = FixedArray::cast(last_match_info->elements());
341 SetAtomLastCapture(array, *subject, output_registers[0], output_registers[1]);
342 return last_match_info;
346 // Irregexp implementation.
348 // Ensures that the regexp object contains a compiled version of the
349 // source for either ASCII or non-ASCII strings.
350 // If the compiled version doesn't already exist, it is compiled
351 // from the source pattern.
352 // If compilation fails, an exception is thrown and this function
354 bool RegExpImpl::EnsureCompiledIrregexp(
355 Handle<JSRegExp> re, Handle<String> sample_subject, bool is_ascii) {
356 Object* compiled_code = re->DataAt(JSRegExp::code_index(is_ascii));
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_ascii));
365 if (saved_code->IsCode()) {
366 // Reinstate the code in the original place.
367 re->SetDataAt(JSRegExp::code_index(is_ascii), saved_code);
368 DCHECK(compiled_code->IsSmi());
371 return CompileIrregexp(re, sample_subject, is_ascii);
375 static bool CreateRegExpErrorObjectAndThrow(Handle<JSRegExp> re,
377 Handle<String> error_message,
379 Factory* factory = isolate->factory();
380 Handle<FixedArray> elements = factory->NewFixedArray(2);
381 elements->set(0, re->Pattern());
382 elements->set(1, *error_message);
383 Handle<JSArray> array = factory->NewJSArrayWithElements(elements);
384 Handle<Object> regexp_err =
385 factory->NewSyntaxError("malformed_regexp", array);
386 isolate->Throw(*regexp_err);
391 bool RegExpImpl::CompileIrregexp(Handle<JSRegExp> re,
392 Handle<String> sample_subject,
394 // Compile the RegExp.
395 Isolate* isolate = re->GetIsolate();
397 PostponeInterruptsScope postpone(isolate);
398 // If we had a compilation error the last time this is saved at the
400 Object* entry = re->DataAt(JSRegExp::code_index(is_ascii));
401 // When arriving here entry can only be a smi, either representing an
402 // uncompiled regexp, a previous compilation error, or code that has
404 DCHECK(entry->IsSmi());
405 int entry_value = Smi::cast(entry)->value();
406 DCHECK(entry_value == JSRegExp::kUninitializedValue ||
407 entry_value == JSRegExp::kCompilationErrorValue ||
408 (entry_value < JSRegExp::kCodeAgeMask && entry_value >= 0));
410 if (entry_value == JSRegExp::kCompilationErrorValue) {
411 // A previous compilation failed and threw an error which we store in
412 // the saved code index (we store the error message, not the actual
413 // error). Recreate the error object and throw it.
414 Object* error_string = re->DataAt(JSRegExp::saved_code_index(is_ascii));
415 DCHECK(error_string->IsString());
416 Handle<String> error_message(String::cast(error_string));
417 CreateRegExpErrorObjectAndThrow(re, is_ascii, error_message, isolate);
421 JSRegExp::Flags flags = re->GetFlags();
423 Handle<String> pattern(re->Pattern());
424 pattern = String::Flatten(pattern);
425 RegExpCompileData compile_data;
426 FlatStringReader reader(isolate, pattern);
427 if (!RegExpParser::ParseRegExp(&reader, flags.is_multiline(),
430 // Throw an exception if we fail to parse the pattern.
431 // THIS SHOULD NOT HAPPEN. We already pre-parsed it successfully once.
432 USE(ThrowRegExpException(re,
435 "malformed_regexp"));
438 RegExpEngine::CompilationResult result =
439 RegExpEngine::Compile(&compile_data,
440 flags.is_ignore_case(),
442 flags.is_multiline(),
447 if (result.error_message != NULL) {
448 // Unable to compile regexp.
449 Handle<String> error_message = isolate->factory()->NewStringFromUtf8(
450 CStrVector(result.error_message)).ToHandleChecked();
451 CreateRegExpErrorObjectAndThrow(re, is_ascii, error_message, isolate);
455 Handle<FixedArray> data = Handle<FixedArray>(FixedArray::cast(re->data()));
456 data->set(JSRegExp::code_index(is_ascii), result.code);
457 int register_max = IrregexpMaxRegisterCount(*data);
458 if (result.num_registers > register_max) {
459 SetIrregexpMaxRegisterCount(*data, result.num_registers);
466 int RegExpImpl::IrregexpMaxRegisterCount(FixedArray* re) {
468 re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
472 void RegExpImpl::SetIrregexpMaxRegisterCount(FixedArray* re, int value) {
473 re->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(value));
477 int RegExpImpl::IrregexpNumberOfCaptures(FixedArray* re) {
478 return Smi::cast(re->get(JSRegExp::kIrregexpCaptureCountIndex))->value();
482 int RegExpImpl::IrregexpNumberOfRegisters(FixedArray* re) {
483 return Smi::cast(re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
487 ByteArray* RegExpImpl::IrregexpByteCode(FixedArray* re, bool is_ascii) {
488 return ByteArray::cast(re->get(JSRegExp::code_index(is_ascii)));
492 Code* RegExpImpl::IrregexpNativeCode(FixedArray* re, bool is_ascii) {
493 return Code::cast(re->get(JSRegExp::code_index(is_ascii)));
497 void RegExpImpl::IrregexpInitialize(Handle<JSRegExp> re,
498 Handle<String> pattern,
499 JSRegExp::Flags flags,
501 // Initialize compiled code entries to null.
502 re->GetIsolate()->factory()->SetRegExpIrregexpData(re,
510 int RegExpImpl::IrregexpPrepare(Handle<JSRegExp> regexp,
511 Handle<String> subject) {
512 subject = String::Flatten(subject);
514 // Check the asciiness of the underlying storage.
515 bool is_ascii = subject->IsOneByteRepresentationUnderneath();
516 if (!EnsureCompiledIrregexp(regexp, subject, is_ascii)) return -1;
518 #ifdef V8_INTERPRETED_REGEXP
519 // Byte-code regexp needs space allocated for all its registers.
520 // The result captures are copied to the start of the registers array
521 // if the match succeeds. This way those registers are not clobbered
522 // when we set the last match info from last successful match.
523 return IrregexpNumberOfRegisters(FixedArray::cast(regexp->data())) +
524 (IrregexpNumberOfCaptures(FixedArray::cast(regexp->data())) + 1) * 2;
525 #else // V8_INTERPRETED_REGEXP
526 // Native regexp only needs room to output captures. Registers are handled
528 return (IrregexpNumberOfCaptures(FixedArray::cast(regexp->data())) + 1) * 2;
529 #endif // V8_INTERPRETED_REGEXP
533 int RegExpImpl::IrregexpExecRaw(Handle<JSRegExp> regexp,
534 Handle<String> subject,
538 Isolate* isolate = regexp->GetIsolate();
540 Handle<FixedArray> irregexp(FixedArray::cast(regexp->data()), isolate);
543 DCHECK(index <= subject->length());
544 DCHECK(subject->IsFlat());
546 bool is_ascii = subject->IsOneByteRepresentationUnderneath();
548 #ifndef V8_INTERPRETED_REGEXP
549 DCHECK(output_size >= (IrregexpNumberOfCaptures(*irregexp) + 1) * 2);
551 EnsureCompiledIrregexp(regexp, subject, is_ascii);
552 Handle<Code> code(IrregexpNativeCode(*irregexp, is_ascii), isolate);
553 // The stack is used to allocate registers for the compiled regexp code.
554 // This means that in case of failure, the output registers array is left
555 // untouched and contains the capture results from the previous successful
556 // match. We can use that to set the last match info lazily.
557 NativeRegExpMacroAssembler::Result res =
558 NativeRegExpMacroAssembler::Match(code,
564 if (res != NativeRegExpMacroAssembler::RETRY) {
565 DCHECK(res != NativeRegExpMacroAssembler::EXCEPTION ||
566 isolate->has_pending_exception());
568 static_cast<int>(NativeRegExpMacroAssembler::SUCCESS) == RE_SUCCESS);
570 static_cast<int>(NativeRegExpMacroAssembler::FAILURE) == RE_FAILURE);
571 STATIC_ASSERT(static_cast<int>(NativeRegExpMacroAssembler::EXCEPTION)
573 return static_cast<IrregexpResult>(res);
575 // If result is RETRY, the string has changed representation, and we
576 // must restart from scratch.
577 // In this case, it means we must make sure we are prepared to handle
578 // the, potentially, different subject (the string can switch between
579 // being internal and external, and even between being ASCII and UC16,
580 // but the characters are always the same).
581 IrregexpPrepare(regexp, subject);
582 is_ascii = subject->IsOneByteRepresentationUnderneath();
586 #else // V8_INTERPRETED_REGEXP
588 DCHECK(output_size >= IrregexpNumberOfRegisters(*irregexp));
589 // We must have done EnsureCompiledIrregexp, so we can get the number of
591 int number_of_capture_registers =
592 (IrregexpNumberOfCaptures(*irregexp) + 1) * 2;
593 int32_t* raw_output = &output[number_of_capture_registers];
594 // We do not touch the actual capture result registers until we know there
595 // has been a match so that we can use those capture results to set the
597 for (int i = number_of_capture_registers - 1; i >= 0; i--) {
600 Handle<ByteArray> byte_codes(IrregexpByteCode(*irregexp, is_ascii), isolate);
602 IrregexpResult result = IrregexpInterpreter::Match(isolate,
607 if (result == RE_SUCCESS) {
608 // Copy capture results to the start of the registers array.
609 MemCopy(output, raw_output, number_of_capture_registers * sizeof(int32_t));
611 if (result == RE_EXCEPTION) {
612 DCHECK(!isolate->has_pending_exception());
613 isolate->StackOverflow();
616 #endif // V8_INTERPRETED_REGEXP
620 MaybeHandle<Object> RegExpImpl::IrregexpExec(Handle<JSRegExp> regexp,
621 Handle<String> subject,
623 Handle<JSArray> last_match_info) {
624 Isolate* isolate = regexp->GetIsolate();
625 DCHECK_EQ(regexp->TypeTag(), JSRegExp::IRREGEXP);
627 // Prepare space for the return values.
628 #if defined(V8_INTERPRETED_REGEXP) && defined(DEBUG)
629 if (FLAG_trace_regexp_bytecodes) {
630 String* pattern = regexp->Pattern();
631 PrintF("\n\nRegexp match: /%s/\n\n", pattern->ToCString().get());
632 PrintF("\n\nSubject string: '%s'\n\n", subject->ToCString().get());
635 int required_registers = RegExpImpl::IrregexpPrepare(regexp, subject);
636 if (required_registers < 0) {
637 // Compiling failed with an exception.
638 DCHECK(isolate->has_pending_exception());
639 return MaybeHandle<Object>();
642 int32_t* output_registers = NULL;
643 if (required_registers > Isolate::kJSRegexpStaticOffsetsVectorSize) {
644 output_registers = NewArray<int32_t>(required_registers);
646 SmartArrayPointer<int32_t> auto_release(output_registers);
647 if (output_registers == NULL) {
648 output_registers = isolate->jsregexp_static_offsets_vector();
651 int res = RegExpImpl::IrregexpExecRaw(
652 regexp, subject, previous_index, output_registers, required_registers);
653 if (res == RE_SUCCESS) {
655 IrregexpNumberOfCaptures(FixedArray::cast(regexp->data()));
656 return SetLastMatchInfo(
657 last_match_info, subject, capture_count, output_registers);
659 if (res == RE_EXCEPTION) {
660 DCHECK(isolate->has_pending_exception());
661 return MaybeHandle<Object>();
663 DCHECK(res == RE_FAILURE);
664 return isolate->factory()->null_value();
668 Handle<JSArray> RegExpImpl::SetLastMatchInfo(Handle<JSArray> last_match_info,
669 Handle<String> subject,
672 DCHECK(last_match_info->HasFastObjectElements());
673 int capture_register_count = (capture_count + 1) * 2;
674 JSArray::EnsureSize(last_match_info,
675 capture_register_count + kLastMatchOverhead);
676 DisallowHeapAllocation no_allocation;
677 FixedArray* array = FixedArray::cast(last_match_info->elements());
679 for (int i = 0; i < capture_register_count; i += 2) {
680 SetCapture(array, i, match[i]);
681 SetCapture(array, i + 1, match[i + 1]);
684 SetLastCaptureCount(array, capture_register_count);
685 SetLastSubject(array, *subject);
686 SetLastInput(array, *subject);
687 return last_match_info;
691 RegExpImpl::GlobalCache::GlobalCache(Handle<JSRegExp> regexp,
692 Handle<String> subject,
695 : register_array_(NULL),
696 register_array_size_(0),
699 #ifdef V8_INTERPRETED_REGEXP
700 bool interpreted = true;
702 bool interpreted = false;
703 #endif // V8_INTERPRETED_REGEXP
705 if (regexp_->TypeTag() == JSRegExp::ATOM) {
706 static const int kAtomRegistersPerMatch = 2;
707 registers_per_match_ = kAtomRegistersPerMatch;
708 // There is no distinction between interpreted and native for atom regexps.
711 registers_per_match_ = RegExpImpl::IrregexpPrepare(regexp_, subject_);
712 if (registers_per_match_ < 0) {
713 num_matches_ = -1; // Signal exception.
718 if (is_global && !interpreted) {
719 register_array_size_ =
720 Max(registers_per_match_, Isolate::kJSRegexpStaticOffsetsVectorSize);
721 max_matches_ = register_array_size_ / registers_per_match_;
723 // Global loop in interpreted regexp is not implemented. We choose
724 // the size of the offsets vector so that it can only store one match.
725 register_array_size_ = registers_per_match_;
729 if (register_array_size_ > Isolate::kJSRegexpStaticOffsetsVectorSize) {
730 register_array_ = NewArray<int32_t>(register_array_size_);
732 register_array_ = isolate->jsregexp_static_offsets_vector();
735 // Set state so that fetching the results the first time triggers a call
736 // to the compiled regexp.
737 current_match_index_ = max_matches_ - 1;
738 num_matches_ = max_matches_;
739 DCHECK(registers_per_match_ >= 2); // Each match has at least one capture.
740 DCHECK_GE(register_array_size_, registers_per_match_);
741 int32_t* last_match =
742 ®ister_array_[current_match_index_ * registers_per_match_];
748 // -------------------------------------------------------------------
749 // Implementation of the Irregexp regular expression engine.
751 // The Irregexp regular expression engine is intended to be a complete
752 // implementation of ECMAScript regular expressions. It generates either
753 // bytecodes or native code.
755 // The Irregexp regexp engine is structured in three steps.
756 // 1) The parser generates an abstract syntax tree. See ast.cc.
757 // 2) From the AST a node network is created. The nodes are all
758 // subclasses of RegExpNode. The nodes represent states when
759 // executing a regular expression. Several optimizations are
760 // performed on the node network.
761 // 3) From the nodes we generate either byte codes or native code
762 // that can actually execute the regular expression (perform
763 // the search). The code generation step is described in more
768 // The nodes are divided into four main categories.
770 // These represent places where the regular expression can
771 // match in more than one way. For example on entry to an
772 // alternation (foo|bar) or a repetition (*, +, ? or {}).
774 // These represent places where some action should be
775 // performed. Examples include recording the current position
776 // in the input string to a register (in order to implement
777 // captures) or other actions on register for example in order
778 // to implement the counters needed for {} repetitions.
780 // These attempt to match some element part of the input string.
781 // Examples of elements include character classes, plain strings
782 // or back references.
784 // These are used to implement the actions required on finding
785 // a successful match or failing to find a match.
787 // The code generated (whether as byte codes or native code) maintains
788 // some state as it runs. This consists of the following elements:
790 // * The capture registers. Used for string captures.
791 // * Other registers. Used for counters etc.
792 // * The current position.
793 // * The stack of backtracking information. Used when a matching node
794 // fails to find a match and needs to try an alternative.
796 // Conceptual regular expression execution model:
798 // There is a simple conceptual model of regular expression execution
799 // which will be presented first. The actual code generated is a more
800 // efficient simulation of the simple conceptual model:
802 // * Choice nodes are implemented as follows:
803 // For each choice except the last {
804 // push current position
805 // push backtrack code location
806 // <generate code to test for choice>
807 // backtrack code location:
808 // pop current position
810 // <generate code to test for last choice>
812 // * Actions nodes are generated as follows
813 // <push affected registers on backtrack stack>
814 // <generate code to perform action>
815 // push backtrack code location
816 // <generate code to test for following nodes>
817 // backtrack code location:
818 // <pop affected registers to restore their state>
819 // <pop backtrack location from stack and go to it>
821 // * Matching nodes are generated as follows:
822 // if input string matches at current position
823 // update current position
824 // <generate code to test for following nodes>
826 // <pop backtrack location from stack and go to it>
828 // Thus it can be seen that the current position is saved and restored
829 // by the choice nodes, whereas the registers are saved and restored by
830 // by the action nodes that manipulate them.
832 // The other interesting aspect of this model is that nodes are generated
833 // at the point where they are needed by a recursive call to Emit(). If
834 // the node has already been code generated then the Emit() call will
835 // generate a jump to the previously generated code instead. In order to
836 // limit recursion it is possible for the Emit() function to put the node
837 // on a work list for later generation and instead generate a jump. The
838 // destination of the jump is resolved later when the code is generated.
840 // Actual regular expression code generation.
842 // Code generation is actually more complicated than the above. In order
843 // to improve the efficiency of the generated code some optimizations are
846 // * Choice nodes have 1-character lookahead.
847 // A choice node looks at the following character and eliminates some of
848 // the choices immediately based on that character. This is not yet
850 // * Simple greedy loops store reduced backtracking information.
851 // A quantifier like /.*foo/m will greedily match the whole input. It will
852 // then need to backtrack to a point where it can match "foo". The naive
853 // implementation of this would push each character position onto the
854 // backtracking stack, then pop them off one by one. This would use space
855 // proportional to the length of the input string. However since the "."
856 // can only match in one way and always has a constant length (in this case
857 // of 1) it suffices to store the current position on the top of the stack
858 // once. Matching now becomes merely incrementing the current position and
859 // backtracking becomes decrementing the current position and checking the
860 // result against the stored current position. This is faster and saves
862 // * The current state is virtualized.
863 // This is used to defer expensive operations until it is clear that they
864 // are needed and to generate code for a node more than once, allowing
865 // specialized an efficient versions of the code to be created. This is
866 // explained in the section below.
868 // Execution state virtualization.
870 // Instead of emitting code, nodes that manipulate the state can record their
871 // manipulation in an object called the Trace. The Trace object can record a
872 // current position offset, an optional backtrack code location on the top of
873 // the virtualized backtrack stack and some register changes. When a node is
874 // to be emitted it can flush the Trace or update it. Flushing the Trace
875 // will emit code to bring the actual state into line with the virtual state.
876 // Avoiding flushing the state can postpone some work (e.g. updates of capture
877 // registers). Postponing work can save time when executing the regular
878 // expression since it may be found that the work never has to be done as a
879 // failure to match can occur. In addition it is much faster to jump to a
880 // known backtrack code location than it is to pop an unknown backtrack
881 // location from the stack and jump there.
883 // The virtual state found in the Trace affects code generation. For example
884 // the virtual state contains the difference between the actual current
885 // position and the virtual current position, and matching code needs to use
886 // this offset to attempt a match in the correct location of the input
887 // string. Therefore code generated for a non-trivial trace is specialized
888 // to that trace. The code generator therefore has the ability to generate
889 // code for each node several times. In order to limit the size of the
890 // generated code there is an arbitrary limit on how many specialized sets of
891 // code may be generated for a given node. If the limit is reached, the
892 // trace is flushed and a generic version of the code for a node is emitted.
893 // This is subsequently used for that node. The code emitted for non-generic
894 // trace is not recorded in the node and so it cannot currently be reused in
895 // the event that code generation is requested for an identical trace.
898 void RegExpTree::AppendToText(RegExpText* text, Zone* zone) {
903 void RegExpAtom::AppendToText(RegExpText* text, Zone* zone) {
904 text->AddElement(TextElement::Atom(this), zone);
908 void RegExpCharacterClass::AppendToText(RegExpText* text, Zone* zone) {
909 text->AddElement(TextElement::CharClass(this), zone);
913 void RegExpText::AppendToText(RegExpText* text, Zone* zone) {
914 for (int i = 0; i < elements()->length(); i++)
915 text->AddElement(elements()->at(i), zone);
919 TextElement TextElement::Atom(RegExpAtom* atom) {
920 return TextElement(ATOM, atom);
924 TextElement TextElement::CharClass(RegExpCharacterClass* char_class) {
925 return TextElement(CHAR_CLASS, char_class);
929 int TextElement::length() const {
930 switch (text_type()) {
932 return atom()->length();
942 DispatchTable* ChoiceNode::GetTable(bool ignore_case) {
943 if (table_ == NULL) {
944 table_ = new(zone()) DispatchTable(zone());
945 DispatchTableConstructor cons(table_, ignore_case, zone());
946 cons.BuildTable(this);
952 class FrequencyCollator {
954 FrequencyCollator() : total_samples_(0) {
955 for (int i = 0; i < RegExpMacroAssembler::kTableSize; i++) {
956 frequencies_[i] = CharacterFrequency(i);
960 void CountCharacter(int character) {
961 int index = (character & RegExpMacroAssembler::kTableMask);
962 frequencies_[index].Increment();
966 // Does not measure in percent, but rather per-128 (the table size from the
967 // regexp macro assembler).
968 int Frequency(int in_character) {
969 DCHECK((in_character & RegExpMacroAssembler::kTableMask) == in_character);
970 if (total_samples_ < 1) return 1; // Division by zero.
972 (frequencies_[in_character].counter() * 128) / total_samples_;
973 return freq_in_per128;
977 class CharacterFrequency {
979 CharacterFrequency() : counter_(0), character_(-1) { }
980 explicit CharacterFrequency(int character)
981 : counter_(0), character_(character) { }
983 void Increment() { counter_++; }
984 int counter() { return counter_; }
985 int character() { return character_; }
994 CharacterFrequency frequencies_[RegExpMacroAssembler::kTableSize];
999 class RegExpCompiler {
1001 RegExpCompiler(int capture_count, bool ignore_case, bool is_ascii,
1004 int AllocateRegister() {
1005 if (next_register_ >= RegExpMacroAssembler::kMaxRegister) {
1006 reg_exp_too_big_ = true;
1007 return next_register_;
1009 return next_register_++;
1012 RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler,
1015 Handle<String> pattern);
1017 inline void AddWork(RegExpNode* node) { work_list_->Add(node); }
1019 static const int kImplementationOffset = 0;
1020 static const int kNumberOfRegistersOffset = 0;
1021 static const int kCodeOffset = 1;
1023 RegExpMacroAssembler* macro_assembler() { return macro_assembler_; }
1024 EndNode* accept() { return accept_; }
1026 static const int kMaxRecursion = 100;
1027 inline int recursion_depth() { return recursion_depth_; }
1028 inline void IncrementRecursionDepth() { recursion_depth_++; }
1029 inline void DecrementRecursionDepth() { recursion_depth_--; }
1031 void SetRegExpTooBig() { reg_exp_too_big_ = true; }
1033 inline bool ignore_case() { return ignore_case_; }
1034 inline bool ascii() { return ascii_; }
1035 FrequencyCollator* frequency_collator() { return &frequency_collator_; }
1037 int current_expansion_factor() { return current_expansion_factor_; }
1038 void set_current_expansion_factor(int value) {
1039 current_expansion_factor_ = value;
1042 Zone* zone() const { return zone_; }
1044 static const int kNoRegister = -1;
1049 List<RegExpNode*>* work_list_;
1050 int recursion_depth_;
1051 RegExpMacroAssembler* macro_assembler_;
1054 bool reg_exp_too_big_;
1055 int current_expansion_factor_;
1056 FrequencyCollator frequency_collator_;
1061 class RecursionCheck {
1063 explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
1064 compiler->IncrementRecursionDepth();
1066 ~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
1068 RegExpCompiler* compiler_;
1072 static RegExpEngine::CompilationResult IrregexpRegExpTooBig(Isolate* isolate) {
1073 return RegExpEngine::CompilationResult(isolate, "RegExp too big");
1077 // Attempts to compile the regexp using an Irregexp code generator. Returns
1078 // a fixed array or a null handle depending on whether it succeeded.
1079 RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case, bool ascii,
1081 : next_register_(2 * (capture_count + 1)),
1083 recursion_depth_(0),
1084 ignore_case_(ignore_case),
1086 reg_exp_too_big_(false),
1087 current_expansion_factor_(1),
1088 frequency_collator_(),
1090 accept_ = new(zone) EndNode(EndNode::ACCEPT, zone);
1091 DCHECK(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
1095 RegExpEngine::CompilationResult RegExpCompiler::Assemble(
1096 RegExpMacroAssembler* macro_assembler,
1099 Handle<String> pattern) {
1100 Heap* heap = pattern->GetHeap();
1102 bool use_slow_safe_regexp_compiler = false;
1103 if (heap->total_regexp_code_generated() >
1104 RegExpImpl::kRegWxpCompiledLimit &&
1105 heap->isolate()->memory_allocator()->SizeExecutable() >
1106 RegExpImpl::kRegExpExecutableMemoryLimit) {
1107 use_slow_safe_regexp_compiler = true;
1110 macro_assembler->set_slow_safe(use_slow_safe_regexp_compiler);
1113 if (FLAG_trace_regexp_assembler)
1114 macro_assembler_ = new RegExpMacroAssemblerTracer(macro_assembler);
1117 macro_assembler_ = macro_assembler;
1119 List <RegExpNode*> work_list(0);
1120 work_list_ = &work_list;
1122 macro_assembler_->PushBacktrack(&fail);
1124 start->Emit(this, &new_trace);
1125 macro_assembler_->Bind(&fail);
1126 macro_assembler_->Fail();
1127 while (!work_list.is_empty()) {
1128 work_list.RemoveLast()->Emit(this, &new_trace);
1130 if (reg_exp_too_big_) return IrregexpRegExpTooBig(zone_->isolate());
1132 Handle<HeapObject> code = macro_assembler_->GetCode(pattern);
1133 heap->IncreaseTotalRegexpCodeGenerated(code->Size());
1136 if (FLAG_print_code) {
1137 CodeTracer::Scope trace_scope(heap->isolate()->GetCodeTracer());
1138 OFStream os(trace_scope.file());
1139 Handle<Code>::cast(code)->Disassemble(pattern->ToCString().get(), os);
1141 if (FLAG_trace_regexp_assembler) {
1142 delete macro_assembler_;
1145 return RegExpEngine::CompilationResult(*code, next_register_);
1149 bool Trace::DeferredAction::Mentions(int that) {
1150 if (action_type() == ActionNode::CLEAR_CAPTURES) {
1151 Interval range = static_cast<DeferredClearCaptures*>(this)->range();
1152 return range.Contains(that);
1154 return reg() == that;
1159 bool Trace::mentions_reg(int reg) {
1160 for (DeferredAction* action = actions_;
1162 action = action->next()) {
1163 if (action->Mentions(reg))
1170 bool Trace::GetStoredPosition(int reg, int* cp_offset) {
1171 DCHECK_EQ(0, *cp_offset);
1172 for (DeferredAction* action = actions_;
1174 action = action->next()) {
1175 if (action->Mentions(reg)) {
1176 if (action->action_type() == ActionNode::STORE_POSITION) {
1177 *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
1188 int Trace::FindAffectedRegisters(OutSet* affected_registers,
1190 int max_register = RegExpCompiler::kNoRegister;
1191 for (DeferredAction* action = actions_;
1193 action = action->next()) {
1194 if (action->action_type() == ActionNode::CLEAR_CAPTURES) {
1195 Interval range = static_cast<DeferredClearCaptures*>(action)->range();
1196 for (int i = range.from(); i <= range.to(); i++)
1197 affected_registers->Set(i, zone);
1198 if (range.to() > max_register) max_register = range.to();
1200 affected_registers->Set(action->reg(), zone);
1201 if (action->reg() > max_register) max_register = action->reg();
1204 return max_register;
1208 void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
1210 const OutSet& registers_to_pop,
1211 const OutSet& registers_to_clear) {
1212 for (int reg = max_register; reg >= 0; reg--) {
1213 if (registers_to_pop.Get(reg)) {
1214 assembler->PopRegister(reg);
1215 } else if (registers_to_clear.Get(reg)) {
1217 while (reg > 0 && registers_to_clear.Get(reg - 1)) {
1220 assembler->ClearRegisters(reg, clear_to);
1226 void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
1228 const OutSet& affected_registers,
1229 OutSet* registers_to_pop,
1230 OutSet* registers_to_clear,
1232 // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
1233 const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
1235 // Count pushes performed to force a stack limit check occasionally.
1238 for (int reg = 0; reg <= max_register; reg++) {
1239 if (!affected_registers.Get(reg)) {
1243 // The chronologically first deferred action in the trace
1244 // is used to infer the action needed to restore a register
1245 // to its previous state (or not, if it's safe to ignore it).
1246 enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
1247 DeferredActionUndoType undo_action = IGNORE;
1250 bool absolute = false;
1252 int store_position = -1;
1253 // This is a little tricky because we are scanning the actions in reverse
1254 // historical order (newest first).
1255 for (DeferredAction* action = actions_;
1257 action = action->next()) {
1258 if (action->Mentions(reg)) {
1259 switch (action->action_type()) {
1260 case ActionNode::SET_REGISTER: {
1261 Trace::DeferredSetRegister* psr =
1262 static_cast<Trace::DeferredSetRegister*>(action);
1264 value += psr->value();
1267 // SET_REGISTER is currently only used for newly introduced loop
1268 // counters. They can have a significant previous value if they
1269 // occour in a loop. TODO(lrn): Propagate this information, so
1270 // we can set undo_action to IGNORE if we know there is no value to
1272 undo_action = RESTORE;
1273 DCHECK_EQ(store_position, -1);
1277 case ActionNode::INCREMENT_REGISTER:
1281 DCHECK_EQ(store_position, -1);
1283 undo_action = RESTORE;
1285 case ActionNode::STORE_POSITION: {
1286 Trace::DeferredCapture* pc =
1287 static_cast<Trace::DeferredCapture*>(action);
1288 if (!clear && store_position == -1) {
1289 store_position = pc->cp_offset();
1292 // For captures we know that stores and clears alternate.
1293 // Other register, are never cleared, and if the occur
1294 // inside a loop, they might be assigned more than once.
1296 // Registers zero and one, aka "capture zero", is
1297 // always set correctly if we succeed. There is no
1298 // need to undo a setting on backtrack, because we
1299 // will set it again or fail.
1300 undo_action = IGNORE;
1302 undo_action = pc->is_capture() ? CLEAR : RESTORE;
1305 DCHECK_EQ(value, 0);
1308 case ActionNode::CLEAR_CAPTURES: {
1309 // Since we're scanning in reverse order, if we've already
1310 // set the position we have to ignore historically earlier
1311 // clearing operations.
1312 if (store_position == -1) {
1315 undo_action = RESTORE;
1317 DCHECK_EQ(value, 0);
1326 // Prepare for the undo-action (e.g., push if it's going to be popped).
1327 if (undo_action == RESTORE) {
1329 RegExpMacroAssembler::StackCheckFlag stack_check =
1330 RegExpMacroAssembler::kNoStackLimitCheck;
1331 if (pushes == push_limit) {
1332 stack_check = RegExpMacroAssembler::kCheckStackLimit;
1336 assembler->PushRegister(reg, stack_check);
1337 registers_to_pop->Set(reg, zone);
1338 } else if (undo_action == CLEAR) {
1339 registers_to_clear->Set(reg, zone);
1341 // Perform the chronologically last action (or accumulated increment)
1342 // for the register.
1343 if (store_position != -1) {
1344 assembler->WriteCurrentPositionToRegister(reg, store_position);
1346 assembler->ClearRegisters(reg, reg);
1347 } else if (absolute) {
1348 assembler->SetRegister(reg, value);
1349 } else if (value != 0) {
1350 assembler->AdvanceRegister(reg, value);
1356 // This is called as we come into a loop choice node and some other tricky
1357 // nodes. It normalizes the state of the code generator to ensure we can
1358 // generate generic code.
1359 void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
1360 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1362 DCHECK(!is_trivial());
1364 if (actions_ == NULL && backtrack() == NULL) {
1365 // Here we just have some deferred cp advances to fix and we are back to
1366 // a normal situation. We may also have to forget some information gained
1367 // through a quick check that was already performed.
1368 if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
1369 // Create a new trivial state and generate the node with that.
1371 successor->Emit(compiler, &new_state);
1375 // Generate deferred actions here along with code to undo them again.
1376 OutSet affected_registers;
1378 if (backtrack() != NULL) {
1379 // Here we have a concrete backtrack location. These are set up by choice
1380 // nodes and so they indicate that we have a deferred save of the current
1381 // position which we may need to emit here.
1382 assembler->PushCurrentPosition();
1385 int max_register = FindAffectedRegisters(&affected_registers,
1387 OutSet registers_to_pop;
1388 OutSet registers_to_clear;
1389 PerformDeferredActions(assembler,
1393 ®isters_to_clear,
1395 if (cp_offset_ != 0) {
1396 assembler->AdvanceCurrentPosition(cp_offset_);
1399 // Create a new trivial state and generate the node with that.
1401 assembler->PushBacktrack(&undo);
1403 successor->Emit(compiler, &new_state);
1405 // On backtrack we need to restore state.
1406 assembler->Bind(&undo);
1407 RestoreAffectedRegisters(assembler,
1410 registers_to_clear);
1411 if (backtrack() == NULL) {
1412 assembler->Backtrack();
1414 assembler->PopCurrentPosition();
1415 assembler->GoTo(backtrack());
1420 void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
1421 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1423 // Omit flushing the trace. We discard the entire stack frame anyway.
1425 if (!label()->is_bound()) {
1426 // We are completely independent of the trace, since we ignore it,
1427 // so this code can be used as the generic version.
1428 assembler->Bind(label());
1431 // Throw away everything on the backtrack stack since the start
1432 // of the negative submatch and restore the character position.
1433 assembler->ReadCurrentPositionFromRegister(current_position_register_);
1434 assembler->ReadStackPointerFromRegister(stack_pointer_register_);
1435 if (clear_capture_count_ > 0) {
1436 // Clear any captures that might have been performed during the success
1437 // of the body of the negative look-ahead.
1438 int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
1439 assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
1441 // Now that we have unwound the stack we find at the top of the stack the
1442 // backtrack that the BeginSubmatch node got.
1443 assembler->Backtrack();
1447 void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
1448 if (!trace->is_trivial()) {
1449 trace->Flush(compiler, this);
1452 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1453 if (!label()->is_bound()) {
1454 assembler->Bind(label());
1458 assembler->Succeed();
1461 assembler->GoTo(trace->backtrack());
1463 case NEGATIVE_SUBMATCH_SUCCESS:
1464 // This case is handled in a different virtual method.
1471 void GuardedAlternative::AddGuard(Guard* guard, Zone* zone) {
1472 if (guards_ == NULL)
1473 guards_ = new(zone) ZoneList<Guard*>(1, zone);
1474 guards_->Add(guard, zone);
1478 ActionNode* ActionNode::SetRegister(int reg,
1480 RegExpNode* on_success) {
1481 ActionNode* result =
1482 new(on_success->zone()) ActionNode(SET_REGISTER, on_success);
1483 result->data_.u_store_register.reg = reg;
1484 result->data_.u_store_register.value = val;
1489 ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
1490 ActionNode* result =
1491 new(on_success->zone()) ActionNode(INCREMENT_REGISTER, on_success);
1492 result->data_.u_increment_register.reg = reg;
1497 ActionNode* ActionNode::StorePosition(int reg,
1499 RegExpNode* on_success) {
1500 ActionNode* result =
1501 new(on_success->zone()) ActionNode(STORE_POSITION, on_success);
1502 result->data_.u_position_register.reg = reg;
1503 result->data_.u_position_register.is_capture = is_capture;
1508 ActionNode* ActionNode::ClearCaptures(Interval range,
1509 RegExpNode* on_success) {
1510 ActionNode* result =
1511 new(on_success->zone()) ActionNode(CLEAR_CAPTURES, on_success);
1512 result->data_.u_clear_captures.range_from = range.from();
1513 result->data_.u_clear_captures.range_to = range.to();
1518 ActionNode* ActionNode::BeginSubmatch(int stack_reg,
1520 RegExpNode* on_success) {
1521 ActionNode* result =
1522 new(on_success->zone()) ActionNode(BEGIN_SUBMATCH, on_success);
1523 result->data_.u_submatch.stack_pointer_register = stack_reg;
1524 result->data_.u_submatch.current_position_register = position_reg;
1529 ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
1531 int clear_register_count,
1532 int clear_register_from,
1533 RegExpNode* on_success) {
1534 ActionNode* result =
1535 new(on_success->zone()) ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
1536 result->data_.u_submatch.stack_pointer_register = stack_reg;
1537 result->data_.u_submatch.current_position_register = position_reg;
1538 result->data_.u_submatch.clear_register_count = clear_register_count;
1539 result->data_.u_submatch.clear_register_from = clear_register_from;
1544 ActionNode* ActionNode::EmptyMatchCheck(int start_register,
1545 int repetition_register,
1546 int repetition_limit,
1547 RegExpNode* on_success) {
1548 ActionNode* result =
1549 new(on_success->zone()) ActionNode(EMPTY_MATCH_CHECK, on_success);
1550 result->data_.u_empty_match_check.start_register = start_register;
1551 result->data_.u_empty_match_check.repetition_register = repetition_register;
1552 result->data_.u_empty_match_check.repetition_limit = repetition_limit;
1557 #define DEFINE_ACCEPT(Type) \
1558 void Type##Node::Accept(NodeVisitor* visitor) { \
1559 visitor->Visit##Type(this); \
1561 FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
1562 #undef DEFINE_ACCEPT
1565 void LoopChoiceNode::Accept(NodeVisitor* visitor) {
1566 visitor->VisitLoopChoice(this);
1570 // -------------------------------------------------------------------
1574 void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
1577 switch (guard->op()) {
1579 DCHECK(!trace->mentions_reg(guard->reg()));
1580 macro_assembler->IfRegisterGE(guard->reg(),
1582 trace->backtrack());
1585 DCHECK(!trace->mentions_reg(guard->reg()));
1586 macro_assembler->IfRegisterLT(guard->reg(),
1588 trace->backtrack());
1594 // Returns the number of characters in the equivalence class, omitting those
1595 // that cannot occur in the source string because it is ASCII.
1596 static int GetCaseIndependentLetters(Isolate* isolate,
1599 unibrow::uchar* letters) {
1601 isolate->jsregexp_uncanonicalize()->get(character, '\0', letters);
1602 // Unibrow returns 0 or 1 for characters where case independence is
1605 letters[0] = character;
1608 if (!ascii_subject || character <= String::kMaxOneByteCharCode) {
1611 // The standard requires that non-ASCII characters cannot have ASCII
1612 // character codes in their equivalence class.
1617 static inline bool EmitSimpleCharacter(Isolate* isolate,
1618 RegExpCompiler* compiler,
1624 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1625 bool bound_checked = false;
1627 assembler->LoadCurrentCharacter(
1631 bound_checked = true;
1633 assembler->CheckNotCharacter(c, on_failure);
1634 return bound_checked;
1638 // Only emits non-letters (things that don't have case). Only used for case
1639 // independent matches.
1640 static inline bool EmitAtomNonLetter(Isolate* isolate,
1641 RegExpCompiler* compiler,
1647 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1648 bool ascii = compiler->ascii();
1649 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
1650 int length = GetCaseIndependentLetters(isolate, c, ascii, chars);
1652 // This can't match. Must be an ASCII subject and a non-ASCII character.
1653 // We do not need to do anything since the ASCII pass already handled this.
1654 return false; // Bounds not checked.
1656 bool checked = false;
1657 // We handle the length > 1 case in a later pass.
1659 if (ascii && c > String::kMaxOneByteCharCodeU) {
1660 // Can't match - see above.
1661 return false; // Bounds not checked.
1664 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1667 macro_assembler->CheckNotCharacter(c, on_failure);
1673 static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
1677 Label* on_failure) {
1680 char_mask = String::kMaxOneByteCharCode;
1682 char_mask = String::kMaxUtf16CodeUnit;
1684 uc16 exor = c1 ^ c2;
1685 // Check whether exor has only one bit set.
1686 if (((exor - 1) & exor) == 0) {
1687 // If c1 and c2 differ only by one bit.
1688 // Ecma262UnCanonicalize always gives the highest number last.
1690 uc16 mask = char_mask ^ exor;
1691 macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
1695 uc16 diff = c2 - c1;
1696 if (((diff - 1) & diff) == 0 && c1 >= diff) {
1697 // If the characters differ by 2^n but don't differ by one bit then
1698 // subtract the difference from the found character, then do the or
1699 // trick. We avoid the theoretical case where negative numbers are
1700 // involved in order to simplify code generation.
1701 uc16 mask = char_mask ^ diff;
1702 macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff,
1712 typedef bool EmitCharacterFunction(Isolate* isolate,
1713 RegExpCompiler* compiler,
1720 // Only emits letters (things that have case). Only used for case independent
1722 static inline bool EmitAtomLetter(Isolate* isolate,
1723 RegExpCompiler* compiler,
1729 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1730 bool ascii = compiler->ascii();
1731 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
1732 int length = GetCaseIndependentLetters(isolate, c, ascii, chars);
1733 if (length <= 1) return false;
1734 // We may not need to check against the end of the input string
1735 // if this character lies before a character that matched.
1737 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1740 DCHECK(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4);
1743 if (ShortCutEmitCharacterPair(macro_assembler,
1749 macro_assembler->CheckCharacter(chars[0], &ok);
1750 macro_assembler->CheckNotCharacter(chars[1], on_failure);
1751 macro_assembler->Bind(&ok);
1756 macro_assembler->CheckCharacter(chars[3], &ok);
1759 macro_assembler->CheckCharacter(chars[0], &ok);
1760 macro_assembler->CheckCharacter(chars[1], &ok);
1761 macro_assembler->CheckNotCharacter(chars[2], on_failure);
1762 macro_assembler->Bind(&ok);
1772 static void EmitBoundaryTest(RegExpMacroAssembler* masm,
1774 Label* fall_through,
1775 Label* above_or_equal,
1777 if (below != fall_through) {
1778 masm->CheckCharacterLT(border, below);
1779 if (above_or_equal != fall_through) masm->GoTo(above_or_equal);
1781 masm->CheckCharacterGT(border - 1, above_or_equal);
1786 static void EmitDoubleBoundaryTest(RegExpMacroAssembler* masm,
1789 Label* fall_through,
1791 Label* out_of_range) {
1792 if (in_range == fall_through) {
1793 if (first == last) {
1794 masm->CheckNotCharacter(first, out_of_range);
1796 masm->CheckCharacterNotInRange(first, last, out_of_range);
1799 if (first == last) {
1800 masm->CheckCharacter(first, in_range);
1802 masm->CheckCharacterInRange(first, last, in_range);
1804 if (out_of_range != fall_through) masm->GoTo(out_of_range);
1809 // even_label is for ranges[i] to ranges[i + 1] where i - start_index is even.
1810 // odd_label is for ranges[i] to ranges[i + 1] where i - start_index is odd.
1811 static void EmitUseLookupTable(
1812 RegExpMacroAssembler* masm,
1813 ZoneList<int>* ranges,
1817 Label* fall_through,
1820 static const int kSize = RegExpMacroAssembler::kTableSize;
1821 static const int kMask = RegExpMacroAssembler::kTableMask;
1823 int base = (min_char & ~kMask);
1826 // Assert that everything is on one kTableSize page.
1827 for (int i = start_index; i <= end_index; i++) {
1828 DCHECK_EQ(ranges->at(i) & ~kMask, base);
1830 DCHECK(start_index == 0 || (ranges->at(start_index - 1) & ~kMask) <= base);
1834 Label* on_bit_clear;
1836 if (even_label == fall_through) {
1837 on_bit_set = odd_label;
1838 on_bit_clear = even_label;
1841 on_bit_set = even_label;
1842 on_bit_clear = odd_label;
1845 for (int i = 0; i < (ranges->at(start_index) & kMask) && i < kSize; i++) {
1850 for (int i = start_index; i < end_index; i++) {
1851 for (j = (ranges->at(i) & kMask); j < (ranges->at(i + 1) & kMask); j++) {
1856 for (int i = j; i < kSize; i++) {
1859 Factory* factory = masm->zone()->isolate()->factory();
1860 // TODO(erikcorry): Cache these.
1861 Handle<ByteArray> ba = factory->NewByteArray(kSize, TENURED);
1862 for (int i = 0; i < kSize; i++) {
1863 ba->set(i, templ[i]);
1865 masm->CheckBitInTable(ba, on_bit_set);
1866 if (on_bit_clear != fall_through) masm->GoTo(on_bit_clear);
1870 static void CutOutRange(RegExpMacroAssembler* masm,
1871 ZoneList<int>* ranges,
1877 bool odd = (((cut_index - start_index) & 1) == 1);
1878 Label* in_range_label = odd ? odd_label : even_label;
1880 EmitDoubleBoundaryTest(masm,
1881 ranges->at(cut_index),
1882 ranges->at(cut_index + 1) - 1,
1886 DCHECK(!dummy.is_linked());
1887 // Cut out the single range by rewriting the array. This creates a new
1888 // range that is a merger of the two ranges on either side of the one we
1889 // are cutting out. The oddity of the labels is preserved.
1890 for (int j = cut_index; j > start_index; j--) {
1891 ranges->at(j) = ranges->at(j - 1);
1893 for (int j = cut_index + 1; j < end_index; j++) {
1894 ranges->at(j) = ranges->at(j + 1);
1899 // Unicode case. Split the search space into kSize spaces that are handled
1901 static void SplitSearchSpace(ZoneList<int>* ranges,
1904 int* new_start_index,
1907 static const int kSize = RegExpMacroAssembler::kTableSize;
1908 static const int kMask = RegExpMacroAssembler::kTableMask;
1910 int first = ranges->at(start_index);
1911 int last = ranges->at(end_index) - 1;
1913 *new_start_index = start_index;
1914 *border = (ranges->at(start_index) & ~kMask) + kSize;
1915 while (*new_start_index < end_index) {
1916 if (ranges->at(*new_start_index) > *border) break;
1917 (*new_start_index)++;
1919 // new_start_index is the index of the first edge that is beyond the
1920 // current kSize space.
1922 // For very large search spaces we do a binary chop search of the non-ASCII
1923 // space instead of just going to the end of the current kSize space. The
1924 // heuristics are complicated a little by the fact that any 128-character
1925 // encoding space can be quickly tested with a table lookup, so we don't
1926 // wish to do binary chop search at a smaller granularity than that. A
1927 // 128-character space can take up a lot of space in the ranges array if,
1928 // for example, we only want to match every second character (eg. the lower
1929 // case characters on some Unicode pages).
1930 int binary_chop_index = (end_index + start_index) / 2;
1931 // The first test ensures that we get to the code that handles the ASCII
1932 // range with a single not-taken branch, speeding up this important
1933 // character range (even non-ASCII charset-based text has spaces and
1935 if (*border - 1 > String::kMaxOneByteCharCode && // ASCII case.
1936 end_index - start_index > (*new_start_index - start_index) * 2 &&
1937 last - first > kSize * 2 &&
1938 binary_chop_index > *new_start_index &&
1939 ranges->at(binary_chop_index) >= first + 2 * kSize) {
1940 int scan_forward_for_section_border = binary_chop_index;;
1941 int new_border = (ranges->at(binary_chop_index) | kMask) + 1;
1943 while (scan_forward_for_section_border < end_index) {
1944 if (ranges->at(scan_forward_for_section_border) > new_border) {
1945 *new_start_index = scan_forward_for_section_border;
1946 *border = new_border;
1949 scan_forward_for_section_border++;
1953 DCHECK(*new_start_index > start_index);
1954 *new_end_index = *new_start_index - 1;
1955 if (ranges->at(*new_end_index) == *border) {
1958 if (*border >= ranges->at(end_index)) {
1959 *border = ranges->at(end_index);
1960 *new_start_index = end_index; // Won't be used.
1961 *new_end_index = end_index - 1;
1966 // Gets a series of segment boundaries representing a character class. If the
1967 // character is in the range between an even and an odd boundary (counting from
1968 // start_index) then go to even_label, otherwise go to odd_label. We already
1969 // know that the character is in the range of min_char to max_char inclusive.
1970 // Either label can be NULL indicating backtracking. Either label can also be
1971 // equal to the fall_through label.
1972 static void GenerateBranches(RegExpMacroAssembler* masm,
1973 ZoneList<int>* ranges,
1978 Label* fall_through,
1981 int first = ranges->at(start_index);
1982 int last = ranges->at(end_index) - 1;
1984 DCHECK_LT(min_char, first);
1986 // Just need to test if the character is before or on-or-after
1987 // a particular character.
1988 if (start_index == end_index) {
1989 EmitBoundaryTest(masm, first, fall_through, even_label, odd_label);
1993 // Another almost trivial case: There is one interval in the middle that is
1994 // different from the end intervals.
1995 if (start_index + 1 == end_index) {
1996 EmitDoubleBoundaryTest(
1997 masm, first, last, fall_through, even_label, odd_label);
2001 // It's not worth using table lookup if there are very few intervals in the
2003 if (end_index - start_index <= 6) {
2004 // It is faster to test for individual characters, so we look for those
2005 // first, then try arbitrary ranges in the second round.
2006 static int kNoCutIndex = -1;
2007 int cut = kNoCutIndex;
2008 for (int i = start_index; i < end_index; i++) {
2009 if (ranges->at(i) == ranges->at(i + 1) - 1) {
2014 if (cut == kNoCutIndex) cut = start_index;
2016 masm, ranges, start_index, end_index, cut, even_label, odd_label);
2017 DCHECK_GE(end_index - start_index, 2);
2018 GenerateBranches(masm,
2030 // If there are a lot of intervals in the regexp, then we will use tables to
2031 // determine whether the character is inside or outside the character class.
2032 static const int kBits = RegExpMacroAssembler::kTableSizeBits;
2034 if ((max_char >> kBits) == (min_char >> kBits)) {
2035 EmitUseLookupTable(masm,
2046 if ((min_char >> kBits) != (first >> kBits)) {
2047 masm->CheckCharacterLT(first, odd_label);
2048 GenerateBranches(masm,
2060 int new_start_index = 0;
2061 int new_end_index = 0;
2064 SplitSearchSpace(ranges,
2072 Label* above = &handle_rest;
2073 if (border == last + 1) {
2074 // We didn't find any section that started after the limit, so everything
2075 // above the border is one of the terminal labels.
2076 above = (end_index & 1) != (start_index & 1) ? odd_label : even_label;
2077 DCHECK(new_end_index == end_index - 1);
2080 DCHECK_LE(start_index, new_end_index);
2081 DCHECK_LE(new_start_index, end_index);
2082 DCHECK_LT(start_index, new_start_index);
2083 DCHECK_LT(new_end_index, end_index);
2084 DCHECK(new_end_index + 1 == new_start_index ||
2085 (new_end_index + 2 == new_start_index &&
2086 border == ranges->at(new_end_index + 1)));
2087 DCHECK_LT(min_char, border - 1);
2088 DCHECK_LT(border, max_char);
2089 DCHECK_LT(ranges->at(new_end_index), border);
2090 DCHECK(border < ranges->at(new_start_index) ||
2091 (border == ranges->at(new_start_index) &&
2092 new_start_index == end_index &&
2093 new_end_index == end_index - 1 &&
2094 border == last + 1));
2095 DCHECK(new_start_index == 0 || border >= ranges->at(new_start_index - 1));
2097 masm->CheckCharacterGT(border - 1, above);
2099 GenerateBranches(masm,
2108 if (handle_rest.is_linked()) {
2109 masm->Bind(&handle_rest);
2110 bool flip = (new_start_index & 1) != (start_index & 1);
2111 GenerateBranches(masm,
2118 flip ? odd_label : even_label,
2119 flip ? even_label : odd_label);
2124 static void EmitCharClass(RegExpMacroAssembler* macro_assembler,
2125 RegExpCharacterClass* cc,
2132 ZoneList<CharacterRange>* ranges = cc->ranges(zone);
2133 if (!CharacterRange::IsCanonical(ranges)) {
2134 CharacterRange::Canonicalize(ranges);
2139 max_char = String::kMaxOneByteCharCode;
2141 max_char = String::kMaxUtf16CodeUnit;
2144 int range_count = ranges->length();
2146 int last_valid_range = range_count - 1;
2147 while (last_valid_range >= 0) {
2148 CharacterRange& range = ranges->at(last_valid_range);
2149 if (range.from() <= max_char) {
2155 if (last_valid_range < 0) {
2156 if (!cc->is_negated()) {
2157 macro_assembler->GoTo(on_failure);
2160 macro_assembler->CheckPosition(cp_offset, on_failure);
2165 if (last_valid_range == 0 &&
2166 ranges->at(0).IsEverything(max_char)) {
2167 if (cc->is_negated()) {
2168 macro_assembler->GoTo(on_failure);
2170 // This is a common case hit by non-anchored expressions.
2172 macro_assembler->CheckPosition(cp_offset, on_failure);
2177 if (last_valid_range == 0 &&
2178 !cc->is_negated() &&
2179 ranges->at(0).IsEverything(max_char)) {
2180 // This is a common case hit by non-anchored expressions.
2182 macro_assembler->CheckPosition(cp_offset, on_failure);
2188 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset);
2191 if (cc->is_standard(zone) &&
2192 macro_assembler->CheckSpecialCharacterClass(cc->standard_type(),
2198 // A new list with ascending entries. Each entry is a code unit
2199 // where there is a boundary between code units that are part of
2200 // the class and code units that are not. Normally we insert an
2201 // entry at zero which goes to the failure label, but if there
2202 // was already one there we fall through for success on that entry.
2203 // Subsequent entries have alternating meaning (success/failure).
2204 ZoneList<int>* range_boundaries =
2205 new(zone) ZoneList<int>(last_valid_range, zone);
2207 bool zeroth_entry_is_failure = !cc->is_negated();
2209 for (int i = 0; i <= last_valid_range; i++) {
2210 CharacterRange& range = ranges->at(i);
2211 if (range.from() == 0) {
2213 zeroth_entry_is_failure = !zeroth_entry_is_failure;
2215 range_boundaries->Add(range.from(), zone);
2217 range_boundaries->Add(range.to() + 1, zone);
2219 int end_index = range_boundaries->length() - 1;
2220 if (range_boundaries->at(end_index) > max_char) {
2225 GenerateBranches(macro_assembler,
2232 zeroth_entry_is_failure ? &fall_through : on_failure,
2233 zeroth_entry_is_failure ? on_failure : &fall_through);
2234 macro_assembler->Bind(&fall_through);
2238 RegExpNode::~RegExpNode() {
2242 RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler,
2244 // If we are generating a greedy loop then don't stop and don't reuse code.
2245 if (trace->stop_node() != NULL) {
2249 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2250 if (trace->is_trivial()) {
2251 if (label_.is_bound()) {
2252 // We are being asked to generate a generic version, but that's already
2253 // been done so just go to it.
2254 macro_assembler->GoTo(&label_);
2257 if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) {
2258 // To avoid too deep recursion we push the node to the work queue and just
2259 // generate a goto here.
2260 compiler->AddWork(this);
2261 macro_assembler->GoTo(&label_);
2264 // Generate generic version of the node and bind the label for later use.
2265 macro_assembler->Bind(&label_);
2269 // We are being asked to make a non-generic version. Keep track of how many
2270 // non-generic versions we generate so as not to overdo it.
2272 if (FLAG_regexp_optimization &&
2273 trace_count_ < kMaxCopiesCodeGenerated &&
2274 compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) {
2278 // If we get here code has been generated for this node too many times or
2279 // recursion is too deep. Time to switch to a generic version. The code for
2280 // generic versions above can handle deep recursion properly.
2281 trace->Flush(compiler, this);
2286 int ActionNode::EatsAtLeast(int still_to_find,
2288 bool not_at_start) {
2289 if (budget <= 0) return 0;
2290 if (action_type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input!
2291 return on_success()->EatsAtLeast(still_to_find,
2297 void ActionNode::FillInBMInfo(int offset,
2299 BoyerMooreLookahead* bm,
2300 bool not_at_start) {
2301 if (action_type_ == BEGIN_SUBMATCH) {
2302 bm->SetRest(offset);
2303 } else if (action_type_ != POSITIVE_SUBMATCH_SUCCESS) {
2304 on_success()->FillInBMInfo(offset, budget - 1, bm, not_at_start);
2306 SaveBMInfo(bm, not_at_start, offset);
2310 int AssertionNode::EatsAtLeast(int still_to_find,
2312 bool not_at_start) {
2313 if (budget <= 0) return 0;
2314 // If we know we are not at the start and we are asked "how many characters
2315 // will you match if you succeed?" then we can answer anything since false
2316 // implies false. So lets just return the max answer (still_to_find) since
2317 // that won't prevent us from preloading a lot of characters for the other
2318 // branches in the node graph.
2319 if (assertion_type() == AT_START && not_at_start) return still_to_find;
2320 return on_success()->EatsAtLeast(still_to_find,
2326 void AssertionNode::FillInBMInfo(int offset,
2328 BoyerMooreLookahead* bm,
2329 bool not_at_start) {
2330 // Match the behaviour of EatsAtLeast on this node.
2331 if (assertion_type() == AT_START && not_at_start) return;
2332 on_success()->FillInBMInfo(offset, budget - 1, bm, not_at_start);
2333 SaveBMInfo(bm, not_at_start, offset);
2337 int BackReferenceNode::EatsAtLeast(int still_to_find,
2339 bool not_at_start) {
2340 if (budget <= 0) return 0;
2341 return on_success()->EatsAtLeast(still_to_find,
2347 int TextNode::EatsAtLeast(int still_to_find,
2349 bool not_at_start) {
2350 int answer = Length();
2351 if (answer >= still_to_find) return answer;
2352 if (budget <= 0) return answer;
2353 // We are not at start after this node so we set the last argument to 'true'.
2354 return answer + on_success()->EatsAtLeast(still_to_find - answer,
2360 int NegativeLookaheadChoiceNode::EatsAtLeast(int still_to_find,
2362 bool not_at_start) {
2363 if (budget <= 0) return 0;
2364 // Alternative 0 is the negative lookahead, alternative 1 is what comes
2366 RegExpNode* node = alternatives_->at(1).node();
2367 return node->EatsAtLeast(still_to_find, budget - 1, not_at_start);
2371 void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
2372 QuickCheckDetails* details,
2373 RegExpCompiler* compiler,
2375 bool not_at_start) {
2376 // Alternative 0 is the negative lookahead, alternative 1 is what comes
2378 RegExpNode* node = alternatives_->at(1).node();
2379 return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
2383 int ChoiceNode::EatsAtLeastHelper(int still_to_find,
2385 RegExpNode* ignore_this_node,
2386 bool not_at_start) {
2387 if (budget <= 0) return 0;
2389 int choice_count = alternatives_->length();
2390 budget = (budget - 1) / choice_count;
2391 for (int i = 0; i < choice_count; i++) {
2392 RegExpNode* node = alternatives_->at(i).node();
2393 if (node == ignore_this_node) continue;
2394 int node_eats_at_least =
2395 node->EatsAtLeast(still_to_find, budget, not_at_start);
2396 if (node_eats_at_least < min) min = node_eats_at_least;
2397 if (min == 0) return 0;
2403 int LoopChoiceNode::EatsAtLeast(int still_to_find,
2405 bool not_at_start) {
2406 return EatsAtLeastHelper(still_to_find,
2413 int ChoiceNode::EatsAtLeast(int still_to_find,
2415 bool not_at_start) {
2416 return EatsAtLeastHelper(still_to_find,
2423 // Takes the left-most 1-bit and smears it out, setting all bits to its right.
2424 static inline uint32_t SmearBitsRight(uint32_t v) {
2434 bool QuickCheckDetails::Rationalize(bool asc) {
2435 bool found_useful_op = false;
2438 char_mask = String::kMaxOneByteCharCode;
2440 char_mask = String::kMaxUtf16CodeUnit;
2445 for (int i = 0; i < characters_; i++) {
2446 Position* pos = &positions_[i];
2447 if ((pos->mask & String::kMaxOneByteCharCode) != 0) {
2448 found_useful_op = true;
2450 mask_ |= (pos->mask & char_mask) << char_shift;
2451 value_ |= (pos->value & char_mask) << char_shift;
2452 char_shift += asc ? 8 : 16;
2454 return found_useful_op;
2458 bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
2460 bool preload_has_checked_bounds,
2461 Label* on_possible_success,
2462 QuickCheckDetails* details,
2463 bool fall_through_on_failure) {
2464 if (details->characters() == 0) return false;
2465 GetQuickCheckDetails(
2466 details, compiler, 0, trace->at_start() == Trace::FALSE_VALUE);
2467 if (details->cannot_match()) return false;
2468 if (!details->Rationalize(compiler->ascii())) return false;
2469 DCHECK(details->characters() == 1 ||
2470 compiler->macro_assembler()->CanReadUnaligned());
2471 uint32_t mask = details->mask();
2472 uint32_t value = details->value();
2474 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2476 if (trace->characters_preloaded() != details->characters()) {
2477 assembler->LoadCurrentCharacter(trace->cp_offset(),
2479 !preload_has_checked_bounds,
2480 details->characters());
2484 bool need_mask = true;
2486 if (details->characters() == 1) {
2487 // If number of characters preloaded is 1 then we used a byte or 16 bit
2488 // load so the value is already masked down.
2490 if (compiler->ascii()) {
2491 char_mask = String::kMaxOneByteCharCode;
2493 char_mask = String::kMaxUtf16CodeUnit;
2495 if ((mask & char_mask) == char_mask) need_mask = false;
2498 // For 2-character preloads in ASCII mode or 1-character preloads in
2499 // TWO_BYTE mode we also use a 16 bit load with zero extend.
2500 if (details->characters() == 2 && compiler->ascii()) {
2501 if ((mask & 0xffff) == 0xffff) need_mask = false;
2502 } else if (details->characters() == 1 && !compiler->ascii()) {
2503 if ((mask & 0xffff) == 0xffff) need_mask = false;
2505 if (mask == 0xffffffff) need_mask = false;
2509 if (fall_through_on_failure) {
2511 assembler->CheckCharacterAfterAnd(value, mask, on_possible_success);
2513 assembler->CheckCharacter(value, on_possible_success);
2517 assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack());
2519 assembler->CheckNotCharacter(value, trace->backtrack());
2526 // Here is the meat of GetQuickCheckDetails (see also the comment on the
2527 // super-class in the .h file).
2529 // We iterate along the text object, building up for each character a
2530 // mask and value that can be used to test for a quick failure to match.
2531 // The masks and values for the positions will be combined into a single
2532 // machine word for the current character width in order to be used in
2533 // generating a quick check.
2534 void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
2535 RegExpCompiler* compiler,
2536 int characters_filled_in,
2537 bool not_at_start) {
2538 Isolate* isolate = compiler->macro_assembler()->zone()->isolate();
2539 DCHECK(characters_filled_in < details->characters());
2540 int characters = details->characters();
2542 if (compiler->ascii()) {
2543 char_mask = String::kMaxOneByteCharCode;
2545 char_mask = String::kMaxUtf16CodeUnit;
2547 for (int k = 0; k < elms_->length(); k++) {
2548 TextElement elm = elms_->at(k);
2549 if (elm.text_type() == TextElement::ATOM) {
2550 Vector<const uc16> quarks = elm.atom()->data();
2551 for (int i = 0; i < characters && i < quarks.length(); i++) {
2552 QuickCheckDetails::Position* pos =
2553 details->positions(characters_filled_in);
2555 if (c > char_mask) {
2556 // If we expect a non-ASCII character from an ASCII string,
2557 // there is no way we can match. Not even case independent
2558 // matching can turn an ASCII character into non-ASCII or
2560 details->set_cannot_match();
2561 pos->determines_perfectly = false;
2564 if (compiler->ignore_case()) {
2565 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
2566 int length = GetCaseIndependentLetters(isolate, c, compiler->ascii(),
2568 DCHECK(length != 0); // Can only happen if c > char_mask (see above).
2570 // This letter has no case equivalents, so it's nice and simple
2571 // and the mask-compare will determine definitely whether we have
2572 // a match at this character position.
2573 pos->mask = char_mask;
2575 pos->determines_perfectly = true;
2577 uint32_t common_bits = char_mask;
2578 uint32_t bits = chars[0];
2579 for (int j = 1; j < length; j++) {
2580 uint32_t differing_bits = ((chars[j] & common_bits) ^ bits);
2581 common_bits ^= differing_bits;
2582 bits &= common_bits;
2584 // If length is 2 and common bits has only one zero in it then
2585 // our mask and compare instruction will determine definitely
2586 // whether we have a match at this character position. Otherwise
2587 // it can only be an approximate check.
2588 uint32_t one_zero = (common_bits | ~char_mask);
2589 if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) {
2590 pos->determines_perfectly = true;
2592 pos->mask = common_bits;
2596 // Don't ignore case. Nice simple case where the mask-compare will
2597 // determine definitely whether we have a match at this character
2599 pos->mask = char_mask;
2601 pos->determines_perfectly = true;
2603 characters_filled_in++;
2604 DCHECK(characters_filled_in <= details->characters());
2605 if (characters_filled_in == details->characters()) {
2610 QuickCheckDetails::Position* pos =
2611 details->positions(characters_filled_in);
2612 RegExpCharacterClass* tree = elm.char_class();
2613 ZoneList<CharacterRange>* ranges = tree->ranges(zone());
2614 if (tree->is_negated()) {
2615 // A quick check uses multi-character mask and compare. There is no
2616 // useful way to incorporate a negative char class into this scheme
2617 // so we just conservatively create a mask and value that will always
2622 int first_range = 0;
2623 while (ranges->at(first_range).from() > char_mask) {
2625 if (first_range == ranges->length()) {
2626 details->set_cannot_match();
2627 pos->determines_perfectly = false;
2631 CharacterRange range = ranges->at(first_range);
2632 uc16 from = range.from();
2633 uc16 to = range.to();
2634 if (to > char_mask) {
2637 uint32_t differing_bits = (from ^ to);
2638 // A mask and compare is only perfect if the differing bits form a
2639 // number like 00011111 with one single block of trailing 1s.
2640 if ((differing_bits & (differing_bits + 1)) == 0 &&
2641 from + differing_bits == to) {
2642 pos->determines_perfectly = true;
2644 uint32_t common_bits = ~SmearBitsRight(differing_bits);
2645 uint32_t bits = (from & common_bits);
2646 for (int i = first_range + 1; i < ranges->length(); i++) {
2647 CharacterRange range = ranges->at(i);
2648 uc16 from = range.from();
2649 uc16 to = range.to();
2650 if (from > char_mask) continue;
2651 if (to > char_mask) to = char_mask;
2652 // Here we are combining more ranges into the mask and compare
2653 // value. With each new range the mask becomes more sparse and
2654 // so the chances of a false positive rise. A character class
2655 // with multiple ranges is assumed never to be equivalent to a
2656 // mask and compare operation.
2657 pos->determines_perfectly = false;
2658 uint32_t new_common_bits = (from ^ to);
2659 new_common_bits = ~SmearBitsRight(new_common_bits);
2660 common_bits &= new_common_bits;
2661 bits &= new_common_bits;
2662 uint32_t differing_bits = (from & common_bits) ^ bits;
2663 common_bits ^= differing_bits;
2664 bits &= common_bits;
2666 pos->mask = common_bits;
2669 characters_filled_in++;
2670 DCHECK(characters_filled_in <= details->characters());
2671 if (characters_filled_in == details->characters()) {
2676 DCHECK(characters_filled_in != details->characters());
2677 if (!details->cannot_match()) {
2678 on_success()-> GetQuickCheckDetails(details,
2680 characters_filled_in,
2686 void QuickCheckDetails::Clear() {
2687 for (int i = 0; i < characters_; i++) {
2688 positions_[i].mask = 0;
2689 positions_[i].value = 0;
2690 positions_[i].determines_perfectly = false;
2696 void QuickCheckDetails::Advance(int by, bool ascii) {
2698 if (by >= characters_) {
2702 for (int i = 0; i < characters_ - by; i++) {
2703 positions_[i] = positions_[by + i];
2705 for (int i = characters_ - by; i < characters_; i++) {
2706 positions_[i].mask = 0;
2707 positions_[i].value = 0;
2708 positions_[i].determines_perfectly = false;
2711 // We could change mask_ and value_ here but we would never advance unless
2712 // they had already been used in a check and they won't be used again because
2713 // it would gain us nothing. So there's no point.
2717 void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) {
2718 DCHECK(characters_ == other->characters_);
2719 if (other->cannot_match_) {
2722 if (cannot_match_) {
2726 for (int i = from_index; i < characters_; i++) {
2727 QuickCheckDetails::Position* pos = positions(i);
2728 QuickCheckDetails::Position* other_pos = other->positions(i);
2729 if (pos->mask != other_pos->mask ||
2730 pos->value != other_pos->value ||
2731 !other_pos->determines_perfectly) {
2732 // Our mask-compare operation will be approximate unless we have the
2733 // exact same operation on both sides of the alternation.
2734 pos->determines_perfectly = false;
2736 pos->mask &= other_pos->mask;
2737 pos->value &= pos->mask;
2738 other_pos->value &= pos->mask;
2739 uc16 differing_bits = (pos->value ^ other_pos->value);
2740 pos->mask &= ~differing_bits;
2741 pos->value &= pos->mask;
2748 explicit VisitMarker(NodeInfo* info) : info_(info) {
2749 DCHECK(!info->visited);
2750 info->visited = true;
2753 info_->visited = false;
2760 RegExpNode* SeqRegExpNode::FilterASCII(int depth, bool ignore_case) {
2761 if (info()->replacement_calculated) return replacement();
2762 if (depth < 0) return this;
2763 DCHECK(!info()->visited);
2764 VisitMarker marker(info());
2765 return FilterSuccessor(depth - 1, ignore_case);
2769 RegExpNode* SeqRegExpNode::FilterSuccessor(int depth, bool ignore_case) {
2770 RegExpNode* next = on_success_->FilterASCII(depth - 1, ignore_case);
2771 if (next == NULL) return set_replacement(NULL);
2773 return set_replacement(this);
2777 // We need to check for the following characters: 0x39c 0x3bc 0x178.
2778 static inline bool RangeContainsLatin1Equivalents(CharacterRange range) {
2779 // TODO(dcarney): this could be a lot more efficient.
2780 return range.Contains(0x39c) ||
2781 range.Contains(0x3bc) || range.Contains(0x178);
2785 static bool RangesContainLatin1Equivalents(ZoneList<CharacterRange>* ranges) {
2786 for (int i = 0; i < ranges->length(); i++) {
2787 // TODO(dcarney): this could be a lot more efficient.
2788 if (RangeContainsLatin1Equivalents(ranges->at(i))) return true;
2794 RegExpNode* TextNode::FilterASCII(int depth, bool ignore_case) {
2795 if (info()->replacement_calculated) return replacement();
2796 if (depth < 0) return this;
2797 DCHECK(!info()->visited);
2798 VisitMarker marker(info());
2799 int element_count = elms_->length();
2800 for (int i = 0; i < element_count; i++) {
2801 TextElement elm = elms_->at(i);
2802 if (elm.text_type() == TextElement::ATOM) {
2803 Vector<const uc16> quarks = elm.atom()->data();
2804 for (int j = 0; j < quarks.length(); j++) {
2805 uint16_t c = quarks[j];
2806 if (c <= String::kMaxOneByteCharCode) continue;
2807 if (!ignore_case) return set_replacement(NULL);
2808 // Here, we need to check for characters whose upper and lower cases
2809 // are outside the Latin-1 range.
2810 uint16_t converted = unibrow::Latin1::ConvertNonLatin1ToLatin1(c);
2811 // Character is outside Latin-1 completely
2812 if (converted == 0) return set_replacement(NULL);
2813 // Convert quark to Latin-1 in place.
2814 uint16_t* copy = const_cast<uint16_t*>(quarks.start());
2815 copy[j] = converted;
2818 DCHECK(elm.text_type() == TextElement::CHAR_CLASS);
2819 RegExpCharacterClass* cc = elm.char_class();
2820 ZoneList<CharacterRange>* ranges = cc->ranges(zone());
2821 if (!CharacterRange::IsCanonical(ranges)) {
2822 CharacterRange::Canonicalize(ranges);
2824 // Now they are in order so we only need to look at the first.
2825 int range_count = ranges->length();
2826 if (cc->is_negated()) {
2827 if (range_count != 0 &&
2828 ranges->at(0).from() == 0 &&
2829 ranges->at(0).to() >= String::kMaxOneByteCharCode) {
2830 // This will be handled in a later filter.
2831 if (ignore_case && RangesContainLatin1Equivalents(ranges)) continue;
2832 return set_replacement(NULL);
2835 if (range_count == 0 ||
2836 ranges->at(0).from() > String::kMaxOneByteCharCode) {
2837 // This will be handled in a later filter.
2838 if (ignore_case && RangesContainLatin1Equivalents(ranges)) continue;
2839 return set_replacement(NULL);
2844 return FilterSuccessor(depth - 1, ignore_case);
2848 RegExpNode* LoopChoiceNode::FilterASCII(int depth, bool ignore_case) {
2849 if (info()->replacement_calculated) return replacement();
2850 if (depth < 0) return this;
2851 if (info()->visited) return this;
2853 VisitMarker marker(info());
2855 RegExpNode* continue_replacement =
2856 continue_node_->FilterASCII(depth - 1, ignore_case);
2857 // If we can't continue after the loop then there is no sense in doing the
2859 if (continue_replacement == NULL) return set_replacement(NULL);
2862 return ChoiceNode::FilterASCII(depth - 1, ignore_case);
2866 RegExpNode* ChoiceNode::FilterASCII(int depth, bool ignore_case) {
2867 if (info()->replacement_calculated) return replacement();
2868 if (depth < 0) return this;
2869 if (info()->visited) return this;
2870 VisitMarker marker(info());
2871 int choice_count = alternatives_->length();
2873 for (int i = 0; i < choice_count; i++) {
2874 GuardedAlternative alternative = alternatives_->at(i);
2875 if (alternative.guards() != NULL && alternative.guards()->length() != 0) {
2876 set_replacement(this);
2882 RegExpNode* survivor = NULL;
2883 for (int i = 0; i < choice_count; i++) {
2884 GuardedAlternative alternative = alternatives_->at(i);
2885 RegExpNode* replacement =
2886 alternative.node()->FilterASCII(depth - 1, ignore_case);
2887 DCHECK(replacement != this); // No missing EMPTY_MATCH_CHECK.
2888 if (replacement != NULL) {
2889 alternatives_->at(i).set_node(replacement);
2891 survivor = replacement;
2894 if (surviving < 2) return set_replacement(survivor);
2896 set_replacement(this);
2897 if (surviving == choice_count) {
2900 // Only some of the nodes survived the filtering. We need to rebuild the
2901 // alternatives list.
2902 ZoneList<GuardedAlternative>* new_alternatives =
2903 new(zone()) ZoneList<GuardedAlternative>(surviving, zone());
2904 for (int i = 0; i < choice_count; i++) {
2905 RegExpNode* replacement =
2906 alternatives_->at(i).node()->FilterASCII(depth - 1, ignore_case);
2907 if (replacement != NULL) {
2908 alternatives_->at(i).set_node(replacement);
2909 new_alternatives->Add(alternatives_->at(i), zone());
2912 alternatives_ = new_alternatives;
2917 RegExpNode* NegativeLookaheadChoiceNode::FilterASCII(int depth,
2919 if (info()->replacement_calculated) return replacement();
2920 if (depth < 0) return this;
2921 if (info()->visited) return this;
2922 VisitMarker marker(info());
2923 // Alternative 0 is the negative lookahead, alternative 1 is what comes
2925 RegExpNode* node = alternatives_->at(1).node();
2926 RegExpNode* replacement = node->FilterASCII(depth - 1, ignore_case);
2927 if (replacement == NULL) return set_replacement(NULL);
2928 alternatives_->at(1).set_node(replacement);
2930 RegExpNode* neg_node = alternatives_->at(0).node();
2931 RegExpNode* neg_replacement = neg_node->FilterASCII(depth - 1, ignore_case);
2932 // If the negative lookahead is always going to fail then
2933 // we don't need to check it.
2934 if (neg_replacement == NULL) return set_replacement(replacement);
2935 alternatives_->at(0).set_node(neg_replacement);
2936 return set_replacement(this);
2940 void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2941 RegExpCompiler* compiler,
2942 int characters_filled_in,
2943 bool not_at_start) {
2944 if (body_can_be_zero_length_ || info()->visited) return;
2945 VisitMarker marker(info());
2946 return ChoiceNode::GetQuickCheckDetails(details,
2948 characters_filled_in,
2953 void LoopChoiceNode::FillInBMInfo(int offset,
2955 BoyerMooreLookahead* bm,
2956 bool not_at_start) {
2957 if (body_can_be_zero_length_ || budget <= 0) {
2958 bm->SetRest(offset);
2959 SaveBMInfo(bm, not_at_start, offset);
2962 ChoiceNode::FillInBMInfo(offset, budget - 1, bm, not_at_start);
2963 SaveBMInfo(bm, not_at_start, offset);
2967 void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2968 RegExpCompiler* compiler,
2969 int characters_filled_in,
2970 bool not_at_start) {
2971 not_at_start = (not_at_start || not_at_start_);
2972 int choice_count = alternatives_->length();
2973 DCHECK(choice_count > 0);
2974 alternatives_->at(0).node()->GetQuickCheckDetails(details,
2976 characters_filled_in,
2978 for (int i = 1; i < choice_count; i++) {
2979 QuickCheckDetails new_details(details->characters());
2980 RegExpNode* node = alternatives_->at(i).node();
2981 node->GetQuickCheckDetails(&new_details, compiler,
2982 characters_filled_in,
2984 // Here we merge the quick match details of the two branches.
2985 details->Merge(&new_details, characters_filled_in);
2990 // Check for [0-9A-Z_a-z].
2991 static void EmitWordCheck(RegExpMacroAssembler* assembler,
2994 bool fall_through_on_word) {
2995 if (assembler->CheckSpecialCharacterClass(
2996 fall_through_on_word ? 'w' : 'W',
2997 fall_through_on_word ? non_word : word)) {
2998 // Optimized implementation available.
3001 assembler->CheckCharacterGT('z', non_word);
3002 assembler->CheckCharacterLT('0', non_word);
3003 assembler->CheckCharacterGT('a' - 1, word);
3004 assembler->CheckCharacterLT('9' + 1, word);
3005 assembler->CheckCharacterLT('A', non_word);
3006 assembler->CheckCharacterLT('Z' + 1, word);
3007 if (fall_through_on_word) {
3008 assembler->CheckNotCharacter('_', non_word);
3010 assembler->CheckCharacter('_', word);
3015 // Emit the code to check for a ^ in multiline mode (1-character lookbehind
3016 // that matches newline or the start of input).
3017 static void EmitHat(RegExpCompiler* compiler,
3018 RegExpNode* on_success,
3020 RegExpMacroAssembler* assembler = compiler->macro_assembler();
3021 // We will be loading the previous character into the current character
3023 Trace new_trace(*trace);
3024 new_trace.InvalidateCurrentCharacter();
3027 if (new_trace.cp_offset() == 0) {
3028 // The start of input counts as a newline in this context, so skip to
3029 // ok if we are at the start.
3030 assembler->CheckAtStart(&ok);
3032 // We already checked that we are not at the start of input so it must be
3033 // OK to load the previous character.
3034 assembler->LoadCurrentCharacter(new_trace.cp_offset() -1,
3035 new_trace.backtrack(),
3037 if (!assembler->CheckSpecialCharacterClass('n',
3038 new_trace.backtrack())) {
3039 // Newline means \n, \r, 0x2028 or 0x2029.
3040 if (!compiler->ascii()) {
3041 assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok);
3043 assembler->CheckCharacter('\n', &ok);
3044 assembler->CheckNotCharacter('\r', new_trace.backtrack());
3046 assembler->Bind(&ok);
3047 on_success->Emit(compiler, &new_trace);
3051 // Emit the code to handle \b and \B (word-boundary or non-word-boundary).
3052 void AssertionNode::EmitBoundaryCheck(RegExpCompiler* compiler, Trace* trace) {
3053 RegExpMacroAssembler* assembler = compiler->macro_assembler();
3054 Trace::TriBool next_is_word_character = Trace::UNKNOWN;
3055 bool not_at_start = (trace->at_start() == Trace::FALSE_VALUE);
3056 BoyerMooreLookahead* lookahead = bm_info(not_at_start);
3057 if (lookahead == NULL) {
3059 Min(kMaxLookaheadForBoyerMoore, EatsAtLeast(kMaxLookaheadForBoyerMoore,
3062 if (eats_at_least >= 1) {
3063 BoyerMooreLookahead* bm =
3064 new(zone()) BoyerMooreLookahead(eats_at_least, compiler, zone());
3065 FillInBMInfo(0, kRecursionBudget, bm, not_at_start);
3066 if (bm->at(0)->is_non_word())
3067 next_is_word_character = Trace::FALSE_VALUE;
3068 if (bm->at(0)->is_word()) next_is_word_character = Trace::TRUE_VALUE;
3071 if (lookahead->at(0)->is_non_word())
3072 next_is_word_character = Trace::FALSE_VALUE;
3073 if (lookahead->at(0)->is_word())
3074 next_is_word_character = Trace::TRUE_VALUE;
3076 bool at_boundary = (assertion_type_ == AssertionNode::AT_BOUNDARY);
3077 if (next_is_word_character == Trace::UNKNOWN) {
3078 Label before_non_word;
3080 if (trace->characters_preloaded() != 1) {
3081 assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word);
3083 // Fall through on non-word.
3084 EmitWordCheck(assembler, &before_word, &before_non_word, false);
3085 // Next character is not a word character.
3086 assembler->Bind(&before_non_word);
3088 BacktrackIfPrevious(compiler, trace, at_boundary ? kIsNonWord : kIsWord);
3089 assembler->GoTo(&ok);
3091 assembler->Bind(&before_word);
3092 BacktrackIfPrevious(compiler, trace, at_boundary ? kIsWord : kIsNonWord);
3093 assembler->Bind(&ok);
3094 } else if (next_is_word_character == Trace::TRUE_VALUE) {
3095 BacktrackIfPrevious(compiler, trace, at_boundary ? kIsWord : kIsNonWord);
3097 DCHECK(next_is_word_character == Trace::FALSE_VALUE);
3098 BacktrackIfPrevious(compiler, trace, at_boundary ? kIsNonWord : kIsWord);
3103 void AssertionNode::BacktrackIfPrevious(
3104 RegExpCompiler* compiler,
3106 AssertionNode::IfPrevious backtrack_if_previous) {
3107 RegExpMacroAssembler* assembler = compiler->macro_assembler();
3108 Trace new_trace(*trace);
3109 new_trace.InvalidateCurrentCharacter();
3111 Label fall_through, dummy;
3113 Label* non_word = backtrack_if_previous == kIsNonWord ?
3114 new_trace.backtrack() :
3116 Label* word = backtrack_if_previous == kIsNonWord ?
3118 new_trace.backtrack();
3120 if (new_trace.cp_offset() == 0) {
3121 // The start of input counts as a non-word character, so the question is
3122 // decided if we are at the start.
3123 assembler->CheckAtStart(non_word);
3125 // We already checked that we are not at the start of input so it must be
3126 // OK to load the previous character.
3127 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1, &dummy, false);
3128 EmitWordCheck(assembler, word, non_word, backtrack_if_previous == kIsNonWord);
3130 assembler->Bind(&fall_through);
3131 on_success()->Emit(compiler, &new_trace);
3135 void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details,
3136 RegExpCompiler* compiler,
3138 bool not_at_start) {
3139 if (assertion_type_ == AT_START && not_at_start) {
3140 details->set_cannot_match();
3143 return on_success()->GetQuickCheckDetails(details,
3150 void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3151 RegExpMacroAssembler* assembler = compiler->macro_assembler();
3152 switch (assertion_type_) {
3155 assembler->CheckPosition(trace->cp_offset(), &ok);
3156 assembler->GoTo(trace->backtrack());
3157 assembler->Bind(&ok);
3161 if (trace->at_start() == Trace::FALSE_VALUE) {
3162 assembler->GoTo(trace->backtrack());
3165 if (trace->at_start() == Trace::UNKNOWN) {
3166 assembler->CheckNotAtStart(trace->backtrack());
3167 Trace at_start_trace = *trace;
3168 at_start_trace.set_at_start(true);
3169 on_success()->Emit(compiler, &at_start_trace);
3175 EmitHat(compiler, on_success(), trace);
3178 case AT_NON_BOUNDARY: {
3179 EmitBoundaryCheck(compiler, trace);
3183 on_success()->Emit(compiler, trace);
3187 static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) {
3188 if (quick_check == NULL) return false;
3189 if (offset >= quick_check->characters()) return false;
3190 return quick_check->positions(offset)->determines_perfectly;
3194 static void UpdateBoundsCheck(int index, int* checked_up_to) {
3195 if (index > *checked_up_to) {
3196 *checked_up_to = index;
3201 // We call this repeatedly to generate code for each pass over the text node.
3202 // The passes are in increasing order of difficulty because we hope one
3203 // of the first passes will fail in which case we are saved the work of the
3204 // later passes. for example for the case independent regexp /%[asdfghjkl]a/
3205 // we will check the '%' in the first pass, the case independent 'a' in the
3206 // second pass and the character class in the last pass.
3208 // The passes are done from right to left, so for example to test for /bar/
3209 // we will first test for an 'r' with offset 2, then an 'a' with offset 1
3210 // and then a 'b' with offset 0. This means we can avoid the end-of-input
3211 // bounds check most of the time. In the example we only need to check for
3212 // end-of-input when loading the putative 'r'.
3214 // A slight complication involves the fact that the first character may already
3215 // be fetched into a register by the previous node. In this case we want to
3216 // do the test for that character first. We do this in separate passes. The
3217 // 'preloaded' argument indicates that we are doing such a 'pass'. If such a
3218 // pass has been performed then subsequent passes will have true in
3219 // first_element_checked to indicate that that character does not need to be
3222 // In addition to all this we are passed a Trace, which can
3223 // contain an AlternativeGeneration object. In this AlternativeGeneration
3224 // object we can see details of any quick check that was already passed in
3225 // order to get to the code we are now generating. The quick check can involve
3226 // loading characters, which means we do not need to recheck the bounds
3227 // up to the limit the quick check already checked. In addition the quick
3228 // check can have involved a mask and compare operation which may simplify
3229 // or obviate the need for further checks at some character positions.
3230 void TextNode::TextEmitPass(RegExpCompiler* compiler,
3231 TextEmitPassType pass,
3234 bool first_element_checked,
3235 int* checked_up_to) {
3236 RegExpMacroAssembler* assembler = compiler->macro_assembler();
3237 Isolate* isolate = assembler->zone()->isolate();
3238 bool ascii = compiler->ascii();
3239 Label* backtrack = trace->backtrack();
3240 QuickCheckDetails* quick_check = trace->quick_check_performed();
3241 int element_count = elms_->length();
3242 for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) {
3243 TextElement elm = elms_->at(i);
3244 int cp_offset = trace->cp_offset() + elm.cp_offset();
3245 if (elm.text_type() == TextElement::ATOM) {
3246 Vector<const uc16> quarks = elm.atom()->data();
3247 for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) {
3248 if (first_element_checked && i == 0 && j == 0) continue;
3249 if (DeterminedAlready(quick_check, elm.cp_offset() + j)) continue;
3250 EmitCharacterFunction* emit_function = NULL;
3252 case NON_ASCII_MATCH:
3254 if (quarks[j] > String::kMaxOneByteCharCode) {
3255 assembler->GoTo(backtrack);
3259 case NON_LETTER_CHARACTER_MATCH:
3260 emit_function = &EmitAtomNonLetter;
3262 case SIMPLE_CHARACTER_MATCH:
3263 emit_function = &EmitSimpleCharacter;
3265 case CASE_CHARACTER_MATCH:
3266 emit_function = &EmitAtomLetter;
3271 if (emit_function != NULL) {
3272 bool bound_checked = emit_function(isolate,
3277 *checked_up_to < cp_offset + j,
3279 if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
3283 DCHECK_EQ(TextElement::CHAR_CLASS, elm.text_type());
3284 if (pass == CHARACTER_CLASS_MATCH) {
3285 if (first_element_checked && i == 0) continue;
3286 if (DeterminedAlready(quick_check, elm.cp_offset())) continue;
3287 RegExpCharacterClass* cc = elm.char_class();
3288 EmitCharClass(assembler,
3293 *checked_up_to < cp_offset,
3296 UpdateBoundsCheck(cp_offset, checked_up_to);
3303 int TextNode::Length() {
3304 TextElement elm = elms_->last();
3305 DCHECK(elm.cp_offset() >= 0);
3306 return elm.cp_offset() + elm.length();
3310 bool TextNode::SkipPass(int int_pass, bool ignore_case) {
3311 TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass);
3313 return pass == SIMPLE_CHARACTER_MATCH;
3315 return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH;
3320 // This generates the code to match a text node. A text node can contain
3321 // straight character sequences (possibly to be matched in a case-independent
3322 // way) and character classes. For efficiency we do not do this in a single
3323 // pass from left to right. Instead we pass over the text node several times,
3324 // emitting code for some character positions every time. See the comment on
3325 // TextEmitPass for details.
3326 void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3327 LimitResult limit_result = LimitVersions(compiler, trace);
3328 if (limit_result == DONE) return;
3329 DCHECK(limit_result == CONTINUE);
3331 if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
3332 compiler->SetRegExpTooBig();
3336 if (compiler->ascii()) {
3338 TextEmitPass(compiler, NON_ASCII_MATCH, false, trace, false, &dummy);
3341 bool first_elt_done = false;
3342 int bound_checked_to = trace->cp_offset() - 1;
3343 bound_checked_to += trace->bound_checked_up_to();
3345 // If a character is preloaded into the current character register then
3347 if (trace->characters_preloaded() == 1) {
3348 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
3349 if (!SkipPass(pass, compiler->ignore_case())) {
3350 TextEmitPass(compiler,
3351 static_cast<TextEmitPassType>(pass),
3358 first_elt_done = true;
3361 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
3362 if (!SkipPass(pass, compiler->ignore_case())) {
3363 TextEmitPass(compiler,
3364 static_cast<TextEmitPassType>(pass),
3372 Trace successor_trace(*trace);
3373 successor_trace.set_at_start(false);
3374 successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler);
3375 RecursionCheck rc(compiler);
3376 on_success()->Emit(compiler, &successor_trace);
3380 void Trace::InvalidateCurrentCharacter() {
3381 characters_preloaded_ = 0;
3385 void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) {
3387 // We don't have an instruction for shifting the current character register
3388 // down or for using a shifted value for anything so lets just forget that
3389 // we preloaded any characters into it.
3390 characters_preloaded_ = 0;
3391 // Adjust the offsets of the quick check performed information. This
3392 // information is used to find out what we already determined about the
3393 // characters by means of mask and compare.
3394 quick_check_performed_.Advance(by, compiler->ascii());
3396 if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
3397 compiler->SetRegExpTooBig();
3400 bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
3404 void TextNode::MakeCaseIndependent(bool is_ascii) {
3405 int element_count = elms_->length();
3406 for (int i = 0; i < element_count; i++) {
3407 TextElement elm = elms_->at(i);
3408 if (elm.text_type() == TextElement::CHAR_CLASS) {
3409 RegExpCharacterClass* cc = elm.char_class();
3410 // None of the standard character classes is different in the case
3411 // independent case and it slows us down if we don't know that.
3412 if (cc->is_standard(zone())) continue;
3413 ZoneList<CharacterRange>* ranges = cc->ranges(zone());
3414 int range_count = ranges->length();
3415 for (int j = 0; j < range_count; j++) {
3416 ranges->at(j).AddCaseEquivalents(ranges, is_ascii, zone());
3423 int TextNode::GreedyLoopTextLength() {
3424 TextElement elm = elms_->at(elms_->length() - 1);
3425 return elm.cp_offset() + elm.length();
3429 RegExpNode* TextNode::GetSuccessorOfOmnivorousTextNode(
3430 RegExpCompiler* compiler) {
3431 if (elms_->length() != 1) return NULL;
3432 TextElement elm = elms_->at(0);
3433 if (elm.text_type() != TextElement::CHAR_CLASS) return NULL;
3434 RegExpCharacterClass* node = elm.char_class();
3435 ZoneList<CharacterRange>* ranges = node->ranges(zone());
3436 if (!CharacterRange::IsCanonical(ranges)) {
3437 CharacterRange::Canonicalize(ranges);
3439 if (node->is_negated()) {
3440 return ranges->length() == 0 ? on_success() : NULL;
3442 if (ranges->length() != 1) return NULL;
3444 if (compiler->ascii()) {
3445 max_char = String::kMaxOneByteCharCode;
3447 max_char = String::kMaxUtf16CodeUnit;
3449 return ranges->at(0).IsEverything(max_char) ? on_success() : NULL;
3453 // Finds the fixed match length of a sequence of nodes that goes from
3454 // this alternative and back to this choice node. If there are variable
3455 // length nodes or other complications in the way then return a sentinel
3456 // value indicating that a greedy loop cannot be constructed.
3457 int ChoiceNode::GreedyLoopTextLengthForAlternative(
3458 GuardedAlternative* alternative) {
3460 RegExpNode* node = alternative->node();
3461 // Later we will generate code for all these text nodes using recursion
3462 // so we have to limit the max number.
3463 int recursion_depth = 0;
3464 while (node != this) {
3465 if (recursion_depth++ > RegExpCompiler::kMaxRecursion) {
3466 return kNodeIsTooComplexForGreedyLoops;
3468 int node_length = node->GreedyLoopTextLength();
3469 if (node_length == kNodeIsTooComplexForGreedyLoops) {
3470 return kNodeIsTooComplexForGreedyLoops;
3472 length += node_length;
3473 SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node);
3474 node = seq_node->on_success();
3480 void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
3481 DCHECK_EQ(loop_node_, NULL);
3482 AddAlternative(alt);
3483 loop_node_ = alt.node();
3487 void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
3488 DCHECK_EQ(continue_node_, NULL);
3489 AddAlternative(alt);
3490 continue_node_ = alt.node();
3494 void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3495 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
3496 if (trace->stop_node() == this) {
3498 GreedyLoopTextLengthForAlternative(&(alternatives_->at(0)));
3499 DCHECK(text_length != kNodeIsTooComplexForGreedyLoops);
3500 // Update the counter-based backtracking info on the stack. This is an
3501 // optimization for greedy loops (see below).
3502 DCHECK(trace->cp_offset() == text_length);
3503 macro_assembler->AdvanceCurrentPosition(text_length);
3504 macro_assembler->GoTo(trace->loop_label());
3507 DCHECK(trace->stop_node() == NULL);
3508 if (!trace->is_trivial()) {
3509 trace->Flush(compiler, this);
3512 ChoiceNode::Emit(compiler, trace);
3516 int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler,
3517 int eats_at_least) {
3518 int preload_characters = Min(4, eats_at_least);
3519 if (compiler->macro_assembler()->CanReadUnaligned()) {
3520 bool ascii = compiler->ascii();
3522 if (preload_characters > 4) preload_characters = 4;
3523 // We can't preload 3 characters because there is no machine instruction
3524 // to do that. We can't just load 4 because we could be reading
3525 // beyond the end of the string, which could cause a memory fault.
3526 if (preload_characters == 3) preload_characters = 2;
3528 if (preload_characters > 2) preload_characters = 2;
3531 if (preload_characters > 1) preload_characters = 1;
3533 return preload_characters;
3537 // This class is used when generating the alternatives in a choice node. It
3538 // records the way the alternative is being code generated.
3539 class AlternativeGeneration: public Malloced {
3541 AlternativeGeneration()
3542 : possible_success(),
3543 expects_preload(false),
3545 quick_check_details() { }
3546 Label possible_success;
3547 bool expects_preload;
3549 QuickCheckDetails quick_check_details;
3553 // Creates a list of AlternativeGenerations. If the list has a reasonable
3554 // size then it is on the stack, otherwise the excess is on the heap.
3555 class AlternativeGenerationList {
3557 AlternativeGenerationList(int count, Zone* zone)
3558 : alt_gens_(count, zone) {
3559 for (int i = 0; i < count && i < kAFew; i++) {
3560 alt_gens_.Add(a_few_alt_gens_ + i, zone);
3562 for (int i = kAFew; i < count; i++) {
3563 alt_gens_.Add(new AlternativeGeneration(), zone);
3566 ~AlternativeGenerationList() {
3567 for (int i = kAFew; i < alt_gens_.length(); i++) {
3568 delete alt_gens_[i];
3569 alt_gens_[i] = NULL;
3573 AlternativeGeneration* at(int i) {
3574 return alt_gens_[i];
3578 static const int kAFew = 10;
3579 ZoneList<AlternativeGeneration*> alt_gens_;
3580 AlternativeGeneration a_few_alt_gens_[kAFew];
3584 // The '2' variant is has inclusive from and exclusive to.
3585 // This covers \s as defined in ECMA-262 5.1, 15.10.2.12,
3586 // which include WhiteSpace (7.2) or LineTerminator (7.3) values.
3587 static const int kSpaceRanges[] = { '\t', '\r' + 1, ' ', ' ' + 1,
3588 0x00A0, 0x00A1, 0x1680, 0x1681, 0x180E, 0x180F, 0x2000, 0x200B,
3589 0x2028, 0x202A, 0x202F, 0x2030, 0x205F, 0x2060, 0x3000, 0x3001,
3590 0xFEFF, 0xFF00, 0x10000 };
3591 static const int kSpaceRangeCount = ARRAY_SIZE(kSpaceRanges);
3593 static const int kWordRanges[] = {
3594 '0', '9' + 1, 'A', 'Z' + 1, '_', '_' + 1, 'a', 'z' + 1, 0x10000 };
3595 static const int kWordRangeCount = ARRAY_SIZE(kWordRanges);
3596 static const int kDigitRanges[] = { '0', '9' + 1, 0x10000 };
3597 static const int kDigitRangeCount = ARRAY_SIZE(kDigitRanges);
3598 static const int kSurrogateRanges[] = { 0xd800, 0xe000, 0x10000 };
3599 static const int kSurrogateRangeCount = ARRAY_SIZE(kSurrogateRanges);
3600 static const int kLineTerminatorRanges[] = { 0x000A, 0x000B, 0x000D, 0x000E,
3601 0x2028, 0x202A, 0x10000 };
3602 static const int kLineTerminatorRangeCount = ARRAY_SIZE(kLineTerminatorRanges);
3605 void BoyerMoorePositionInfo::Set(int character) {
3606 SetInterval(Interval(character, character));
3610 void BoyerMoorePositionInfo::SetInterval(const Interval& interval) {
3611 s_ = AddRange(s_, kSpaceRanges, kSpaceRangeCount, interval);
3612 w_ = AddRange(w_, kWordRanges, kWordRangeCount, interval);
3613 d_ = AddRange(d_, kDigitRanges, kDigitRangeCount, interval);
3615 AddRange(surrogate_, kSurrogateRanges, kSurrogateRangeCount, interval);
3616 if (interval.to() - interval.from() >= kMapSize - 1) {
3617 if (map_count_ != kMapSize) {
3618 map_count_ = kMapSize;
3619 for (int i = 0; i < kMapSize; i++) map_->at(i) = true;
3623 for (int i = interval.from(); i <= interval.to(); i++) {
3624 int mod_character = (i & kMask);
3625 if (!map_->at(mod_character)) {
3627 map_->at(mod_character) = true;
3629 if (map_count_ == kMapSize) return;
3634 void BoyerMoorePositionInfo::SetAll() {
3635 s_ = w_ = d_ = kLatticeUnknown;
3636 if (map_count_ != kMapSize) {
3637 map_count_ = kMapSize;
3638 for (int i = 0; i < kMapSize; i++) map_->at(i) = true;
3643 BoyerMooreLookahead::BoyerMooreLookahead(
3644 int length, RegExpCompiler* compiler, Zone* zone)
3646 compiler_(compiler) {
3647 if (compiler->ascii()) {
3648 max_char_ = String::kMaxOneByteCharCode;
3650 max_char_ = String::kMaxUtf16CodeUnit;
3652 bitmaps_ = new(zone) ZoneList<BoyerMoorePositionInfo*>(length, zone);
3653 for (int i = 0; i < length; i++) {
3654 bitmaps_->Add(new(zone) BoyerMoorePositionInfo(zone), zone);
3659 // Find the longest range of lookahead that has the fewest number of different
3660 // characters that can occur at a given position. Since we are optimizing two
3661 // different parameters at once this is a tradeoff.
3662 bool BoyerMooreLookahead::FindWorthwhileInterval(int* from, int* to) {
3663 int biggest_points = 0;
3664 // If more than 32 characters out of 128 can occur it is unlikely that we can
3665 // be lucky enough to step forwards much of the time.
3666 const int kMaxMax = 32;
3667 for (int max_number_of_chars = 4;
3668 max_number_of_chars < kMaxMax;
3669 max_number_of_chars *= 2) {
3671 FindBestInterval(max_number_of_chars, biggest_points, from, to);
3673 if (biggest_points == 0) return false;
3678 // Find the highest-points range between 0 and length_ where the character
3679 // information is not too vague. 'Too vague' means that there are more than
3680 // max_number_of_chars that can occur at this position. Calculates the number
3681 // of points as the product of width-of-the-range and
3682 // probability-of-finding-one-of-the-characters, where the probability is
3683 // calculated using the frequency distribution of the sample subject string.
3684 int BoyerMooreLookahead::FindBestInterval(
3685 int max_number_of_chars, int old_biggest_points, int* from, int* to) {
3686 int biggest_points = old_biggest_points;
3687 static const int kSize = RegExpMacroAssembler::kTableSize;
3688 for (int i = 0; i < length_; ) {
3689 while (i < length_ && Count(i) > max_number_of_chars) i++;
3690 if (i == length_) break;
3691 int remembered_from = i;
3692 bool union_map[kSize];
3693 for (int j = 0; j < kSize; j++) union_map[j] = false;
3694 while (i < length_ && Count(i) <= max_number_of_chars) {
3695 BoyerMoorePositionInfo* map = bitmaps_->at(i);
3696 for (int j = 0; j < kSize; j++) union_map[j] |= map->at(j);
3700 for (int j = 0; j < kSize; j++) {
3702 // Add 1 to the frequency to give a small per-character boost for
3703 // the cases where our sampling is not good enough and many
3704 // characters have a frequency of zero. This means the frequency
3705 // can theoretically be up to 2*kSize though we treat it mostly as
3706 // a fraction of kSize.
3707 frequency += compiler_->frequency_collator()->Frequency(j) + 1;
3710 // We use the probability of skipping times the distance we are skipping to
3711 // judge the effectiveness of this. Actually we have a cut-off: By
3712 // dividing by 2 we switch off the skipping if the probability of skipping
3713 // is less than 50%. This is because the multibyte mask-and-compare
3714 // skipping in quickcheck is more likely to do well on this case.
3715 bool in_quickcheck_range = ((i - remembered_from < 4) ||
3716 (compiler_->ascii() ? remembered_from <= 4 : remembered_from <= 2));
3717 // Called 'probability' but it is only a rough estimate and can actually
3718 // be outside the 0-kSize range.
3719 int probability = (in_quickcheck_range ? kSize / 2 : kSize) - frequency;
3720 int points = (i - remembered_from) * probability;
3721 if (points > biggest_points) {
3722 *from = remembered_from;
3724 biggest_points = points;
3727 return biggest_points;
3731 // Take all the characters that will not prevent a successful match if they
3732 // occur in the subject string in the range between min_lookahead and
3733 // max_lookahead (inclusive) measured from the current position. If the
3734 // character at max_lookahead offset is not one of these characters, then we
3735 // can safely skip forwards by the number of characters in the range.
3736 int BoyerMooreLookahead::GetSkipTable(int min_lookahead,
3738 Handle<ByteArray> boolean_skip_table) {
3739 const int kSize = RegExpMacroAssembler::kTableSize;
3741 const int kSkipArrayEntry = 0;
3742 const int kDontSkipArrayEntry = 1;
3744 for (int i = 0; i < kSize; i++) {
3745 boolean_skip_table->set(i, kSkipArrayEntry);
3747 int skip = max_lookahead + 1 - min_lookahead;
3749 for (int i = max_lookahead; i >= min_lookahead; i--) {
3750 BoyerMoorePositionInfo* map = bitmaps_->at(i);
3751 for (int j = 0; j < kSize; j++) {
3753 boolean_skip_table->set(j, kDontSkipArrayEntry);
3762 // See comment above on the implementation of GetSkipTable.
3763 bool BoyerMooreLookahead::EmitSkipInstructions(RegExpMacroAssembler* masm) {
3764 const int kSize = RegExpMacroAssembler::kTableSize;
3766 int min_lookahead = 0;
3767 int max_lookahead = 0;
3769 if (!FindWorthwhileInterval(&min_lookahead, &max_lookahead)) return false;
3771 bool found_single_character = false;
3772 int single_character = 0;
3773 for (int i = max_lookahead; i >= min_lookahead; i--) {
3774 BoyerMoorePositionInfo* map = bitmaps_->at(i);
3775 if (map->map_count() > 1 ||
3776 (found_single_character && map->map_count() != 0)) {
3777 found_single_character = false;
3780 for (int j = 0; j < kSize; j++) {
3782 found_single_character = true;
3783 single_character = j;
3789 int lookahead_width = max_lookahead + 1 - min_lookahead;
3791 if (found_single_character && lookahead_width == 1 && max_lookahead < 3) {
3792 // The mask-compare can probably handle this better.
3796 if (found_single_character) {
3799 masm->LoadCurrentCharacter(max_lookahead, &cont, true);
3800 if (max_char_ > kSize) {
3801 masm->CheckCharacterAfterAnd(single_character,
3802 RegExpMacroAssembler::kTableMask,
3805 masm->CheckCharacter(single_character, &cont);
3807 masm->AdvanceCurrentPosition(lookahead_width);
3813 Factory* factory = masm->zone()->isolate()->factory();
3814 Handle<ByteArray> boolean_skip_table = factory->NewByteArray(kSize, TENURED);
3815 int skip_distance = GetSkipTable(
3816 min_lookahead, max_lookahead, boolean_skip_table);
3817 DCHECK(skip_distance != 0);
3821 masm->LoadCurrentCharacter(max_lookahead, &cont, true);
3822 masm->CheckBitInTable(boolean_skip_table, &cont);
3823 masm->AdvanceCurrentPosition(skip_distance);
3831 /* Code generation for choice nodes.
3833 * We generate quick checks that do a mask and compare to eliminate a
3834 * choice. If the quick check succeeds then it jumps to the continuation to
3835 * do slow checks and check subsequent nodes. If it fails (the common case)
3836 * it falls through to the next choice.
3838 * Here is the desired flow graph. Nodes directly below each other imply
3839 * fallthrough. Alternatives 1 and 2 have quick checks. Alternative
3840 * 3 doesn't have a quick check so we have to call the slow check.
3841 * Nodes are marked Qn for quick checks and Sn for slow checks. The entire
3842 * regexp continuation is generated directly after the Sn node, up to the
3843 * next GoTo if we decide to reuse some already generated code. Some
3844 * nodes expect preload_characters to be preloaded into the current
3845 * character register. R nodes do this preloading. Vertices are marked
3846 * F for failures and S for success (possible success in the case of quick
3847 * nodes). L, V, < and > are used as arrow heads.
3881 * For greedy loops we reverse our expectation and expect to match rather
3882 * than fail. Therefore we want the loop code to look like this (U is the
3883 * unwind code that steps back in the greedy loop). The following alternatives
3884 * look the same as above.
3909 void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3910 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
3911 int choice_count = alternatives_->length();
3913 for (int i = 0; i < choice_count - 1; i++) {
3914 GuardedAlternative alternative = alternatives_->at(i);
3915 ZoneList<Guard*>* guards = alternative.guards();
3916 int guard_count = (guards == NULL) ? 0 : guards->length();
3917 for (int j = 0; j < guard_count; j++) {
3918 DCHECK(!trace->mentions_reg(guards->at(j)->reg()));
3923 LimitResult limit_result = LimitVersions(compiler, trace);
3924 if (limit_result == DONE) return;
3925 DCHECK(limit_result == CONTINUE);
3927 int new_flush_budget = trace->flush_budget() / choice_count;
3928 if (trace->flush_budget() == 0 && trace->actions() != NULL) {
3929 trace->Flush(compiler, this);
3933 RecursionCheck rc(compiler);
3935 Trace* current_trace = trace;
3937 int text_length = GreedyLoopTextLengthForAlternative(&(alternatives_->at(0)));
3938 bool greedy_loop = false;
3939 Label greedy_loop_label;
3940 Trace counter_backtrack_trace;
3941 counter_backtrack_trace.set_backtrack(&greedy_loop_label);
3942 if (not_at_start()) counter_backtrack_trace.set_at_start(false);
3944 if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) {
3945 // Here we have special handling for greedy loops containing only text nodes
3946 // and other simple nodes. These are handled by pushing the current
3947 // position on the stack and then incrementing the current position each
3948 // time around the switch. On backtrack we decrement the current position
3949 // and check it against the pushed value. This avoids pushing backtrack
3950 // information for each iteration of the loop, which could take up a lot of
3953 DCHECK(trace->stop_node() == NULL);
3954 macro_assembler->PushCurrentPosition();
3955 current_trace = &counter_backtrack_trace;
3956 Label greedy_match_failed;
3957 Trace greedy_match_trace;
3958 if (not_at_start()) greedy_match_trace.set_at_start(false);
3959 greedy_match_trace.set_backtrack(&greedy_match_failed);
3961 macro_assembler->Bind(&loop_label);
3962 greedy_match_trace.set_stop_node(this);
3963 greedy_match_trace.set_loop_label(&loop_label);
3964 alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
3965 macro_assembler->Bind(&greedy_match_failed);
3968 Label second_choice; // For use in greedy matches.
3969 macro_assembler->Bind(&second_choice);
3971 int first_normal_choice = greedy_loop ? 1 : 0;
3973 bool not_at_start = current_trace->at_start() == Trace::FALSE_VALUE;
3974 const int kEatsAtLeastNotYetInitialized = -1;
3975 int eats_at_least = kEatsAtLeastNotYetInitialized;
3977 bool skip_was_emitted = false;
3979 if (!greedy_loop && choice_count == 2) {
3980 GuardedAlternative alt1 = alternatives_->at(1);
3981 if (alt1.guards() == NULL || alt1.guards()->length() == 0) {
3982 RegExpNode* eats_anything_node = alt1.node();
3983 if (eats_anything_node->GetSuccessorOfOmnivorousTextNode(compiler) ==
3985 // At this point we know that we are at a non-greedy loop that will eat
3986 // any character one at a time. Any non-anchored regexp has such a
3987 // loop prepended to it in order to find where it starts. We look for
3988 // a pattern of the form ...abc... where we can look 6 characters ahead
3989 // and step forwards 3 if the character is not one of abc. Abc need
3990 // not be atoms, they can be any reasonably limited character class or
3991 // small alternation.
3992 DCHECK(trace->is_trivial()); // This is the case on LoopChoiceNodes.
3993 BoyerMooreLookahead* lookahead = bm_info(not_at_start);
3994 if (lookahead == NULL) {
3995 eats_at_least = Min(kMaxLookaheadForBoyerMoore,
3996 EatsAtLeast(kMaxLookaheadForBoyerMoore,
3999 if (eats_at_least >= 1) {
4000 BoyerMooreLookahead* bm =
4001 new(zone()) BoyerMooreLookahead(eats_at_least,
4004 GuardedAlternative alt0 = alternatives_->at(0);
4005 alt0.node()->FillInBMInfo(0, kRecursionBudget, bm, not_at_start);
4006 skip_was_emitted = bm->EmitSkipInstructions(macro_assembler);
4009 skip_was_emitted = lookahead->EmitSkipInstructions(macro_assembler);
4015 if (eats_at_least == kEatsAtLeastNotYetInitialized) {
4016 // Save some time by looking at most one machine word ahead.
4018 EatsAtLeast(compiler->ascii() ? 4 : 2, kRecursionBudget, not_at_start);
4020 int preload_characters = CalculatePreloadCharacters(compiler, eats_at_least);
4022 bool preload_is_current = !skip_was_emitted &&
4023 (current_trace->characters_preloaded() == preload_characters);
4024 bool preload_has_checked_bounds = preload_is_current;
4026 AlternativeGenerationList alt_gens(choice_count, zone());
4028 // For now we just call all choices one after the other. The idea ultimately
4029 // is to use the Dispatch table to try only the relevant ones.
4030 for (int i = first_normal_choice; i < choice_count; i++) {
4031 GuardedAlternative alternative = alternatives_->at(i);
4032 AlternativeGeneration* alt_gen = alt_gens.at(i);
4033 alt_gen->quick_check_details.set_characters(preload_characters);
4034 ZoneList<Guard*>* guards = alternative.guards();
4035 int guard_count = (guards == NULL) ? 0 : guards->length();
4036 Trace new_trace(*current_trace);
4037 new_trace.set_characters_preloaded(preload_is_current ?
4038 preload_characters :
4040 if (preload_has_checked_bounds) {
4041 new_trace.set_bound_checked_up_to(preload_characters);
4043 new_trace.quick_check_performed()->Clear();
4044 if (not_at_start_) new_trace.set_at_start(Trace::FALSE_VALUE);
4045 alt_gen->expects_preload = preload_is_current;
4046 bool generate_full_check_inline = false;
4047 if (FLAG_regexp_optimization &&
4048 try_to_emit_quick_check_for_alternative(i) &&
4049 alternative.node()->EmitQuickCheck(compiler,
4051 preload_has_checked_bounds,
4052 &alt_gen->possible_success,
4053 &alt_gen->quick_check_details,
4054 i < choice_count - 1)) {
4055 // Quick check was generated for this choice.
4056 preload_is_current = true;
4057 preload_has_checked_bounds = true;
4058 // On the last choice in the ChoiceNode we generated the quick
4059 // check to fall through on possible success. So now we need to
4060 // generate the full check inline.
4061 if (i == choice_count - 1) {
4062 macro_assembler->Bind(&alt_gen->possible_success);
4063 new_trace.set_quick_check_performed(&alt_gen->quick_check_details);
4064 new_trace.set_characters_preloaded(preload_characters);
4065 new_trace.set_bound_checked_up_to(preload_characters);
4066 generate_full_check_inline = true;
4068 } else if (alt_gen->quick_check_details.cannot_match()) {
4069 if (i == choice_count - 1 && !greedy_loop) {
4070 macro_assembler->GoTo(trace->backtrack());
4074 // No quick check was generated. Put the full code here.
4075 // If this is not the first choice then there could be slow checks from
4076 // previous cases that go here when they fail. There's no reason to
4077 // insist that they preload characters since the slow check we are about
4078 // to generate probably can't use it.
4079 if (i != first_normal_choice) {
4080 alt_gen->expects_preload = false;
4081 new_trace.InvalidateCurrentCharacter();
4083 if (i < choice_count - 1) {
4084 new_trace.set_backtrack(&alt_gen->after);
4086 generate_full_check_inline = true;
4088 if (generate_full_check_inline) {
4089 if (new_trace.actions() != NULL) {
4090 new_trace.set_flush_budget(new_flush_budget);
4092 for (int j = 0; j < guard_count; j++) {
4093 GenerateGuard(macro_assembler, guards->at(j), &new_trace);
4095 alternative.node()->Emit(compiler, &new_trace);
4096 preload_is_current = false;
4098 macro_assembler->Bind(&alt_gen->after);
4101 macro_assembler->Bind(&greedy_loop_label);
4102 // If we have unwound to the bottom then backtrack.
4103 macro_assembler->CheckGreedyLoop(trace->backtrack());
4104 // Otherwise try the second priority at an earlier position.
4105 macro_assembler->AdvanceCurrentPosition(-text_length);
4106 macro_assembler->GoTo(&second_choice);
4109 // At this point we need to generate slow checks for the alternatives where
4110 // the quick check was inlined. We can recognize these because the associated
4112 for (int i = first_normal_choice; i < choice_count - 1; i++) {
4113 AlternativeGeneration* alt_gen = alt_gens.at(i);
4114 Trace new_trace(*current_trace);
4115 // If there are actions to be flushed we have to limit how many times
4116 // they are flushed. Take the budget of the parent trace and distribute
4117 // it fairly amongst the children.
4118 if (new_trace.actions() != NULL) {
4119 new_trace.set_flush_budget(new_flush_budget);
4121 EmitOutOfLineContinuation(compiler,
4123 alternatives_->at(i),
4126 alt_gens.at(i + 1)->expects_preload);
4131 void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
4133 GuardedAlternative alternative,
4134 AlternativeGeneration* alt_gen,
4135 int preload_characters,
4136 bool next_expects_preload) {
4137 if (!alt_gen->possible_success.is_linked()) return;
4139 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
4140 macro_assembler->Bind(&alt_gen->possible_success);
4141 Trace out_of_line_trace(*trace);
4142 out_of_line_trace.set_characters_preloaded(preload_characters);
4143 out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details);
4144 if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE_VALUE);
4145 ZoneList<Guard*>* guards = alternative.guards();
4146 int guard_count = (guards == NULL) ? 0 : guards->length();
4147 if (next_expects_preload) {
4148 Label reload_current_char;
4149 out_of_line_trace.set_backtrack(&reload_current_char);
4150 for (int j = 0; j < guard_count; j++) {
4151 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
4153 alternative.node()->Emit(compiler, &out_of_line_trace);
4154 macro_assembler->Bind(&reload_current_char);
4155 // Reload the current character, since the next quick check expects that.
4156 // We don't need to check bounds here because we only get into this
4157 // code through a quick check which already did the checked load.
4158 macro_assembler->LoadCurrentCharacter(trace->cp_offset(),
4161 preload_characters);
4162 macro_assembler->GoTo(&(alt_gen->after));
4164 out_of_line_trace.set_backtrack(&(alt_gen->after));
4165 for (int j = 0; j < guard_count; j++) {
4166 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
4168 alternative.node()->Emit(compiler, &out_of_line_trace);
4173 void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
4174 RegExpMacroAssembler* assembler = compiler->macro_assembler();
4175 LimitResult limit_result = LimitVersions(compiler, trace);
4176 if (limit_result == DONE) return;
4177 DCHECK(limit_result == CONTINUE);
4179 RecursionCheck rc(compiler);
4181 switch (action_type_) {
4182 case STORE_POSITION: {
4183 Trace::DeferredCapture
4184 new_capture(data_.u_position_register.reg,
4185 data_.u_position_register.is_capture,
4187 Trace new_trace = *trace;
4188 new_trace.add_action(&new_capture);
4189 on_success()->Emit(compiler, &new_trace);
4192 case INCREMENT_REGISTER: {
4193 Trace::DeferredIncrementRegister
4194 new_increment(data_.u_increment_register.reg);
4195 Trace new_trace = *trace;
4196 new_trace.add_action(&new_increment);
4197 on_success()->Emit(compiler, &new_trace);
4200 case SET_REGISTER: {
4201 Trace::DeferredSetRegister
4202 new_set(data_.u_store_register.reg, data_.u_store_register.value);
4203 Trace new_trace = *trace;
4204 new_trace.add_action(&new_set);
4205 on_success()->Emit(compiler, &new_trace);
4208 case CLEAR_CAPTURES: {
4209 Trace::DeferredClearCaptures
4210 new_capture(Interval(data_.u_clear_captures.range_from,
4211 data_.u_clear_captures.range_to));
4212 Trace new_trace = *trace;
4213 new_trace.add_action(&new_capture);
4214 on_success()->Emit(compiler, &new_trace);
4217 case BEGIN_SUBMATCH:
4218 if (!trace->is_trivial()) {
4219 trace->Flush(compiler, this);
4221 assembler->WriteCurrentPositionToRegister(
4222 data_.u_submatch.current_position_register, 0);
4223 assembler->WriteStackPointerToRegister(
4224 data_.u_submatch.stack_pointer_register);
4225 on_success()->Emit(compiler, trace);
4228 case EMPTY_MATCH_CHECK: {
4229 int start_pos_reg = data_.u_empty_match_check.start_register;
4231 int rep_reg = data_.u_empty_match_check.repetition_register;
4232 bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister);
4233 bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos);
4234 if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) {
4235 // If we know we haven't advanced and there is no minimum we
4236 // can just backtrack immediately.
4237 assembler->GoTo(trace->backtrack());
4238 } else if (know_dist && stored_pos < trace->cp_offset()) {
4239 // If we know we've advanced we can generate the continuation
4241 on_success()->Emit(compiler, trace);
4242 } else if (!trace->is_trivial()) {
4243 trace->Flush(compiler, this);
4245 Label skip_empty_check;
4246 // If we have a minimum number of repetitions we check the current
4247 // number first and skip the empty check if it's not enough.
4249 int limit = data_.u_empty_match_check.repetition_limit;
4250 assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check);
4252 // If the match is empty we bail out, otherwise we fall through
4253 // to the on-success continuation.
4254 assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register,
4255 trace->backtrack());
4256 assembler->Bind(&skip_empty_check);
4257 on_success()->Emit(compiler, trace);
4261 case POSITIVE_SUBMATCH_SUCCESS: {
4262 if (!trace->is_trivial()) {
4263 trace->Flush(compiler, this);
4266 assembler->ReadCurrentPositionFromRegister(
4267 data_.u_submatch.current_position_register);
4268 assembler->ReadStackPointerFromRegister(
4269 data_.u_submatch.stack_pointer_register);
4270 int clear_register_count = data_.u_submatch.clear_register_count;
4271 if (clear_register_count == 0) {
4272 on_success()->Emit(compiler, trace);
4275 int clear_registers_from = data_.u_submatch.clear_register_from;
4276 Label clear_registers_backtrack;
4277 Trace new_trace = *trace;
4278 new_trace.set_backtrack(&clear_registers_backtrack);
4279 on_success()->Emit(compiler, &new_trace);
4281 assembler->Bind(&clear_registers_backtrack);
4282 int clear_registers_to = clear_registers_from + clear_register_count - 1;
4283 assembler->ClearRegisters(clear_registers_from, clear_registers_to);
4285 DCHECK(trace->backtrack() == NULL);
4286 assembler->Backtrack();
4295 void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
4296 RegExpMacroAssembler* assembler = compiler->macro_assembler();
4297 if (!trace->is_trivial()) {
4298 trace->Flush(compiler, this);
4302 LimitResult limit_result = LimitVersions(compiler, trace);
4303 if (limit_result == DONE) return;
4304 DCHECK(limit_result == CONTINUE);
4306 RecursionCheck rc(compiler);
4308 DCHECK_EQ(start_reg_ + 1, end_reg_);
4309 if (compiler->ignore_case()) {
4310 assembler->CheckNotBackReferenceIgnoreCase(start_reg_,
4311 trace->backtrack());
4313 assembler->CheckNotBackReference(start_reg_, trace->backtrack());
4315 on_success()->Emit(compiler, trace);
4319 // -------------------------------------------------------------------
4326 class DotPrinter: public NodeVisitor {
4328 DotPrinter(OStream& os, bool ignore_case) // NOLINT
4330 ignore_case_(ignore_case) {}
4331 void PrintNode(const char* label, RegExpNode* node);
4332 void Visit(RegExpNode* node);
4333 void PrintAttributes(RegExpNode* from);
4334 void PrintOnFailure(RegExpNode* from, RegExpNode* to);
4335 #define DECLARE_VISIT(Type) \
4336 virtual void Visit##Type(Type##Node* that);
4337 FOR_EACH_NODE_TYPE(DECLARE_VISIT)
4338 #undef DECLARE_VISIT
4345 void DotPrinter::PrintNode(const char* label, RegExpNode* node) {
4346 os_ << "digraph G {\n graph [label=\"";
4347 for (int i = 0; label[i]; i++) {
4366 void DotPrinter::Visit(RegExpNode* node) {
4367 if (node->info()->visited) return;
4368 node->info()->visited = true;
4373 void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
4374 os_ << " n" << from << " -> n" << on_failure << " [style=dotted];\n";
4379 class TableEntryBodyPrinter {
4381 TableEntryBodyPrinter(OStream& os, ChoiceNode* choice) // NOLINT
4384 void Call(uc16 from, DispatchTable::Entry entry) {
4385 OutSet* out_set = entry.out_set();
4386 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
4387 if (out_set->Get(i)) {
4388 os_ << " n" << choice() << ":s" << from << "o" << i << " -> n"
4389 << choice()->alternatives()->at(i).node() << ";\n";
4394 ChoiceNode* choice() { return choice_; }
4396 ChoiceNode* choice_;
4400 class TableEntryHeaderPrinter {
4402 explicit TableEntryHeaderPrinter(OStream& os) // NOLINT
4405 void Call(uc16 from, DispatchTable::Entry entry) {
4411 os_ << "{\\" << AsUC16(from) << "-\\" << AsUC16(entry.to()) << "|{";
4412 OutSet* out_set = entry.out_set();
4414 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
4415 if (out_set->Get(i)) {
4416 if (priority > 0) os_ << "|";
4417 os_ << "<s" << from << "o" << i << "> " << priority;
4430 class AttributePrinter {
4432 explicit AttributePrinter(OStream& os) // NOLINT
4435 void PrintSeparator() {
4442 void PrintBit(const char* name, bool value) {
4445 os_ << "{" << name << "}";
4447 void PrintPositive(const char* name, int value) {
4448 if (value < 0) return;
4450 os_ << "{" << name << "|" << value << "}";
4459 void DotPrinter::PrintAttributes(RegExpNode* that) {
4460 os_ << " a" << that << " [shape=Mrecord, color=grey, fontcolor=grey, "
4461 << "margin=0.1, fontsize=10, label=\"{";
4462 AttributePrinter printer(os_);
4463 NodeInfo* info = that->info();
4464 printer.PrintBit("NI", info->follows_newline_interest);
4465 printer.PrintBit("WI", info->follows_word_interest);
4466 printer.PrintBit("SI", info->follows_start_interest);
4467 Label* label = that->label();
4468 if (label->is_bound())
4469 printer.PrintPositive("@", label->pos());
4471 << " a" << that << " -> n" << that
4472 << " [style=dashed, color=grey, arrowhead=none];\n";
4476 static const bool kPrintDispatchTable = false;
4477 void DotPrinter::VisitChoice(ChoiceNode* that) {
4478 if (kPrintDispatchTable) {
4479 os_ << " n" << that << " [shape=Mrecord, label=\"";
4480 TableEntryHeaderPrinter header_printer(os_);
4481 that->GetTable(ignore_case_)->ForEach(&header_printer);
4483 PrintAttributes(that);
4484 TableEntryBodyPrinter body_printer(os_, that);
4485 that->GetTable(ignore_case_)->ForEach(&body_printer);
4487 os_ << " n" << that << " [shape=Mrecord, label=\"?\"];\n";
4488 for (int i = 0; i < that->alternatives()->length(); i++) {
4489 GuardedAlternative alt = that->alternatives()->at(i);
4490 os_ << " n" << that << " -> n" << alt.node();
4493 for (int i = 0; i < that->alternatives()->length(); i++) {
4494 GuardedAlternative alt = that->alternatives()->at(i);
4495 alt.node()->Accept(this);
4500 void DotPrinter::VisitText(TextNode* that) {
4501 Zone* zone = that->zone();
4502 os_ << " n" << that << " [label=\"";
4503 for (int i = 0; i < that->elements()->length(); i++) {
4504 if (i > 0) os_ << " ";
4505 TextElement elm = that->elements()->at(i);
4506 switch (elm.text_type()) {
4507 case TextElement::ATOM: {
4508 Vector<const uc16> data = elm.atom()->data();
4509 for (int i = 0; i < data.length(); i++) {
4510 os_ << static_cast<char>(data[i]);
4514 case TextElement::CHAR_CLASS: {
4515 RegExpCharacterClass* node = elm.char_class();
4517 if (node->is_negated()) os_ << "^";
4518 for (int j = 0; j < node->ranges(zone)->length(); j++) {
4519 CharacterRange range = node->ranges(zone)->at(j);
4520 os_ << AsUC16(range.from()) << "-" << AsUC16(range.to());
4529 os_ << "\", shape=box, peripheries=2];\n";
4530 PrintAttributes(that);
4531 os_ << " n" << that << " -> n" << that->on_success() << ";\n";
4532 Visit(that->on_success());
4536 void DotPrinter::VisitBackReference(BackReferenceNode* that) {
4537 os_ << " n" << that << " [label=\"$" << that->start_register() << "..$"
4538 << that->end_register() << "\", shape=doubleoctagon];\n";
4539 PrintAttributes(that);
4540 os_ << " n" << that << " -> n" << that->on_success() << ";\n";
4541 Visit(that->on_success());
4545 void DotPrinter::VisitEnd(EndNode* that) {
4546 os_ << " n" << that << " [style=bold, shape=point];\n";
4547 PrintAttributes(that);
4551 void DotPrinter::VisitAssertion(AssertionNode* that) {
4552 os_ << " n" << that << " [";
4553 switch (that->assertion_type()) {
4554 case AssertionNode::AT_END:
4555 os_ << "label=\"$\", shape=septagon";
4557 case AssertionNode::AT_START:
4558 os_ << "label=\"^\", shape=septagon";
4560 case AssertionNode::AT_BOUNDARY:
4561 os_ << "label=\"\\b\", shape=septagon";
4563 case AssertionNode::AT_NON_BOUNDARY:
4564 os_ << "label=\"\\B\", shape=septagon";
4566 case AssertionNode::AFTER_NEWLINE:
4567 os_ << "label=\"(?<=\\n)\", shape=septagon";
4571 PrintAttributes(that);
4572 RegExpNode* successor = that->on_success();
4573 os_ << " n" << that << " -> n" << successor << ";\n";
4578 void DotPrinter::VisitAction(ActionNode* that) {
4579 os_ << " n" << that << " [";
4580 switch (that->action_type_) {
4581 case ActionNode::SET_REGISTER:
4582 os_ << "label=\"$" << that->data_.u_store_register.reg
4583 << ":=" << that->data_.u_store_register.value << "\", shape=octagon";
4585 case ActionNode::INCREMENT_REGISTER:
4586 os_ << "label=\"$" << that->data_.u_increment_register.reg
4587 << "++\", shape=octagon";
4589 case ActionNode::STORE_POSITION:
4590 os_ << "label=\"$" << that->data_.u_position_register.reg
4591 << ":=$pos\", shape=octagon";
4593 case ActionNode::BEGIN_SUBMATCH:
4594 os_ << "label=\"$" << that->data_.u_submatch.current_position_register
4595 << ":=$pos,begin\", shape=septagon";
4597 case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
4598 os_ << "label=\"escape\", shape=septagon";
4600 case ActionNode::EMPTY_MATCH_CHECK:
4601 os_ << "label=\"$" << that->data_.u_empty_match_check.start_register
4602 << "=$pos?,$" << that->data_.u_empty_match_check.repetition_register
4603 << "<" << that->data_.u_empty_match_check.repetition_limit
4604 << "?\", shape=septagon";
4606 case ActionNode::CLEAR_CAPTURES: {
4607 os_ << "label=\"clear $" << that->data_.u_clear_captures.range_from
4608 << " to $" << that->data_.u_clear_captures.range_to
4609 << "\", shape=septagon";
4614 PrintAttributes(that);
4615 RegExpNode* successor = that->on_success();
4616 os_ << " n" << that << " -> n" << successor << ";\n";
4621 class DispatchTableDumper {
4623 explicit DispatchTableDumper(OStream& os) : os_(os) {}
4624 void Call(uc16 key, DispatchTable::Entry entry);
4630 void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) {
4631 os_ << "[" << AsUC16(key) << "-" << AsUC16(entry.to()) << "]: {";
4632 OutSet* set = entry.out_set();
4634 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
4648 void DispatchTable::Dump() {
4649 OFStream os(stderr);
4650 DispatchTableDumper dumper(os);
4651 tree()->ForEach(&dumper);
4655 void RegExpEngine::DotPrint(const char* label,
4658 OFStream os(stdout);
4659 DotPrinter printer(os, ignore_case);
4660 printer.PrintNode(label, node);
4667 // -------------------------------------------------------------------
4668 // Tree to graph conversion
4670 RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
4671 RegExpNode* on_success) {
4672 ZoneList<TextElement>* elms =
4673 new(compiler->zone()) ZoneList<TextElement>(1, compiler->zone());
4674 elms->Add(TextElement::Atom(this), compiler->zone());
4675 return new(compiler->zone()) TextNode(elms, on_success);
4679 RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
4680 RegExpNode* on_success) {
4681 return new(compiler->zone()) TextNode(elements(), on_success);
4685 static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
4686 const int* special_class,
4688 length--; // Remove final 0x10000.
4689 DCHECK(special_class[length] == 0x10000);
4690 DCHECK(ranges->length() != 0);
4691 DCHECK(length != 0);
4692 DCHECK(special_class[0] != 0);
4693 if (ranges->length() != (length >> 1) + 1) {
4696 CharacterRange range = ranges->at(0);
4697 if (range.from() != 0) {
4700 for (int i = 0; i < length; i += 2) {
4701 if (special_class[i] != (range.to() + 1)) {
4704 range = ranges->at((i >> 1) + 1);
4705 if (special_class[i+1] != range.from()) {
4709 if (range.to() != 0xffff) {
4716 static bool CompareRanges(ZoneList<CharacterRange>* ranges,
4717 const int* special_class,
4719 length--; // Remove final 0x10000.
4720 DCHECK(special_class[length] == 0x10000);
4721 if (ranges->length() * 2 != length) {
4724 for (int i = 0; i < length; i += 2) {
4725 CharacterRange range = ranges->at(i >> 1);
4726 if (range.from() != special_class[i] ||
4727 range.to() != special_class[i + 1] - 1) {
4735 bool RegExpCharacterClass::is_standard(Zone* zone) {
4736 // TODO(lrn): Remove need for this function, by not throwing away information
4741 if (set_.is_standard()) {
4744 if (CompareRanges(set_.ranges(zone), kSpaceRanges, kSpaceRangeCount)) {
4745 set_.set_standard_set_type('s');
4748 if (CompareInverseRanges(set_.ranges(zone), kSpaceRanges, kSpaceRangeCount)) {
4749 set_.set_standard_set_type('S');
4752 if (CompareInverseRanges(set_.ranges(zone),
4753 kLineTerminatorRanges,
4754 kLineTerminatorRangeCount)) {
4755 set_.set_standard_set_type('.');
4758 if (CompareRanges(set_.ranges(zone),
4759 kLineTerminatorRanges,
4760 kLineTerminatorRangeCount)) {
4761 set_.set_standard_set_type('n');
4764 if (CompareRanges(set_.ranges(zone), kWordRanges, kWordRangeCount)) {
4765 set_.set_standard_set_type('w');
4768 if (CompareInverseRanges(set_.ranges(zone), kWordRanges, kWordRangeCount)) {
4769 set_.set_standard_set_type('W');
4776 RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
4777 RegExpNode* on_success) {
4778 return new(compiler->zone()) TextNode(this, on_success);
4782 RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
4783 RegExpNode* on_success) {
4784 ZoneList<RegExpTree*>* alternatives = this->alternatives();
4785 int length = alternatives->length();
4786 ChoiceNode* result =
4787 new(compiler->zone()) ChoiceNode(length, compiler->zone());
4788 for (int i = 0; i < length; i++) {
4789 GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler,
4791 result->AddAlternative(alternative);
4797 RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
4798 RegExpNode* on_success) {
4799 return ToNode(min(),
4808 // Scoped object to keep track of how much we unroll quantifier loops in the
4809 // regexp graph generator.
4810 class RegExpExpansionLimiter {
4812 static const int kMaxExpansionFactor = 6;
4813 RegExpExpansionLimiter(RegExpCompiler* compiler, int factor)
4814 : compiler_(compiler),
4815 saved_expansion_factor_(compiler->current_expansion_factor()),
4816 ok_to_expand_(saved_expansion_factor_ <= kMaxExpansionFactor) {
4818 if (ok_to_expand_) {
4819 if (factor > kMaxExpansionFactor) {
4820 // Avoid integer overflow of the current expansion factor.
4821 ok_to_expand_ = false;
4822 compiler->set_current_expansion_factor(kMaxExpansionFactor + 1);
4824 int new_factor = saved_expansion_factor_ * factor;
4825 ok_to_expand_ = (new_factor <= kMaxExpansionFactor);
4826 compiler->set_current_expansion_factor(new_factor);
4831 ~RegExpExpansionLimiter() {
4832 compiler_->set_current_expansion_factor(saved_expansion_factor_);
4835 bool ok_to_expand() { return ok_to_expand_; }
4838 RegExpCompiler* compiler_;
4839 int saved_expansion_factor_;
4842 DISALLOW_IMPLICIT_CONSTRUCTORS(RegExpExpansionLimiter);
4846 RegExpNode* RegExpQuantifier::ToNode(int min,
4850 RegExpCompiler* compiler,
4851 RegExpNode* on_success,
4852 bool not_at_start) {
4853 // x{f, t} becomes this:
4859 // (r=0)-->(?)---/ [if r < t]
4861 // [if r >= f] \----> ...
4864 // 15.10.2.5 RepeatMatcher algorithm.
4865 // The parser has already eliminated the case where max is 0. In the case
4866 // where max_match is zero the parser has removed the quantifier if min was
4867 // > 0 and removed the atom if min was 0. See AddQuantifierToAtom.
4869 // If we know that we cannot match zero length then things are a little
4870 // simpler since we don't need to make the special zero length match check
4871 // from step 2.1. If the min and max are small we can unroll a little in
4873 static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,}
4874 static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3}
4875 if (max == 0) return on_success; // This can happen due to recursion.
4876 bool body_can_be_empty = (body->min_match() == 0);
4877 int body_start_reg = RegExpCompiler::kNoRegister;
4878 Interval capture_registers = body->CaptureRegisters();
4879 bool needs_capture_clearing = !capture_registers.is_empty();
4880 Zone* zone = compiler->zone();
4882 if (body_can_be_empty) {
4883 body_start_reg = compiler->AllocateRegister();
4884 } else if (FLAG_regexp_optimization && !needs_capture_clearing) {
4885 // Only unroll if there are no captures and the body can't be
4888 RegExpExpansionLimiter limiter(
4889 compiler, min + ((max != min) ? 1 : 0));
4890 if (min > 0 && min <= kMaxUnrolledMinMatches && limiter.ok_to_expand()) {
4891 int new_max = (max == kInfinity) ? max : max - min;
4892 // Recurse once to get the loop or optional matches after the fixed
4894 RegExpNode* answer = ToNode(
4895 0, new_max, is_greedy, body, compiler, on_success, true);
4896 // Unroll the forced matches from 0 to min. This can cause chains of
4897 // TextNodes (which the parser does not generate). These should be
4898 // combined if it turns out they hinder good code generation.
4899 for (int i = 0; i < min; i++) {
4900 answer = body->ToNode(compiler, answer);
4905 if (max <= kMaxUnrolledMaxMatches && min == 0) {
4906 DCHECK(max > 0); // Due to the 'if' above.
4907 RegExpExpansionLimiter limiter(compiler, max);
4908 if (limiter.ok_to_expand()) {
4909 // Unroll the optional matches up to max.
4910 RegExpNode* answer = on_success;
4911 for (int i = 0; i < max; i++) {
4912 ChoiceNode* alternation = new(zone) ChoiceNode(2, zone);
4914 alternation->AddAlternative(
4915 GuardedAlternative(body->ToNode(compiler, answer)));
4916 alternation->AddAlternative(GuardedAlternative(on_success));
4918 alternation->AddAlternative(GuardedAlternative(on_success));
4919 alternation->AddAlternative(
4920 GuardedAlternative(body->ToNode(compiler, answer)));
4922 answer = alternation;
4923 if (not_at_start) alternation->set_not_at_start();
4929 bool has_min = min > 0;
4930 bool has_max = max < RegExpTree::kInfinity;
4931 bool needs_counter = has_min || has_max;
4932 int reg_ctr = needs_counter
4933 ? compiler->AllocateRegister()
4934 : RegExpCompiler::kNoRegister;
4935 LoopChoiceNode* center = new(zone) LoopChoiceNode(body->min_match() == 0,
4937 if (not_at_start) center->set_not_at_start();
4938 RegExpNode* loop_return = needs_counter
4939 ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
4940 : static_cast<RegExpNode*>(center);
4941 if (body_can_be_empty) {
4942 // If the body can be empty we need to check if it was and then
4944 loop_return = ActionNode::EmptyMatchCheck(body_start_reg,
4949 RegExpNode* body_node = body->ToNode(compiler, loop_return);
4950 if (body_can_be_empty) {
4951 // If the body can be empty we need to store the start position
4952 // so we can bail out if it was empty.
4953 body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
4955 if (needs_capture_clearing) {
4956 // Before entering the body of this loop we need to clear captures.
4957 body_node = ActionNode::ClearCaptures(capture_registers, body_node);
4959 GuardedAlternative body_alt(body_node);
4962 new(zone) Guard(reg_ctr, Guard::LT, max);
4963 body_alt.AddGuard(body_guard, zone);
4965 GuardedAlternative rest_alt(on_success);
4967 Guard* rest_guard = new(compiler->zone()) Guard(reg_ctr, Guard::GEQ, min);
4968 rest_alt.AddGuard(rest_guard, zone);
4971 center->AddLoopAlternative(body_alt);
4972 center->AddContinueAlternative(rest_alt);
4974 center->AddContinueAlternative(rest_alt);
4975 center->AddLoopAlternative(body_alt);
4977 if (needs_counter) {
4978 return ActionNode::SetRegister(reg_ctr, 0, center);
4985 RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
4986 RegExpNode* on_success) {
4988 Zone* zone = compiler->zone();
4990 switch (assertion_type()) {
4992 return AssertionNode::AfterNewline(on_success);
4993 case START_OF_INPUT:
4994 return AssertionNode::AtStart(on_success);
4996 return AssertionNode::AtBoundary(on_success);
4998 return AssertionNode::AtNonBoundary(on_success);
5000 return AssertionNode::AtEnd(on_success);
5002 // Compile $ in multiline regexps as an alternation with a positive
5003 // lookahead in one side and an end-of-input on the other side.
5004 // We need two registers for the lookahead.
5005 int stack_pointer_register = compiler->AllocateRegister();
5006 int position_register = compiler->AllocateRegister();
5007 // The ChoiceNode to distinguish between a newline and end-of-input.
5008 ChoiceNode* result = new(zone) ChoiceNode(2, zone);
5009 // Create a newline atom.
5010 ZoneList<CharacterRange>* newline_ranges =
5011 new(zone) ZoneList<CharacterRange>(3, zone);
5012 CharacterRange::AddClassEscape('n', newline_ranges, zone);
5013 RegExpCharacterClass* newline_atom = new(zone) RegExpCharacterClass('n');
5014 TextNode* newline_matcher = new(zone) TextNode(
5016 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
5018 0, // No captures inside.
5019 -1, // Ignored if no captures.
5021 // Create an end-of-input matcher.
5022 RegExpNode* end_of_line = ActionNode::BeginSubmatch(
5023 stack_pointer_register,
5026 // Add the two alternatives to the ChoiceNode.
5027 GuardedAlternative eol_alternative(end_of_line);
5028 result->AddAlternative(eol_alternative);
5029 GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
5030 result->AddAlternative(end_alternative);
5040 RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
5041 RegExpNode* on_success) {
5042 return new(compiler->zone())
5043 BackReferenceNode(RegExpCapture::StartRegister(index()),
5044 RegExpCapture::EndRegister(index()),
5049 RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
5050 RegExpNode* on_success) {
5055 RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler,
5056 RegExpNode* on_success) {
5057 int stack_pointer_register = compiler->AllocateRegister();
5058 int position_register = compiler->AllocateRegister();
5060 const int registers_per_capture = 2;
5061 const int register_of_first_capture = 2;
5062 int register_count = capture_count_ * registers_per_capture;
5063 int register_start =
5064 register_of_first_capture + capture_from_ * registers_per_capture;
5066 RegExpNode* success;
5067 if (is_positive()) {
5068 RegExpNode* node = ActionNode::BeginSubmatch(
5069 stack_pointer_register,
5073 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
5080 // We use a ChoiceNode for a negative lookahead because it has most of
5081 // the characteristics we need. It has the body of the lookahead as its
5082 // first alternative and the expression after the lookahead of the second
5083 // alternative. If the first alternative succeeds then the
5084 // NegativeSubmatchSuccess will unwind the stack including everything the
5085 // choice node set up and backtrack. If the first alternative fails then
5086 // the second alternative is tried, which is exactly the desired result
5087 // for a negative lookahead. The NegativeLookaheadChoiceNode is a special
5088 // ChoiceNode that knows to ignore the first exit when calculating quick
5090 Zone* zone = compiler->zone();
5092 GuardedAlternative body_alt(
5095 success = new(zone) NegativeSubmatchSuccess(stack_pointer_register,
5100 ChoiceNode* choice_node =
5101 new(zone) NegativeLookaheadChoiceNode(body_alt,
5102 GuardedAlternative(on_success),
5104 return ActionNode::BeginSubmatch(stack_pointer_register,
5111 RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
5112 RegExpNode* on_success) {
5113 return ToNode(body(), index(), compiler, on_success);
5117 RegExpNode* RegExpCapture::ToNode(RegExpTree* body,
5119 RegExpCompiler* compiler,
5120 RegExpNode* on_success) {
5121 int start_reg = RegExpCapture::StartRegister(index);
5122 int end_reg = RegExpCapture::EndRegister(index);
5123 RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
5124 RegExpNode* body_node = body->ToNode(compiler, store_end);
5125 return ActionNode::StorePosition(start_reg, true, body_node);
5129 RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
5130 RegExpNode* on_success) {
5131 ZoneList<RegExpTree*>* children = nodes();
5132 RegExpNode* current = on_success;
5133 for (int i = children->length() - 1; i >= 0; i--) {
5134 current = children->at(i)->ToNode(compiler, current);
5140 static void AddClass(const int* elmv,
5142 ZoneList<CharacterRange>* ranges,
5145 DCHECK(elmv[elmc] == 0x10000);
5146 for (int i = 0; i < elmc; i += 2) {
5147 DCHECK(elmv[i] < elmv[i + 1]);
5148 ranges->Add(CharacterRange(elmv[i], elmv[i + 1] - 1), zone);
5153 static void AddClassNegated(const int *elmv,
5155 ZoneList<CharacterRange>* ranges,
5158 DCHECK(elmv[elmc] == 0x10000);
5159 DCHECK(elmv[0] != 0x0000);
5160 DCHECK(elmv[elmc-1] != String::kMaxUtf16CodeUnit);
5162 for (int i = 0; i < elmc; i += 2) {
5163 DCHECK(last <= elmv[i] - 1);
5164 DCHECK(elmv[i] < elmv[i + 1]);
5165 ranges->Add(CharacterRange(last, elmv[i] - 1), zone);
5168 ranges->Add(CharacterRange(last, String::kMaxUtf16CodeUnit), zone);
5172 void CharacterRange::AddClassEscape(uc16 type,
5173 ZoneList<CharacterRange>* ranges,
5177 AddClass(kSpaceRanges, kSpaceRangeCount, ranges, zone);
5180 AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges, zone);
5183 AddClass(kWordRanges, kWordRangeCount, ranges, zone);
5186 AddClassNegated(kWordRanges, kWordRangeCount, ranges, zone);
5189 AddClass(kDigitRanges, kDigitRangeCount, ranges, zone);
5192 AddClassNegated(kDigitRanges, kDigitRangeCount, ranges, zone);
5195 AddClassNegated(kLineTerminatorRanges,
5196 kLineTerminatorRangeCount,
5200 // This is not a character range as defined by the spec but a
5201 // convenient shorthand for a character class that matches any
5204 ranges->Add(CharacterRange::Everything(), zone);
5206 // This is the set of characters matched by the $ and ^ symbols
5207 // in multiline mode.
5209 AddClass(kLineTerminatorRanges,
5210 kLineTerminatorRangeCount,
5220 Vector<const int> CharacterRange::GetWordBounds() {
5221 return Vector<const int>(kWordRanges, kWordRangeCount - 1);
5225 class CharacterRangeSplitter {
5227 CharacterRangeSplitter(ZoneList<CharacterRange>** included,
5228 ZoneList<CharacterRange>** excluded,
5230 : included_(included),
5231 excluded_(excluded),
5233 void Call(uc16 from, DispatchTable::Entry entry);
5235 static const int kInBase = 0;
5236 static const int kInOverlay = 1;
5239 ZoneList<CharacterRange>** included_;
5240 ZoneList<CharacterRange>** excluded_;
5245 void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) {
5246 if (!entry.out_set()->Get(kInBase)) return;
5247 ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay)
5250 if (*target == NULL) *target = new(zone_) ZoneList<CharacterRange>(2, zone_);
5251 (*target)->Add(CharacterRange(entry.from(), entry.to()), zone_);
5255 void CharacterRange::Split(ZoneList<CharacterRange>* base,
5256 Vector<const int> overlay,
5257 ZoneList<CharacterRange>** included,
5258 ZoneList<CharacterRange>** excluded,
5260 DCHECK_EQ(NULL, *included);
5261 DCHECK_EQ(NULL, *excluded);
5262 DispatchTable table(zone);
5263 for (int i = 0; i < base->length(); i++)
5264 table.AddRange(base->at(i), CharacterRangeSplitter::kInBase, zone);
5265 for (int i = 0; i < overlay.length(); i += 2) {
5266 table.AddRange(CharacterRange(overlay[i], overlay[i + 1] - 1),
5267 CharacterRangeSplitter::kInOverlay, zone);
5269 CharacterRangeSplitter callback(included, excluded, zone);
5270 table.ForEach(&callback);
5274 void CharacterRange::AddCaseEquivalents(ZoneList<CharacterRange>* ranges,
5277 Isolate* isolate = zone->isolate();
5278 uc16 bottom = from();
5280 if (is_ascii && !RangeContainsLatin1Equivalents(*this)) {
5281 if (bottom > String::kMaxOneByteCharCode) return;
5282 if (top > String::kMaxOneByteCharCode) top = String::kMaxOneByteCharCode;
5284 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
5285 if (top == bottom) {
5286 // If this is a singleton we just expand the one character.
5287 int length = isolate->jsregexp_uncanonicalize()->get(bottom, '\0', chars);
5288 for (int i = 0; i < length; i++) {
5289 uc32 chr = chars[i];
5290 if (chr != bottom) {
5291 ranges->Add(CharacterRange::Singleton(chars[i]), zone);
5295 // If this is a range we expand the characters block by block,
5296 // expanding contiguous subranges (blocks) one at a time.
5297 // The approach is as follows. For a given start character we
5298 // look up the remainder of the block that contains it (represented
5299 // by the end point), for instance we find 'z' if the character
5300 // is 'c'. A block is characterized by the property
5301 // that all characters uncanonicalize in the same way, except that
5302 // each entry in the result is incremented by the distance from the first
5303 // element. So a-z is a block because 'a' uncanonicalizes to ['a', 'A'] and
5304 // the k'th letter uncanonicalizes to ['a' + k, 'A' + k].
5305 // Once we've found the end point we look up its uncanonicalization
5306 // and produce a range for each element. For instance for [c-f]
5307 // we look up ['z', 'Z'] and produce [c-f] and [C-F]. We then only
5308 // add a range if it is not already contained in the input, so [c-f]
5309 // will be skipped but [C-F] will be added. If this range is not
5310 // completely contained in a block we do this for all the blocks
5311 // covered by the range (handling characters that is not in a block
5312 // as a "singleton block").
5313 unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth];
5315 while (pos <= top) {
5316 int length = isolate->jsregexp_canonrange()->get(pos, '\0', range);
5321 DCHECK_EQ(1, length);
5322 block_end = range[0];
5324 int end = (block_end > top) ? top : block_end;
5325 length = isolate->jsregexp_uncanonicalize()->get(block_end, '\0', range);
5326 for (int i = 0; i < length; i++) {
5328 uc16 range_from = c - (block_end - pos);
5329 uc16 range_to = c - (block_end - end);
5330 if (!(bottom <= range_from && range_to <= top)) {
5331 ranges->Add(CharacterRange(range_from, range_to), zone);
5340 bool CharacterRange::IsCanonical(ZoneList<CharacterRange>* ranges) {
5341 DCHECK_NOT_NULL(ranges);
5342 int n = ranges->length();
5343 if (n <= 1) return true;
5344 int max = ranges->at(0).to();
5345 for (int i = 1; i < n; i++) {
5346 CharacterRange next_range = ranges->at(i);
5347 if (next_range.from() <= max + 1) return false;
5348 max = next_range.to();
5354 ZoneList<CharacterRange>* CharacterSet::ranges(Zone* zone) {
5355 if (ranges_ == NULL) {
5356 ranges_ = new(zone) ZoneList<CharacterRange>(2, zone);
5357 CharacterRange::AddClassEscape(standard_set_type_, ranges_, zone);
5363 // Move a number of elements in a zonelist to another position
5364 // in the same list. Handles overlapping source and target areas.
5365 static void MoveRanges(ZoneList<CharacterRange>* list,
5369 // Ranges are potentially overlapping.
5371 for (int i = count - 1; i >= 0; i--) {
5372 list->at(to + i) = list->at(from + i);
5375 for (int i = 0; i < count; i++) {
5376 list->at(to + i) = list->at(from + i);
5382 static int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list,
5384 CharacterRange insert) {
5385 // Inserts a range into list[0..count[, which must be sorted
5386 // by from value and non-overlapping and non-adjacent, using at most
5387 // list[0..count] for the result. Returns the number of resulting
5388 // canonicalized ranges. Inserting a range may collapse existing ranges into
5389 // fewer ranges, so the return value can be anything in the range 1..count+1.
5390 uc16 from = insert.from();
5391 uc16 to = insert.to();
5393 int end_pos = count;
5394 for (int i = count - 1; i >= 0; i--) {
5395 CharacterRange current = list->at(i);
5396 if (current.from() > to + 1) {
5398 } else if (current.to() + 1 < from) {
5404 // Inserted range overlaps, or is adjacent to, ranges at positions
5405 // [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are
5406 // not affected by the insertion.
5407 // If start_pos == end_pos, the range must be inserted before start_pos.
5408 // if start_pos < end_pos, the entire range from start_pos to end_pos
5409 // must be merged with the insert range.
5411 if (start_pos == end_pos) {
5412 // Insert between existing ranges at position start_pos.
5413 if (start_pos < count) {
5414 MoveRanges(list, start_pos, start_pos + 1, count - start_pos);
5416 list->at(start_pos) = insert;
5419 if (start_pos + 1 == end_pos) {
5420 // Replace single existing range at position start_pos.
5421 CharacterRange to_replace = list->at(start_pos);
5422 int new_from = Min(to_replace.from(), from);
5423 int new_to = Max(to_replace.to(), to);
5424 list->at(start_pos) = CharacterRange(new_from, new_to);
5427 // Replace a number of existing ranges from start_pos to end_pos - 1.
5428 // Move the remaining ranges down.
5430 int new_from = Min(list->at(start_pos).from(), from);
5431 int new_to = Max(list->at(end_pos - 1).to(), to);
5432 if (end_pos < count) {
5433 MoveRanges(list, end_pos, start_pos + 1, count - end_pos);
5435 list->at(start_pos) = CharacterRange(new_from, new_to);
5436 return count - (end_pos - start_pos) + 1;
5440 void CharacterSet::Canonicalize() {
5441 // Special/default classes are always considered canonical. The result
5442 // of calling ranges() will be sorted.
5443 if (ranges_ == NULL) return;
5444 CharacterRange::Canonicalize(ranges_);
5448 void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) {
5449 if (character_ranges->length() <= 1) return;
5450 // Check whether ranges are already canonical (increasing, non-overlapping,
5452 int n = character_ranges->length();
5453 int max = character_ranges->at(0).to();
5456 CharacterRange current = character_ranges->at(i);
5457 if (current.from() <= max + 1) {
5463 // Canonical until the i'th range. If that's all of them, we are done.
5466 // The ranges at index i and forward are not canonicalized. Make them so by
5467 // doing the equivalent of insertion sort (inserting each into the previous
5469 // Notice that inserting a range can reduce the number of ranges in the
5470 // result due to combining of adjacent and overlapping ranges.
5471 int read = i; // Range to insert.
5472 int num_canonical = i; // Length of canonicalized part of list.
5474 num_canonical = InsertRangeInCanonicalList(character_ranges,
5476 character_ranges->at(read));
5479 character_ranges->Rewind(num_canonical);
5481 DCHECK(CharacterRange::IsCanonical(character_ranges));
5485 void CharacterRange::Negate(ZoneList<CharacterRange>* ranges,
5486 ZoneList<CharacterRange>* negated_ranges,
5488 DCHECK(CharacterRange::IsCanonical(ranges));
5489 DCHECK_EQ(0, negated_ranges->length());
5490 int range_count = ranges->length();
5493 if (range_count > 0 && ranges->at(0).from() == 0) {
5494 from = ranges->at(0).to();
5497 while (i < range_count) {
5498 CharacterRange range = ranges->at(i);
5499 negated_ranges->Add(CharacterRange(from + 1, range.from() - 1), zone);
5503 if (from < String::kMaxUtf16CodeUnit) {
5504 negated_ranges->Add(CharacterRange(from + 1, String::kMaxUtf16CodeUnit),
5510 // -------------------------------------------------------------------
5514 OutSet* OutSet::Extend(unsigned value, Zone* zone) {
5517 if (successors(zone) != NULL) {
5518 for (int i = 0; i < successors(zone)->length(); i++) {
5519 OutSet* successor = successors(zone)->at(i);
5520 if (successor->Get(value))
5524 successors_ = new(zone) ZoneList<OutSet*>(2, zone);
5526 OutSet* result = new(zone) OutSet(first_, remaining_);
5527 result->Set(value, zone);
5528 successors(zone)->Add(result, zone);
5533 void OutSet::Set(unsigned value, Zone *zone) {
5534 if (value < kFirstLimit) {
5535 first_ |= (1 << value);
5537 if (remaining_ == NULL)
5538 remaining_ = new(zone) ZoneList<unsigned>(1, zone);
5539 if (remaining_->is_empty() || !remaining_->Contains(value))
5540 remaining_->Add(value, zone);
5545 bool OutSet::Get(unsigned value) const {
5546 if (value < kFirstLimit) {
5547 return (first_ & (1 << value)) != 0;
5548 } else if (remaining_ == NULL) {
5551 return remaining_->Contains(value);
5556 const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
5559 void DispatchTable::AddRange(CharacterRange full_range, int value,
5561 CharacterRange current = full_range;
5562 if (tree()->is_empty()) {
5563 // If this is the first range we just insert into the table.
5564 ZoneSplayTree<Config>::Locator loc;
5565 DCHECK_RESULT(tree()->Insert(current.from(), &loc));
5566 loc.set_value(Entry(current.from(), current.to(),
5567 empty()->Extend(value, zone)));
5570 // First see if there is a range to the left of this one that
5572 ZoneSplayTree<Config>::Locator loc;
5573 if (tree()->FindGreatestLessThan(current.from(), &loc)) {
5574 Entry* entry = &loc.value();
5575 // If we've found a range that overlaps with this one, and it
5576 // starts strictly to the left of this one, we have to fix it
5577 // because the following code only handles ranges that start on
5578 // or after the start point of the range we're adding.
5579 if (entry->from() < current.from() && entry->to() >= current.from()) {
5580 // Snap the overlapping range in half around the start point of
5581 // the range we're adding.
5582 CharacterRange left(entry->from(), current.from() - 1);
5583 CharacterRange right(current.from(), entry->to());
5584 // The left part of the overlapping range doesn't overlap.
5585 // Truncate the whole entry to be just the left part.
5586 entry->set_to(left.to());
5587 // The right part is the one that overlaps. We add this part
5588 // to the map and let the next step deal with merging it with
5589 // the range we're adding.
5590 ZoneSplayTree<Config>::Locator loc;
5591 DCHECK_RESULT(tree()->Insert(right.from(), &loc));
5592 loc.set_value(Entry(right.from(),
5597 while (current.is_valid()) {
5598 if (tree()->FindLeastGreaterThan(current.from(), &loc) &&
5599 (loc.value().from() <= current.to()) &&
5600 (loc.value().to() >= current.from())) {
5601 Entry* entry = &loc.value();
5602 // We have overlap. If there is space between the start point of
5603 // the range we're adding and where the overlapping range starts
5604 // then we have to add a range covering just that space.
5605 if (current.from() < entry->from()) {
5606 ZoneSplayTree<Config>::Locator ins;
5607 DCHECK_RESULT(tree()->Insert(current.from(), &ins));
5608 ins.set_value(Entry(current.from(),
5610 empty()->Extend(value, zone)));
5611 current.set_from(entry->from());
5613 DCHECK_EQ(current.from(), entry->from());
5614 // If the overlapping range extends beyond the one we want to add
5615 // we have to snap the right part off and add it separately.
5616 if (entry->to() > current.to()) {
5617 ZoneSplayTree<Config>::Locator ins;
5618 DCHECK_RESULT(tree()->Insert(current.to() + 1, &ins));
5619 ins.set_value(Entry(current.to() + 1,
5622 entry->set_to(current.to());
5624 DCHECK(entry->to() <= current.to());
5625 // The overlapping range is now completely contained by the range
5626 // we're adding so we can just update it and move the start point
5627 // of the range we're adding just past it.
5628 entry->AddValue(value, zone);
5629 // Bail out if the last interval ended at 0xFFFF since otherwise
5630 // adding 1 will wrap around to 0.
5631 if (entry->to() == String::kMaxUtf16CodeUnit)
5633 DCHECK(entry->to() + 1 > current.from());
5634 current.set_from(entry->to() + 1);
5636 // There is no overlap so we can just add the range
5637 ZoneSplayTree<Config>::Locator ins;
5638 DCHECK_RESULT(tree()->Insert(current.from(), &ins));
5639 ins.set_value(Entry(current.from(),
5641 empty()->Extend(value, zone)));
5648 OutSet* DispatchTable::Get(uc16 value) {
5649 ZoneSplayTree<Config>::Locator loc;
5650 if (!tree()->FindGreatestLessThan(value, &loc))
5652 Entry* entry = &loc.value();
5653 if (value <= entry->to())
5654 return entry->out_set();
5660 // -------------------------------------------------------------------
5664 void Analysis::EnsureAnalyzed(RegExpNode* that) {
5665 StackLimitCheck check(that->zone()->isolate());
5666 if (check.HasOverflowed()) {
5667 fail("Stack overflow");
5670 if (that->info()->been_analyzed || that->info()->being_analyzed)
5672 that->info()->being_analyzed = true;
5674 that->info()->being_analyzed = false;
5675 that->info()->been_analyzed = true;
5679 void Analysis::VisitEnd(EndNode* that) {
5684 void TextNode::CalculateOffsets() {
5685 int element_count = elements()->length();
5686 // Set up the offsets of the elements relative to the start. This is a fixed
5687 // quantity since a TextNode can only contain fixed-width things.
5689 for (int i = 0; i < element_count; i++) {
5690 TextElement& elm = elements()->at(i);
5691 elm.set_cp_offset(cp_offset);
5692 cp_offset += elm.length();
5697 void Analysis::VisitText(TextNode* that) {
5699 that->MakeCaseIndependent(is_ascii_);
5701 EnsureAnalyzed(that->on_success());
5702 if (!has_failed()) {
5703 that->CalculateOffsets();
5708 void Analysis::VisitAction(ActionNode* that) {
5709 RegExpNode* target = that->on_success();
5710 EnsureAnalyzed(target);
5711 if (!has_failed()) {
5712 // If the next node is interested in what it follows then this node
5713 // has to be interested too so it can pass the information on.
5714 that->info()->AddFromFollowing(target->info());
5719 void Analysis::VisitChoice(ChoiceNode* that) {
5720 NodeInfo* info = that->info();
5721 for (int i = 0; i < that->alternatives()->length(); i++) {
5722 RegExpNode* node = that->alternatives()->at(i).node();
5723 EnsureAnalyzed(node);
5724 if (has_failed()) return;
5725 // Anything the following nodes need to know has to be known by
5726 // this node also, so it can pass it on.
5727 info->AddFromFollowing(node->info());
5732 void Analysis::VisitLoopChoice(LoopChoiceNode* that) {
5733 NodeInfo* info = that->info();
5734 for (int i = 0; i < that->alternatives()->length(); i++) {
5735 RegExpNode* node = that->alternatives()->at(i).node();
5736 if (node != that->loop_node()) {
5737 EnsureAnalyzed(node);
5738 if (has_failed()) return;
5739 info->AddFromFollowing(node->info());
5742 // Check the loop last since it may need the value of this node
5743 // to get a correct result.
5744 EnsureAnalyzed(that->loop_node());
5745 if (!has_failed()) {
5746 info->AddFromFollowing(that->loop_node()->info());
5751 void Analysis::VisitBackReference(BackReferenceNode* that) {
5752 EnsureAnalyzed(that->on_success());
5756 void Analysis::VisitAssertion(AssertionNode* that) {
5757 EnsureAnalyzed(that->on_success());
5761 void BackReferenceNode::FillInBMInfo(int offset,
5763 BoyerMooreLookahead* bm,
5764 bool not_at_start) {
5765 // Working out the set of characters that a backreference can match is too
5766 // hard, so we just say that any character can match.
5767 bm->SetRest(offset);
5768 SaveBMInfo(bm, not_at_start, offset);
5772 STATIC_ASSERT(BoyerMoorePositionInfo::kMapSize ==
5773 RegExpMacroAssembler::kTableSize);
5776 void ChoiceNode::FillInBMInfo(int offset,
5778 BoyerMooreLookahead* bm,
5779 bool not_at_start) {
5780 ZoneList<GuardedAlternative>* alts = alternatives();
5781 budget = (budget - 1) / alts->length();
5782 for (int i = 0; i < alts->length(); i++) {
5783 GuardedAlternative& alt = alts->at(i);
5784 if (alt.guards() != NULL && alt.guards()->length() != 0) {
5785 bm->SetRest(offset); // Give up trying to fill in info.
5786 SaveBMInfo(bm, not_at_start, offset);
5789 alt.node()->FillInBMInfo(offset, budget, bm, not_at_start);
5791 SaveBMInfo(bm, not_at_start, offset);
5795 void TextNode::FillInBMInfo(int initial_offset,
5797 BoyerMooreLookahead* bm,
5798 bool not_at_start) {
5799 if (initial_offset >= bm->length()) return;
5800 int offset = initial_offset;
5801 int max_char = bm->max_char();
5802 for (int i = 0; i < elements()->length(); i++) {
5803 if (offset >= bm->length()) {
5804 if (initial_offset == 0) set_bm_info(not_at_start, bm);
5807 TextElement text = elements()->at(i);
5808 if (text.text_type() == TextElement::ATOM) {
5809 RegExpAtom* atom = text.atom();
5810 for (int j = 0; j < atom->length(); j++, offset++) {
5811 if (offset >= bm->length()) {
5812 if (initial_offset == 0) set_bm_info(not_at_start, bm);
5815 uc16 character = atom->data()[j];
5816 if (bm->compiler()->ignore_case()) {
5817 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
5818 int length = GetCaseIndependentLetters(
5821 bm->max_char() == String::kMaxOneByteCharCode,
5823 for (int j = 0; j < length; j++) {
5824 bm->Set(offset, chars[j]);
5827 if (character <= max_char) bm->Set(offset, character);
5831 DCHECK_EQ(TextElement::CHAR_CLASS, text.text_type());
5832 RegExpCharacterClass* char_class = text.char_class();
5833 ZoneList<CharacterRange>* ranges = char_class->ranges(zone());
5834 if (char_class->is_negated()) {
5837 for (int k = 0; k < ranges->length(); k++) {
5838 CharacterRange& range = ranges->at(k);
5839 if (range.from() > max_char) continue;
5840 int to = Min(max_char, static_cast<int>(range.to()));
5841 bm->SetInterval(offset, Interval(range.from(), to));
5847 if (offset >= bm->length()) {
5848 if (initial_offset == 0) set_bm_info(not_at_start, bm);
5851 on_success()->FillInBMInfo(offset,
5854 true); // Not at start after a text node.
5855 if (initial_offset == 0) set_bm_info(not_at_start, bm);
5859 // -------------------------------------------------------------------
5860 // Dispatch table construction
5863 void DispatchTableConstructor::VisitEnd(EndNode* that) {
5864 AddRange(CharacterRange::Everything());
5868 void DispatchTableConstructor::BuildTable(ChoiceNode* node) {
5869 node->set_being_calculated(true);
5870 ZoneList<GuardedAlternative>* alternatives = node->alternatives();
5871 for (int i = 0; i < alternatives->length(); i++) {
5872 set_choice_index(i);
5873 alternatives->at(i).node()->Accept(this);
5875 node->set_being_calculated(false);
5879 class AddDispatchRange {
5881 explicit AddDispatchRange(DispatchTableConstructor* constructor)
5882 : constructor_(constructor) { }
5883 void Call(uc32 from, DispatchTable::Entry entry);
5885 DispatchTableConstructor* constructor_;
5889 void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
5890 CharacterRange range(from, entry.to());
5891 constructor_->AddRange(range);
5895 void DispatchTableConstructor::VisitChoice(ChoiceNode* node) {
5896 if (node->being_calculated())
5898 DispatchTable* table = node->GetTable(ignore_case_);
5899 AddDispatchRange adder(this);
5900 table->ForEach(&adder);
5904 void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) {
5905 // TODO(160): Find the node that we refer back to and propagate its start
5906 // set back to here. For now we just accept anything.
5907 AddRange(CharacterRange::Everything());
5911 void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
5912 RegExpNode* target = that->on_success();
5913 target->Accept(this);
5917 static int CompareRangeByFrom(const CharacterRange* a,
5918 const CharacterRange* b) {
5919 return Compare<uc16>(a->from(), b->from());
5923 void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) {
5924 ranges->Sort(CompareRangeByFrom);
5926 for (int i = 0; i < ranges->length(); i++) {
5927 CharacterRange range = ranges->at(i);
5928 if (last < range.from())
5929 AddRange(CharacterRange(last, range.from() - 1));
5930 if (range.to() >= last) {
5931 if (range.to() == String::kMaxUtf16CodeUnit) {
5934 last = range.to() + 1;
5938 AddRange(CharacterRange(last, String::kMaxUtf16CodeUnit));
5942 void DispatchTableConstructor::VisitText(TextNode* that) {
5943 TextElement elm = that->elements()->at(0);
5944 switch (elm.text_type()) {
5945 case TextElement::ATOM: {
5946 uc16 c = elm.atom()->data()[0];
5947 AddRange(CharacterRange(c, c));
5950 case TextElement::CHAR_CLASS: {
5951 RegExpCharacterClass* tree = elm.char_class();
5952 ZoneList<CharacterRange>* ranges = tree->ranges(that->zone());
5953 if (tree->is_negated()) {
5956 for (int i = 0; i < ranges->length(); i++)
5957 AddRange(ranges->at(i));
5968 void DispatchTableConstructor::VisitAction(ActionNode* that) {
5969 RegExpNode* target = that->on_success();
5970 target->Accept(this);
5974 RegExpEngine::CompilationResult RegExpEngine::Compile(
5975 RegExpCompileData* data,
5979 Handle<String> pattern,
5980 Handle<String> sample_subject,
5983 if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) {
5984 return IrregexpRegExpTooBig(zone->isolate());
5986 RegExpCompiler compiler(data->capture_count, ignore_case, is_ascii, zone);
5988 // Sample some characters from the middle of the string.
5989 static const int kSampleSize = 128;
5991 sample_subject = String::Flatten(sample_subject);
5992 int chars_sampled = 0;
5993 int half_way = (sample_subject->length() - kSampleSize) / 2;
5994 for (int i = Max(0, half_way);
5995 i < sample_subject->length() && chars_sampled < kSampleSize;
5996 i++, chars_sampled++) {
5997 compiler.frequency_collator()->CountCharacter(sample_subject->Get(i));
6000 // Wrap the body of the regexp in capture #0.
6001 RegExpNode* captured_body = RegExpCapture::ToNode(data->tree,
6005 RegExpNode* node = captured_body;
6006 bool is_end_anchored = data->tree->IsAnchoredAtEnd();
6007 bool is_start_anchored = data->tree->IsAnchoredAtStart();
6008 int max_length = data->tree->max_match();
6009 if (!is_start_anchored) {
6010 // Add a .*? at the beginning, outside the body capture, unless
6011 // this expression is anchored at the beginning.
6012 RegExpNode* loop_node =
6013 RegExpQuantifier::ToNode(0,
6014 RegExpTree::kInfinity,
6016 new(zone) RegExpCharacterClass('*'),
6019 data->contains_anchor);
6021 if (data->contains_anchor) {
6022 // Unroll loop once, to take care of the case that might start
6023 // at the start of input.
6024 ChoiceNode* first_step_node = new(zone) ChoiceNode(2, zone);
6025 first_step_node->AddAlternative(GuardedAlternative(captured_body));
6026 first_step_node->AddAlternative(GuardedAlternative(
6027 new(zone) TextNode(new(zone) RegExpCharacterClass('*'), loop_node)));
6028 node = first_step_node;
6034 node = node->FilterASCII(RegExpCompiler::kMaxRecursion, ignore_case);
6035 // Do it again to propagate the new nodes to places where they were not
6036 // put because they had not been calculated yet.
6038 node = node->FilterASCII(RegExpCompiler::kMaxRecursion, ignore_case);
6042 if (node == NULL) node = new(zone) EndNode(EndNode::BACKTRACK, zone);
6044 Analysis analysis(ignore_case, is_ascii);
6045 analysis.EnsureAnalyzed(node);
6046 if (analysis.has_failed()) {
6047 const char* error_message = analysis.error_message();
6048 return CompilationResult(zone->isolate(), error_message);
6051 // Create the correct assembler for the architecture.
6052 #ifndef V8_INTERPRETED_REGEXP
6053 // Native regexp implementation.
6055 NativeRegExpMacroAssembler::Mode mode =
6056 is_ascii ? NativeRegExpMacroAssembler::ASCII
6057 : NativeRegExpMacroAssembler::UC16;
6059 #if V8_TARGET_ARCH_IA32
6060 RegExpMacroAssemblerIA32 macro_assembler(mode, (data->capture_count + 1) * 2,
6062 #elif V8_TARGET_ARCH_X64
6063 RegExpMacroAssemblerX64 macro_assembler(mode, (data->capture_count + 1) * 2,
6065 #elif V8_TARGET_ARCH_ARM
6066 RegExpMacroAssemblerARM macro_assembler(mode, (data->capture_count + 1) * 2,
6068 #elif V8_TARGET_ARCH_ARM64
6069 RegExpMacroAssemblerARM64 macro_assembler(mode, (data->capture_count + 1) * 2,
6071 #elif V8_TARGET_ARCH_MIPS
6072 RegExpMacroAssemblerMIPS macro_assembler(mode, (data->capture_count + 1) * 2,
6074 #elif V8_TARGET_ARCH_MIPS64
6075 RegExpMacroAssemblerMIPS macro_assembler(mode, (data->capture_count + 1) * 2,
6077 #elif V8_TARGET_ARCH_X87
6078 RegExpMacroAssemblerX87 macro_assembler(mode, (data->capture_count + 1) * 2,
6081 #error "Unsupported architecture"
6084 #else // V8_INTERPRETED_REGEXP
6085 // Interpreted regexp implementation.
6086 EmbeddedVector<byte, 1024> codes;
6087 RegExpMacroAssemblerIrregexp macro_assembler(codes, zone);
6088 #endif // V8_INTERPRETED_REGEXP
6090 // Inserted here, instead of in Assembler, because it depends on information
6091 // in the AST that isn't replicated in the Node structure.
6092 static const int kMaxBacksearchLimit = 1024;
6093 if (is_end_anchored &&
6094 !is_start_anchored &&
6095 max_length < kMaxBacksearchLimit) {
6096 macro_assembler.SetCurrentPositionFromEnd(max_length);
6100 macro_assembler.set_global_mode(
6101 (data->tree->min_match() > 0)
6102 ? RegExpMacroAssembler::GLOBAL_NO_ZERO_LENGTH_CHECK
6103 : RegExpMacroAssembler::GLOBAL);
6106 return compiler.Assemble(¯o_assembler,
6108 data->capture_count,
6113 }} // namespace v8::internal