1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
8 #include "src/base/platform/platform.h"
9 #include "src/compilation-cache.h"
10 #include "src/compiler.h"
11 #include "src/execution.h"
12 #include "src/factory.h"
13 #include "src/jsregexp-inl.h"
14 #include "src/jsregexp.h"
15 #include "src/ostreams.h"
16 #include "src/parser.h"
17 #include "src/regexp-macro-assembler.h"
18 #include "src/regexp-macro-assembler-irregexp.h"
19 #include "src/regexp-macro-assembler-tracer.h"
20 #include "src/regexp-stack.h"
21 #include "src/runtime/runtime.h"
22 #include "src/string-search.h"
23 #include "src/unicode-decoder.h"
25 #ifndef V8_INTERPRETED_REGEXP
26 #if V8_TARGET_ARCH_IA32
27 #include "src/ia32/regexp-macro-assembler-ia32.h" // NOLINT
28 #elif V8_TARGET_ARCH_X64
29 #include "src/x64/regexp-macro-assembler-x64.h" // NOLINT
30 #elif V8_TARGET_ARCH_ARM64
31 #include "src/arm64/regexp-macro-assembler-arm64.h" // NOLINT
32 #elif V8_TARGET_ARCH_ARM
33 #include "src/arm/regexp-macro-assembler-arm.h" // NOLINT
34 #elif V8_TARGET_ARCH_PPC
35 #include "src/ppc/regexp-macro-assembler-ppc.h" // NOLINT
36 #elif V8_TARGET_ARCH_MIPS
37 #include "src/mips/regexp-macro-assembler-mips.h" // NOLINT
38 #elif V8_TARGET_ARCH_MIPS64
39 #include "src/mips64/regexp-macro-assembler-mips64.h" // NOLINT
40 #elif V8_TARGET_ARCH_X87
41 #include "src/x87/regexp-macro-assembler-x87.h" // NOLINT
43 #error Unsupported target architecture.
47 #include "src/interpreter-irregexp.h"
53 MaybeHandle<Object> RegExpImpl::CreateRegExpLiteral(
54 Handle<JSFunction> constructor,
55 Handle<String> pattern,
56 Handle<String> flags) {
57 // Call the construct code with 2 arguments.
58 Handle<Object> argv[] = { pattern, flags };
59 return Execution::New(constructor, arraysize(argv), argv);
64 static inline MaybeHandle<Object> ThrowRegExpException(
66 Handle<String> pattern,
67 Handle<String> error_text,
68 const char* message) {
69 Isolate* isolate = re->GetIsolate();
70 Factory* factory = isolate->factory();
71 Handle<FixedArray> elements = factory->NewFixedArray(2);
72 elements->set(0, *pattern);
73 elements->set(1, *error_text);
74 Handle<JSArray> array = factory->NewJSArrayWithElements(elements);
75 Handle<Object> regexp_err;
76 THROW_NEW_ERROR(isolate, NewSyntaxError(message, array), Object);
80 ContainedInLattice AddRange(ContainedInLattice containment,
84 DCHECK((ranges_length & 1) == 1);
85 DCHECK(ranges[ranges_length - 1] == String::kMaxUtf16CodeUnit + 1);
86 if (containment == kLatticeUnknown) return containment;
89 for (int i = 0; i < ranges_length; inside = !inside, last = ranges[i], i++) {
90 // Consider the range from last to ranges[i].
91 // We haven't got to the new range yet.
92 if (ranges[i] <= new_range.from()) continue;
93 // New range is wholly inside last-ranges[i]. Note that new_range.to() is
94 // inclusive, but the values in ranges are not.
95 if (last <= new_range.from() && new_range.to() < ranges[i]) {
96 return Combine(containment, inside ? kLatticeIn : kLatticeOut);
98 return kLatticeUnknown;
104 // More makes code generation slower, less makes V8 benchmark score lower.
105 const int kMaxLookaheadForBoyerMoore = 8;
106 // In a 3-character pattern you can maximally step forwards 3 characters
107 // at a time, which is not always enough to pay for the extra logic.
108 const int kPatternTooShortForBoyerMoore = 2;
111 // Identifies the sort of regexps where the regexp engine is faster
112 // than the code used for atom matches.
113 static bool HasFewDifferentCharacters(Handle<String> pattern) {
114 int length = Min(kMaxLookaheadForBoyerMoore, pattern->length());
115 if (length <= kPatternTooShortForBoyerMoore) return false;
116 const int kMod = 128;
117 bool character_found[kMod];
119 memset(&character_found[0], 0, sizeof(character_found));
120 for (int i = 0; i < length; i++) {
121 int ch = (pattern->Get(i) & (kMod - 1));
122 if (!character_found[ch]) {
123 character_found[ch] = true;
125 // We declare a regexp low-alphabet if it has at least 3 times as many
126 // characters as it has different characters.
127 if (different * 3 > length) return false;
134 // Generic RegExp methods. Dispatches to implementation specific methods.
137 MaybeHandle<Object> RegExpImpl::Compile(Handle<JSRegExp> re,
138 Handle<String> pattern,
139 JSRegExp::Flags flags) {
140 Isolate* isolate = re->GetIsolate();
142 CompilationCache* compilation_cache = isolate->compilation_cache();
143 MaybeHandle<FixedArray> maybe_cached =
144 compilation_cache->LookupRegExp(pattern, flags);
145 Handle<FixedArray> cached;
146 bool in_cache = maybe_cached.ToHandle(&cached);
147 LOG(isolate, RegExpCompileEvent(re, in_cache));
149 Handle<Object> result;
151 re->set_data(*cached);
154 pattern = String::Flatten(pattern);
155 PostponeInterruptsScope postpone(isolate);
156 RegExpCompileData parse_result;
157 FlatStringReader reader(isolate, pattern);
158 if (!RegExpParser::ParseRegExp(re->GetIsolate(), &zone, &reader,
159 flags.is_multiline(), flags.is_unicode(),
161 // Throw an exception if we fail to parse the pattern.
162 return ThrowRegExpException(re,
168 bool has_been_compiled = false;
170 if (parse_result.simple &&
171 !flags.is_ignore_case() &&
172 !flags.is_sticky() &&
173 !HasFewDifferentCharacters(pattern)) {
174 // Parse-tree is a single atom that is equal to the pattern.
175 AtomCompile(re, pattern, flags, pattern);
176 has_been_compiled = true;
177 } else if (parse_result.tree->IsAtom() &&
178 !flags.is_ignore_case() &&
179 !flags.is_sticky() &&
180 parse_result.capture_count == 0) {
181 RegExpAtom* atom = parse_result.tree->AsAtom();
182 Vector<const uc16> atom_pattern = atom->data();
183 Handle<String> atom_string;
184 ASSIGN_RETURN_ON_EXCEPTION(
185 isolate, atom_string,
186 isolate->factory()->NewStringFromTwoByte(atom_pattern),
188 if (!HasFewDifferentCharacters(atom_string)) {
189 AtomCompile(re, pattern, flags, atom_string);
190 has_been_compiled = true;
193 if (!has_been_compiled) {
194 IrregexpInitialize(re, pattern, flags, parse_result.capture_count);
196 DCHECK(re->data()->IsFixedArray());
197 // Compilation succeeded so the data is set on the regexp
198 // and we can store it in the cache.
199 Handle<FixedArray> data(FixedArray::cast(re->data()));
200 compilation_cache->PutRegExp(pattern, flags, data);
206 MaybeHandle<Object> RegExpImpl::Exec(Handle<JSRegExp> regexp,
207 Handle<String> subject,
209 Handle<JSArray> last_match_info) {
210 switch (regexp->TypeTag()) {
212 return AtomExec(regexp, subject, index, last_match_info);
213 case JSRegExp::IRREGEXP: {
214 return IrregexpExec(regexp, subject, index, last_match_info);
218 return MaybeHandle<Object>();
223 // RegExp Atom implementation: Simple string search using indexOf.
226 void RegExpImpl::AtomCompile(Handle<JSRegExp> re,
227 Handle<String> pattern,
228 JSRegExp::Flags flags,
229 Handle<String> match_pattern) {
230 re->GetIsolate()->factory()->SetRegExpAtomData(re,
238 static void SetAtomLastCapture(FixedArray* array,
242 SealHandleScope shs(array->GetIsolate());
243 RegExpImpl::SetLastCaptureCount(array, 2);
244 RegExpImpl::SetLastSubject(array, subject);
245 RegExpImpl::SetLastInput(array, subject);
246 RegExpImpl::SetCapture(array, 0, from);
247 RegExpImpl::SetCapture(array, 1, to);
251 int RegExpImpl::AtomExecRaw(Handle<JSRegExp> regexp,
252 Handle<String> subject,
256 Isolate* isolate = regexp->GetIsolate();
259 DCHECK(index <= subject->length());
261 subject = String::Flatten(subject);
262 DisallowHeapAllocation no_gc; // ensure vectors stay valid
264 String* needle = String::cast(regexp->DataAt(JSRegExp::kAtomPatternIndex));
265 int needle_len = needle->length();
266 DCHECK(needle->IsFlat());
267 DCHECK_LT(0, needle_len);
269 if (index + needle_len > subject->length()) {
270 return RegExpImpl::RE_FAILURE;
273 for (int i = 0; i < output_size; i += 2) {
274 String::FlatContent needle_content = needle->GetFlatContent();
275 String::FlatContent subject_content = subject->GetFlatContent();
276 DCHECK(needle_content.IsFlat());
277 DCHECK(subject_content.IsFlat());
278 // dispatch on type of strings
280 (needle_content.IsOneByte()
281 ? (subject_content.IsOneByte()
282 ? SearchString(isolate, subject_content.ToOneByteVector(),
283 needle_content.ToOneByteVector(), index)
284 : SearchString(isolate, subject_content.ToUC16Vector(),
285 needle_content.ToOneByteVector(), index))
286 : (subject_content.IsOneByte()
287 ? SearchString(isolate, subject_content.ToOneByteVector(),
288 needle_content.ToUC16Vector(), index)
289 : SearchString(isolate, subject_content.ToUC16Vector(),
290 needle_content.ToUC16Vector(), index)));
292 return i / 2; // Return number of matches.
295 output[i+1] = index + needle_len;
299 return output_size / 2;
303 Handle<Object> RegExpImpl::AtomExec(Handle<JSRegExp> re,
304 Handle<String> subject,
306 Handle<JSArray> last_match_info) {
307 Isolate* isolate = re->GetIsolate();
309 static const int kNumRegisters = 2;
310 STATIC_ASSERT(kNumRegisters <= Isolate::kJSRegexpStaticOffsetsVectorSize);
311 int32_t* output_registers = isolate->jsregexp_static_offsets_vector();
313 int res = AtomExecRaw(re, subject, index, output_registers, kNumRegisters);
315 if (res == RegExpImpl::RE_FAILURE) return isolate->factory()->null_value();
317 DCHECK_EQ(res, RegExpImpl::RE_SUCCESS);
318 SealHandleScope shs(isolate);
319 FixedArray* array = FixedArray::cast(last_match_info->elements());
320 SetAtomLastCapture(array, *subject, output_registers[0], output_registers[1]);
321 return last_match_info;
325 // Irregexp implementation.
327 // Ensures that the regexp object contains a compiled version of the
328 // source for either one-byte or two-byte subject strings.
329 // If the compiled version doesn't already exist, it is compiled
330 // from the source pattern.
331 // If compilation fails, an exception is thrown and this function
333 bool RegExpImpl::EnsureCompiledIrregexp(Handle<JSRegExp> re,
334 Handle<String> sample_subject,
336 Object* compiled_code = re->DataAt(JSRegExp::code_index(is_one_byte));
337 #ifdef V8_INTERPRETED_REGEXP
338 if (compiled_code->IsByteArray()) return true;
339 #else // V8_INTERPRETED_REGEXP (RegExp native code)
340 if (compiled_code->IsCode()) return true;
342 // We could potentially have marked this as flushable, but have kept
343 // a saved version if we did not flush it yet.
344 Object* saved_code = re->DataAt(JSRegExp::saved_code_index(is_one_byte));
345 if (saved_code->IsCode()) {
346 // Reinstate the code in the original place.
347 re->SetDataAt(JSRegExp::code_index(is_one_byte), saved_code);
348 DCHECK(compiled_code->IsSmi());
351 return CompileIrregexp(re, sample_subject, is_one_byte);
355 static void CreateRegExpErrorObjectAndThrow(Handle<JSRegExp> re,
356 Handle<String> error_message,
358 Factory* factory = isolate->factory();
359 Handle<FixedArray> elements = factory->NewFixedArray(2);
360 elements->set(0, re->Pattern());
361 elements->set(1, *error_message);
362 Handle<JSArray> array = factory->NewJSArrayWithElements(elements);
363 Handle<Object> error = factory->NewSyntaxError("malformed_regexp", array);
364 isolate->Throw(*error);
368 bool RegExpImpl::CompileIrregexp(Handle<JSRegExp> re,
369 Handle<String> sample_subject,
371 // Compile the RegExp.
372 Isolate* isolate = re->GetIsolate();
374 PostponeInterruptsScope postpone(isolate);
375 // If we had a compilation error the last time this is saved at the
377 Object* entry = re->DataAt(JSRegExp::code_index(is_one_byte));
378 // When arriving here entry can only be a smi, either representing an
379 // uncompiled regexp, a previous compilation error, or code that has
381 DCHECK(entry->IsSmi());
382 int entry_value = Smi::cast(entry)->value();
383 DCHECK(entry_value == JSRegExp::kUninitializedValue ||
384 entry_value == JSRegExp::kCompilationErrorValue ||
385 (entry_value < JSRegExp::kCodeAgeMask && entry_value >= 0));
387 if (entry_value == JSRegExp::kCompilationErrorValue) {
388 // A previous compilation failed and threw an error which we store in
389 // the saved code index (we store the error message, not the actual
390 // error). Recreate the error object and throw it.
391 Object* error_string = re->DataAt(JSRegExp::saved_code_index(is_one_byte));
392 DCHECK(error_string->IsString());
393 Handle<String> error_message(String::cast(error_string));
394 CreateRegExpErrorObjectAndThrow(re, error_message, isolate);
398 JSRegExp::Flags flags = re->GetFlags();
400 Handle<String> pattern(re->Pattern());
401 pattern = String::Flatten(pattern);
402 RegExpCompileData compile_data;
403 FlatStringReader reader(isolate, pattern);
404 if (!RegExpParser::ParseRegExp(isolate, &zone, &reader, flags.is_multiline(),
405 flags.is_unicode(), &compile_data)) {
406 // Throw an exception if we fail to parse the pattern.
407 // THIS SHOULD NOT HAPPEN. We already pre-parsed it successfully once.
408 USE(ThrowRegExpException(re,
411 "malformed_regexp"));
414 RegExpEngine::CompilationResult result = RegExpEngine::Compile(
415 isolate, &zone, &compile_data, flags.is_ignore_case(), flags.is_global(),
416 flags.is_multiline(), flags.is_sticky(), pattern, sample_subject,
418 if (result.error_message != NULL) {
419 // Unable to compile regexp.
420 Handle<String> error_message = isolate->factory()->NewStringFromUtf8(
421 CStrVector(result.error_message)).ToHandleChecked();
422 CreateRegExpErrorObjectAndThrow(re, error_message, isolate);
426 Handle<FixedArray> data = Handle<FixedArray>(FixedArray::cast(re->data()));
427 data->set(JSRegExp::code_index(is_one_byte), result.code);
428 int register_max = IrregexpMaxRegisterCount(*data);
429 if (result.num_registers > register_max) {
430 SetIrregexpMaxRegisterCount(*data, result.num_registers);
437 int RegExpImpl::IrregexpMaxRegisterCount(FixedArray* re) {
439 re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
443 void RegExpImpl::SetIrregexpMaxRegisterCount(FixedArray* re, int value) {
444 re->set(JSRegExp::kIrregexpMaxRegisterCountIndex, Smi::FromInt(value));
448 int RegExpImpl::IrregexpNumberOfCaptures(FixedArray* re) {
449 return Smi::cast(re->get(JSRegExp::kIrregexpCaptureCountIndex))->value();
453 int RegExpImpl::IrregexpNumberOfRegisters(FixedArray* re) {
454 return Smi::cast(re->get(JSRegExp::kIrregexpMaxRegisterCountIndex))->value();
458 ByteArray* RegExpImpl::IrregexpByteCode(FixedArray* re, bool is_one_byte) {
459 return ByteArray::cast(re->get(JSRegExp::code_index(is_one_byte)));
463 Code* RegExpImpl::IrregexpNativeCode(FixedArray* re, bool is_one_byte) {
464 return Code::cast(re->get(JSRegExp::code_index(is_one_byte)));
468 void RegExpImpl::IrregexpInitialize(Handle<JSRegExp> re,
469 Handle<String> pattern,
470 JSRegExp::Flags flags,
472 // Initialize compiled code entries to null.
473 re->GetIsolate()->factory()->SetRegExpIrregexpData(re,
481 int RegExpImpl::IrregexpPrepare(Handle<JSRegExp> regexp,
482 Handle<String> subject) {
483 subject = String::Flatten(subject);
485 // Check representation of the underlying storage.
486 bool is_one_byte = subject->IsOneByteRepresentationUnderneath();
487 if (!EnsureCompiledIrregexp(regexp, subject, is_one_byte)) return -1;
489 #ifdef V8_INTERPRETED_REGEXP
490 // Byte-code regexp needs space allocated for all its registers.
491 // The result captures are copied to the start of the registers array
492 // if the match succeeds. This way those registers are not clobbered
493 // when we set the last match info from last successful match.
494 return IrregexpNumberOfRegisters(FixedArray::cast(regexp->data())) +
495 (IrregexpNumberOfCaptures(FixedArray::cast(regexp->data())) + 1) * 2;
496 #else // V8_INTERPRETED_REGEXP
497 // Native regexp only needs room to output captures. Registers are handled
499 return (IrregexpNumberOfCaptures(FixedArray::cast(regexp->data())) + 1) * 2;
500 #endif // V8_INTERPRETED_REGEXP
504 int RegExpImpl::IrregexpExecRaw(Handle<JSRegExp> regexp,
505 Handle<String> subject,
509 Isolate* isolate = regexp->GetIsolate();
511 Handle<FixedArray> irregexp(FixedArray::cast(regexp->data()), isolate);
514 DCHECK(index <= subject->length());
515 DCHECK(subject->IsFlat());
517 bool is_one_byte = subject->IsOneByteRepresentationUnderneath();
519 #ifndef V8_INTERPRETED_REGEXP
520 DCHECK(output_size >= (IrregexpNumberOfCaptures(*irregexp) + 1) * 2);
522 EnsureCompiledIrregexp(regexp, subject, is_one_byte);
523 Handle<Code> code(IrregexpNativeCode(*irregexp, is_one_byte), isolate);
524 // The stack is used to allocate registers for the compiled regexp code.
525 // This means that in case of failure, the output registers array is left
526 // untouched and contains the capture results from the previous successful
527 // match. We can use that to set the last match info lazily.
528 NativeRegExpMacroAssembler::Result res =
529 NativeRegExpMacroAssembler::Match(code,
535 if (res != NativeRegExpMacroAssembler::RETRY) {
536 DCHECK(res != NativeRegExpMacroAssembler::EXCEPTION ||
537 isolate->has_pending_exception());
539 static_cast<int>(NativeRegExpMacroAssembler::SUCCESS) == RE_SUCCESS);
541 static_cast<int>(NativeRegExpMacroAssembler::FAILURE) == RE_FAILURE);
542 STATIC_ASSERT(static_cast<int>(NativeRegExpMacroAssembler::EXCEPTION)
544 return static_cast<IrregexpResult>(res);
546 // If result is RETRY, the string has changed representation, and we
547 // must restart from scratch.
548 // In this case, it means we must make sure we are prepared to handle
549 // the, potentially, different subject (the string can switch between
550 // being internal and external, and even between being Latin1 and UC16,
551 // but the characters are always the same).
552 IrregexpPrepare(regexp, subject);
553 is_one_byte = subject->IsOneByteRepresentationUnderneath();
557 #else // V8_INTERPRETED_REGEXP
559 DCHECK(output_size >= IrregexpNumberOfRegisters(*irregexp));
560 // We must have done EnsureCompiledIrregexp, so we can get the number of
562 int number_of_capture_registers =
563 (IrregexpNumberOfCaptures(*irregexp) + 1) * 2;
564 int32_t* raw_output = &output[number_of_capture_registers];
565 // We do not touch the actual capture result registers until we know there
566 // has been a match so that we can use those capture results to set the
568 for (int i = number_of_capture_registers - 1; i >= 0; i--) {
571 Handle<ByteArray> byte_codes(IrregexpByteCode(*irregexp, is_one_byte),
574 IrregexpResult result = IrregexpInterpreter::Match(isolate,
579 if (result == RE_SUCCESS) {
580 // Copy capture results to the start of the registers array.
581 MemCopy(output, raw_output, number_of_capture_registers * sizeof(int32_t));
583 if (result == RE_EXCEPTION) {
584 DCHECK(!isolate->has_pending_exception());
585 isolate->StackOverflow();
588 #endif // V8_INTERPRETED_REGEXP
592 MaybeHandle<Object> RegExpImpl::IrregexpExec(Handle<JSRegExp> regexp,
593 Handle<String> subject,
595 Handle<JSArray> last_match_info) {
596 Isolate* isolate = regexp->GetIsolate();
597 DCHECK_EQ(regexp->TypeTag(), JSRegExp::IRREGEXP);
599 // Prepare space for the return values.
600 #if defined(V8_INTERPRETED_REGEXP) && defined(DEBUG)
601 if (FLAG_trace_regexp_bytecodes) {
602 String* pattern = regexp->Pattern();
603 PrintF("\n\nRegexp match: /%s/\n\n", pattern->ToCString().get());
604 PrintF("\n\nSubject string: '%s'\n\n", subject->ToCString().get());
607 int required_registers = RegExpImpl::IrregexpPrepare(regexp, subject);
608 if (required_registers < 0) {
609 // Compiling failed with an exception.
610 DCHECK(isolate->has_pending_exception());
611 return MaybeHandle<Object>();
614 int32_t* output_registers = NULL;
615 if (required_registers > Isolate::kJSRegexpStaticOffsetsVectorSize) {
616 output_registers = NewArray<int32_t>(required_registers);
618 SmartArrayPointer<int32_t> auto_release(output_registers);
619 if (output_registers == NULL) {
620 output_registers = isolate->jsregexp_static_offsets_vector();
623 int res = RegExpImpl::IrregexpExecRaw(
624 regexp, subject, previous_index, output_registers, required_registers);
625 if (res == RE_SUCCESS) {
627 IrregexpNumberOfCaptures(FixedArray::cast(regexp->data()));
628 return SetLastMatchInfo(
629 last_match_info, subject, capture_count, output_registers);
631 if (res == RE_EXCEPTION) {
632 DCHECK(isolate->has_pending_exception());
633 return MaybeHandle<Object>();
635 DCHECK(res == RE_FAILURE);
636 return isolate->factory()->null_value();
640 Handle<JSArray> RegExpImpl::SetLastMatchInfo(Handle<JSArray> last_match_info,
641 Handle<String> subject,
644 DCHECK(last_match_info->HasFastObjectElements());
645 int capture_register_count = (capture_count + 1) * 2;
646 JSArray::EnsureSize(last_match_info,
647 capture_register_count + kLastMatchOverhead);
648 DisallowHeapAllocation no_allocation;
649 FixedArray* array = FixedArray::cast(last_match_info->elements());
651 for (int i = 0; i < capture_register_count; i += 2) {
652 SetCapture(array, i, match[i]);
653 SetCapture(array, i + 1, match[i + 1]);
656 SetLastCaptureCount(array, capture_register_count);
657 SetLastSubject(array, *subject);
658 SetLastInput(array, *subject);
659 return last_match_info;
663 RegExpImpl::GlobalCache::GlobalCache(Handle<JSRegExp> regexp,
664 Handle<String> subject,
667 : register_array_(NULL),
668 register_array_size_(0),
671 #ifdef V8_INTERPRETED_REGEXP
672 bool interpreted = true;
674 bool interpreted = false;
675 #endif // V8_INTERPRETED_REGEXP
677 if (regexp_->TypeTag() == JSRegExp::ATOM) {
678 static const int kAtomRegistersPerMatch = 2;
679 registers_per_match_ = kAtomRegistersPerMatch;
680 // There is no distinction between interpreted and native for atom regexps.
683 registers_per_match_ = RegExpImpl::IrregexpPrepare(regexp_, subject_);
684 if (registers_per_match_ < 0) {
685 num_matches_ = -1; // Signal exception.
690 if (is_global && !interpreted) {
691 register_array_size_ =
692 Max(registers_per_match_, Isolate::kJSRegexpStaticOffsetsVectorSize);
693 max_matches_ = register_array_size_ / registers_per_match_;
695 // Global loop in interpreted regexp is not implemented. We choose
696 // the size of the offsets vector so that it can only store one match.
697 register_array_size_ = registers_per_match_;
701 if (register_array_size_ > Isolate::kJSRegexpStaticOffsetsVectorSize) {
702 register_array_ = NewArray<int32_t>(register_array_size_);
704 register_array_ = isolate->jsregexp_static_offsets_vector();
707 // Set state so that fetching the results the first time triggers a call
708 // to the compiled regexp.
709 current_match_index_ = max_matches_ - 1;
710 num_matches_ = max_matches_;
711 DCHECK(registers_per_match_ >= 2); // Each match has at least one capture.
712 DCHECK_GE(register_array_size_, registers_per_match_);
713 int32_t* last_match =
714 ®ister_array_[current_match_index_ * registers_per_match_];
720 // -------------------------------------------------------------------
721 // Implementation of the Irregexp regular expression engine.
723 // The Irregexp regular expression engine is intended to be a complete
724 // implementation of ECMAScript regular expressions. It generates either
725 // bytecodes or native code.
727 // The Irregexp regexp engine is structured in three steps.
728 // 1) The parser generates an abstract syntax tree. See ast.cc.
729 // 2) From the AST a node network is created. The nodes are all
730 // subclasses of RegExpNode. The nodes represent states when
731 // executing a regular expression. Several optimizations are
732 // performed on the node network.
733 // 3) From the nodes we generate either byte codes or native code
734 // that can actually execute the regular expression (perform
735 // the search). The code generation step is described in more
740 // The nodes are divided into four main categories.
742 // These represent places where the regular expression can
743 // match in more than one way. For example on entry to an
744 // alternation (foo|bar) or a repetition (*, +, ? or {}).
746 // These represent places where some action should be
747 // performed. Examples include recording the current position
748 // in the input string to a register (in order to implement
749 // captures) or other actions on register for example in order
750 // to implement the counters needed for {} repetitions.
752 // These attempt to match some element part of the input string.
753 // Examples of elements include character classes, plain strings
754 // or back references.
756 // These are used to implement the actions required on finding
757 // a successful match or failing to find a match.
759 // The code generated (whether as byte codes or native code) maintains
760 // some state as it runs. This consists of the following elements:
762 // * The capture registers. Used for string captures.
763 // * Other registers. Used for counters etc.
764 // * The current position.
765 // * The stack of backtracking information. Used when a matching node
766 // fails to find a match and needs to try an alternative.
768 // Conceptual regular expression execution model:
770 // There is a simple conceptual model of regular expression execution
771 // which will be presented first. The actual code generated is a more
772 // efficient simulation of the simple conceptual model:
774 // * Choice nodes are implemented as follows:
775 // For each choice except the last {
776 // push current position
777 // push backtrack code location
778 // <generate code to test for choice>
779 // backtrack code location:
780 // pop current position
782 // <generate code to test for last choice>
784 // * Actions nodes are generated as follows
785 // <push affected registers on backtrack stack>
786 // <generate code to perform action>
787 // push backtrack code location
788 // <generate code to test for following nodes>
789 // backtrack code location:
790 // <pop affected registers to restore their state>
791 // <pop backtrack location from stack and go to it>
793 // * Matching nodes are generated as follows:
794 // if input string matches at current position
795 // update current position
796 // <generate code to test for following nodes>
798 // <pop backtrack location from stack and go to it>
800 // Thus it can be seen that the current position is saved and restored
801 // by the choice nodes, whereas the registers are saved and restored by
802 // by the action nodes that manipulate them.
804 // The other interesting aspect of this model is that nodes are generated
805 // at the point where they are needed by a recursive call to Emit(). If
806 // the node has already been code generated then the Emit() call will
807 // generate a jump to the previously generated code instead. In order to
808 // limit recursion it is possible for the Emit() function to put the node
809 // on a work list for later generation and instead generate a jump. The
810 // destination of the jump is resolved later when the code is generated.
812 // Actual regular expression code generation.
814 // Code generation is actually more complicated than the above. In order
815 // to improve the efficiency of the generated code some optimizations are
818 // * Choice nodes have 1-character lookahead.
819 // A choice node looks at the following character and eliminates some of
820 // the choices immediately based on that character. This is not yet
822 // * Simple greedy loops store reduced backtracking information.
823 // A quantifier like /.*foo/m will greedily match the whole input. It will
824 // then need to backtrack to a point where it can match "foo". The naive
825 // implementation of this would push each character position onto the
826 // backtracking stack, then pop them off one by one. This would use space
827 // proportional to the length of the input string. However since the "."
828 // can only match in one way and always has a constant length (in this case
829 // of 1) it suffices to store the current position on the top of the stack
830 // once. Matching now becomes merely incrementing the current position and
831 // backtracking becomes decrementing the current position and checking the
832 // result against the stored current position. This is faster and saves
834 // * The current state is virtualized.
835 // This is used to defer expensive operations until it is clear that they
836 // are needed and to generate code for a node more than once, allowing
837 // specialized an efficient versions of the code to be created. This is
838 // explained in the section below.
840 // Execution state virtualization.
842 // Instead of emitting code, nodes that manipulate the state can record their
843 // manipulation in an object called the Trace. The Trace object can record a
844 // current position offset, an optional backtrack code location on the top of
845 // the virtualized backtrack stack and some register changes. When a node is
846 // to be emitted it can flush the Trace or update it. Flushing the Trace
847 // will emit code to bring the actual state into line with the virtual state.
848 // Avoiding flushing the state can postpone some work (e.g. updates of capture
849 // registers). Postponing work can save time when executing the regular
850 // expression since it may be found that the work never has to be done as a
851 // failure to match can occur. In addition it is much faster to jump to a
852 // known backtrack code location than it is to pop an unknown backtrack
853 // location from the stack and jump there.
855 // The virtual state found in the Trace affects code generation. For example
856 // the virtual state contains the difference between the actual current
857 // position and the virtual current position, and matching code needs to use
858 // this offset to attempt a match in the correct location of the input
859 // string. Therefore code generated for a non-trivial trace is specialized
860 // to that trace. The code generator therefore has the ability to generate
861 // code for each node several times. In order to limit the size of the
862 // generated code there is an arbitrary limit on how many specialized sets of
863 // code may be generated for a given node. If the limit is reached, the
864 // trace is flushed and a generic version of the code for a node is emitted.
865 // This is subsequently used for that node. The code emitted for non-generic
866 // trace is not recorded in the node and so it cannot currently be reused in
867 // the event that code generation is requested for an identical trace.
870 void RegExpTree::AppendToText(RegExpText* text, Zone* zone) {
875 void RegExpAtom::AppendToText(RegExpText* text, Zone* zone) {
876 text->AddElement(TextElement::Atom(this), zone);
880 void RegExpCharacterClass::AppendToText(RegExpText* text, Zone* zone) {
881 text->AddElement(TextElement::CharClass(this), zone);
885 void RegExpText::AppendToText(RegExpText* text, Zone* zone) {
886 for (int i = 0; i < elements()->length(); i++)
887 text->AddElement(elements()->at(i), zone);
891 TextElement TextElement::Atom(RegExpAtom* atom) {
892 return TextElement(ATOM, atom);
896 TextElement TextElement::CharClass(RegExpCharacterClass* char_class) {
897 return TextElement(CHAR_CLASS, char_class);
901 int TextElement::length() const {
902 switch (text_type()) {
904 return atom()->length();
914 DispatchTable* ChoiceNode::GetTable(bool ignore_case) {
915 if (table_ == NULL) {
916 table_ = new(zone()) DispatchTable(zone());
917 DispatchTableConstructor cons(table_, ignore_case, zone());
918 cons.BuildTable(this);
924 class FrequencyCollator {
926 FrequencyCollator() : total_samples_(0) {
927 for (int i = 0; i < RegExpMacroAssembler::kTableSize; i++) {
928 frequencies_[i] = CharacterFrequency(i);
932 void CountCharacter(int character) {
933 int index = (character & RegExpMacroAssembler::kTableMask);
934 frequencies_[index].Increment();
938 // Does not measure in percent, but rather per-128 (the table size from the
939 // regexp macro assembler).
940 int Frequency(int in_character) {
941 DCHECK((in_character & RegExpMacroAssembler::kTableMask) == in_character);
942 if (total_samples_ < 1) return 1; // Division by zero.
944 (frequencies_[in_character].counter() * 128) / total_samples_;
945 return freq_in_per128;
949 class CharacterFrequency {
951 CharacterFrequency() : counter_(0), character_(-1) { }
952 explicit CharacterFrequency(int character)
953 : counter_(0), character_(character) { }
955 void Increment() { counter_++; }
956 int counter() { return counter_; }
957 int character() { return character_; }
966 CharacterFrequency frequencies_[RegExpMacroAssembler::kTableSize];
971 class RegExpCompiler {
973 RegExpCompiler(Isolate* isolate, Zone* zone, int capture_count,
974 bool ignore_case, bool is_one_byte);
976 int AllocateRegister() {
977 if (next_register_ >= RegExpMacroAssembler::kMaxRegister) {
978 reg_exp_too_big_ = true;
979 return next_register_;
981 return next_register_++;
984 RegExpEngine::CompilationResult Assemble(RegExpMacroAssembler* assembler,
987 Handle<String> pattern);
989 inline void AddWork(RegExpNode* node) { work_list_->Add(node); }
991 static const int kImplementationOffset = 0;
992 static const int kNumberOfRegistersOffset = 0;
993 static const int kCodeOffset = 1;
995 RegExpMacroAssembler* macro_assembler() { return macro_assembler_; }
996 EndNode* accept() { return accept_; }
998 static const int kMaxRecursion = 100;
999 inline int recursion_depth() { return recursion_depth_; }
1000 inline void IncrementRecursionDepth() { recursion_depth_++; }
1001 inline void DecrementRecursionDepth() { recursion_depth_--; }
1003 void SetRegExpTooBig() { reg_exp_too_big_ = true; }
1005 inline bool ignore_case() { return ignore_case_; }
1006 inline bool one_byte() { return one_byte_; }
1007 inline bool optimize() { return optimize_; }
1008 inline void set_optimize(bool value) { optimize_ = value; }
1009 FrequencyCollator* frequency_collator() { return &frequency_collator_; }
1011 int current_expansion_factor() { return current_expansion_factor_; }
1012 void set_current_expansion_factor(int value) {
1013 current_expansion_factor_ = value;
1016 Isolate* isolate() const { return isolate_; }
1017 Zone* zone() const { return zone_; }
1019 static const int kNoRegister = -1;
1024 List<RegExpNode*>* work_list_;
1025 int recursion_depth_;
1026 RegExpMacroAssembler* macro_assembler_;
1029 bool reg_exp_too_big_;
1031 int current_expansion_factor_;
1032 FrequencyCollator frequency_collator_;
1038 class RecursionCheck {
1040 explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
1041 compiler->IncrementRecursionDepth();
1043 ~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
1045 RegExpCompiler* compiler_;
1049 static RegExpEngine::CompilationResult IrregexpRegExpTooBig(Isolate* isolate) {
1050 return RegExpEngine::CompilationResult(isolate, "RegExp too big");
1054 // Attempts to compile the regexp using an Irregexp code generator. Returns
1055 // a fixed array or a null handle depending on whether it succeeded.
1056 RegExpCompiler::RegExpCompiler(Isolate* isolate, Zone* zone, int capture_count,
1057 bool ignore_case, bool one_byte)
1058 : next_register_(2 * (capture_count + 1)),
1060 recursion_depth_(0),
1061 ignore_case_(ignore_case),
1062 one_byte_(one_byte),
1063 reg_exp_too_big_(false),
1064 optimize_(FLAG_regexp_optimization),
1065 current_expansion_factor_(1),
1066 frequency_collator_(),
1069 accept_ = new(zone) EndNode(EndNode::ACCEPT, zone);
1070 DCHECK(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
1074 RegExpEngine::CompilationResult RegExpCompiler::Assemble(
1075 RegExpMacroAssembler* macro_assembler,
1078 Handle<String> pattern) {
1079 Heap* heap = pattern->GetHeap();
1082 if (FLAG_trace_regexp_assembler)
1084 new RegExpMacroAssemblerTracer(isolate(), macro_assembler);
1087 macro_assembler_ = macro_assembler;
1089 List <RegExpNode*> work_list(0);
1090 work_list_ = &work_list;
1092 macro_assembler_->PushBacktrack(&fail);
1094 start->Emit(this, &new_trace);
1095 macro_assembler_->Bind(&fail);
1096 macro_assembler_->Fail();
1097 while (!work_list.is_empty()) {
1098 work_list.RemoveLast()->Emit(this, &new_trace);
1100 if (reg_exp_too_big_) return IrregexpRegExpTooBig(isolate_);
1102 Handle<HeapObject> code = macro_assembler_->GetCode(pattern);
1103 heap->IncreaseTotalRegexpCodeGenerated(code->Size());
1105 #ifdef ENABLE_DISASSEMBLER
1106 if (FLAG_print_code) {
1107 CodeTracer::Scope trace_scope(heap->isolate()->GetCodeTracer());
1108 OFStream os(trace_scope.file());
1109 Handle<Code>::cast(code)->Disassemble(pattern->ToCString().get(), os);
1113 if (FLAG_trace_regexp_assembler) {
1114 delete macro_assembler_;
1117 return RegExpEngine::CompilationResult(*code, next_register_);
1121 bool Trace::DeferredAction::Mentions(int that) {
1122 if (action_type() == ActionNode::CLEAR_CAPTURES) {
1123 Interval range = static_cast<DeferredClearCaptures*>(this)->range();
1124 return range.Contains(that);
1126 return reg() == that;
1131 bool Trace::mentions_reg(int reg) {
1132 for (DeferredAction* action = actions_;
1134 action = action->next()) {
1135 if (action->Mentions(reg))
1142 bool Trace::GetStoredPosition(int reg, int* cp_offset) {
1143 DCHECK_EQ(0, *cp_offset);
1144 for (DeferredAction* action = actions_;
1146 action = action->next()) {
1147 if (action->Mentions(reg)) {
1148 if (action->action_type() == ActionNode::STORE_POSITION) {
1149 *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
1160 int Trace::FindAffectedRegisters(OutSet* affected_registers,
1162 int max_register = RegExpCompiler::kNoRegister;
1163 for (DeferredAction* action = actions_;
1165 action = action->next()) {
1166 if (action->action_type() == ActionNode::CLEAR_CAPTURES) {
1167 Interval range = static_cast<DeferredClearCaptures*>(action)->range();
1168 for (int i = range.from(); i <= range.to(); i++)
1169 affected_registers->Set(i, zone);
1170 if (range.to() > max_register) max_register = range.to();
1172 affected_registers->Set(action->reg(), zone);
1173 if (action->reg() > max_register) max_register = action->reg();
1176 return max_register;
1180 void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
1182 const OutSet& registers_to_pop,
1183 const OutSet& registers_to_clear) {
1184 for (int reg = max_register; reg >= 0; reg--) {
1185 if (registers_to_pop.Get(reg)) {
1186 assembler->PopRegister(reg);
1187 } else if (registers_to_clear.Get(reg)) {
1189 while (reg > 0 && registers_to_clear.Get(reg - 1)) {
1192 assembler->ClearRegisters(reg, clear_to);
1198 void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
1200 const OutSet& affected_registers,
1201 OutSet* registers_to_pop,
1202 OutSet* registers_to_clear,
1204 // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
1205 const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
1207 // Count pushes performed to force a stack limit check occasionally.
1210 for (int reg = 0; reg <= max_register; reg++) {
1211 if (!affected_registers.Get(reg)) {
1215 // The chronologically first deferred action in the trace
1216 // is used to infer the action needed to restore a register
1217 // to its previous state (or not, if it's safe to ignore it).
1218 enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
1219 DeferredActionUndoType undo_action = IGNORE;
1222 bool absolute = false;
1224 int store_position = -1;
1225 // This is a little tricky because we are scanning the actions in reverse
1226 // historical order (newest first).
1227 for (DeferredAction* action = actions_;
1229 action = action->next()) {
1230 if (action->Mentions(reg)) {
1231 switch (action->action_type()) {
1232 case ActionNode::SET_REGISTER: {
1233 Trace::DeferredSetRegister* psr =
1234 static_cast<Trace::DeferredSetRegister*>(action);
1236 value += psr->value();
1239 // SET_REGISTER is currently only used for newly introduced loop
1240 // counters. They can have a significant previous value if they
1241 // occour in a loop. TODO(lrn): Propagate this information, so
1242 // we can set undo_action to IGNORE if we know there is no value to
1244 undo_action = RESTORE;
1245 DCHECK_EQ(store_position, -1);
1249 case ActionNode::INCREMENT_REGISTER:
1253 DCHECK_EQ(store_position, -1);
1255 undo_action = RESTORE;
1257 case ActionNode::STORE_POSITION: {
1258 Trace::DeferredCapture* pc =
1259 static_cast<Trace::DeferredCapture*>(action);
1260 if (!clear && store_position == -1) {
1261 store_position = pc->cp_offset();
1264 // For captures we know that stores and clears alternate.
1265 // Other register, are never cleared, and if the occur
1266 // inside a loop, they might be assigned more than once.
1268 // Registers zero and one, aka "capture zero", is
1269 // always set correctly if we succeed. There is no
1270 // need to undo a setting on backtrack, because we
1271 // will set it again or fail.
1272 undo_action = IGNORE;
1274 undo_action = pc->is_capture() ? CLEAR : RESTORE;
1277 DCHECK_EQ(value, 0);
1280 case ActionNode::CLEAR_CAPTURES: {
1281 // Since we're scanning in reverse order, if we've already
1282 // set the position we have to ignore historically earlier
1283 // clearing operations.
1284 if (store_position == -1) {
1287 undo_action = RESTORE;
1289 DCHECK_EQ(value, 0);
1298 // Prepare for the undo-action (e.g., push if it's going to be popped).
1299 if (undo_action == RESTORE) {
1301 RegExpMacroAssembler::StackCheckFlag stack_check =
1302 RegExpMacroAssembler::kNoStackLimitCheck;
1303 if (pushes == push_limit) {
1304 stack_check = RegExpMacroAssembler::kCheckStackLimit;
1308 assembler->PushRegister(reg, stack_check);
1309 registers_to_pop->Set(reg, zone);
1310 } else if (undo_action == CLEAR) {
1311 registers_to_clear->Set(reg, zone);
1313 // Perform the chronologically last action (or accumulated increment)
1314 // for the register.
1315 if (store_position != -1) {
1316 assembler->WriteCurrentPositionToRegister(reg, store_position);
1318 assembler->ClearRegisters(reg, reg);
1319 } else if (absolute) {
1320 assembler->SetRegister(reg, value);
1321 } else if (value != 0) {
1322 assembler->AdvanceRegister(reg, value);
1328 // This is called as we come into a loop choice node and some other tricky
1329 // nodes. It normalizes the state of the code generator to ensure we can
1330 // generate generic code.
1331 void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
1332 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1334 DCHECK(!is_trivial());
1336 if (actions_ == NULL && backtrack() == NULL) {
1337 // Here we just have some deferred cp advances to fix and we are back to
1338 // a normal situation. We may also have to forget some information gained
1339 // through a quick check that was already performed.
1340 if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
1341 // Create a new trivial state and generate the node with that.
1343 successor->Emit(compiler, &new_state);
1347 // Generate deferred actions here along with code to undo them again.
1348 OutSet affected_registers;
1350 if (backtrack() != NULL) {
1351 // Here we have a concrete backtrack location. These are set up by choice
1352 // nodes and so they indicate that we have a deferred save of the current
1353 // position which we may need to emit here.
1354 assembler->PushCurrentPosition();
1357 int max_register = FindAffectedRegisters(&affected_registers,
1359 OutSet registers_to_pop;
1360 OutSet registers_to_clear;
1361 PerformDeferredActions(assembler,
1365 ®isters_to_clear,
1367 if (cp_offset_ != 0) {
1368 assembler->AdvanceCurrentPosition(cp_offset_);
1371 // Create a new trivial state and generate the node with that.
1373 assembler->PushBacktrack(&undo);
1375 successor->Emit(compiler, &new_state);
1377 // On backtrack we need to restore state.
1378 assembler->Bind(&undo);
1379 RestoreAffectedRegisters(assembler,
1382 registers_to_clear);
1383 if (backtrack() == NULL) {
1384 assembler->Backtrack();
1386 assembler->PopCurrentPosition();
1387 assembler->GoTo(backtrack());
1392 void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
1393 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1395 // Omit flushing the trace. We discard the entire stack frame anyway.
1397 if (!label()->is_bound()) {
1398 // We are completely independent of the trace, since we ignore it,
1399 // so this code can be used as the generic version.
1400 assembler->Bind(label());
1403 // Throw away everything on the backtrack stack since the start
1404 // of the negative submatch and restore the character position.
1405 assembler->ReadCurrentPositionFromRegister(current_position_register_);
1406 assembler->ReadStackPointerFromRegister(stack_pointer_register_);
1407 if (clear_capture_count_ > 0) {
1408 // Clear any captures that might have been performed during the success
1409 // of the body of the negative look-ahead.
1410 int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
1411 assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
1413 // Now that we have unwound the stack we find at the top of the stack the
1414 // backtrack that the BeginSubmatch node got.
1415 assembler->Backtrack();
1419 void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
1420 if (!trace->is_trivial()) {
1421 trace->Flush(compiler, this);
1424 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1425 if (!label()->is_bound()) {
1426 assembler->Bind(label());
1430 assembler->Succeed();
1433 assembler->GoTo(trace->backtrack());
1435 case NEGATIVE_SUBMATCH_SUCCESS:
1436 // This case is handled in a different virtual method.
1443 void GuardedAlternative::AddGuard(Guard* guard, Zone* zone) {
1444 if (guards_ == NULL)
1445 guards_ = new(zone) ZoneList<Guard*>(1, zone);
1446 guards_->Add(guard, zone);
1450 ActionNode* ActionNode::SetRegister(int reg,
1452 RegExpNode* on_success) {
1453 ActionNode* result =
1454 new(on_success->zone()) ActionNode(SET_REGISTER, on_success);
1455 result->data_.u_store_register.reg = reg;
1456 result->data_.u_store_register.value = val;
1461 ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
1462 ActionNode* result =
1463 new(on_success->zone()) ActionNode(INCREMENT_REGISTER, on_success);
1464 result->data_.u_increment_register.reg = reg;
1469 ActionNode* ActionNode::StorePosition(int reg,
1471 RegExpNode* on_success) {
1472 ActionNode* result =
1473 new(on_success->zone()) ActionNode(STORE_POSITION, on_success);
1474 result->data_.u_position_register.reg = reg;
1475 result->data_.u_position_register.is_capture = is_capture;
1480 ActionNode* ActionNode::ClearCaptures(Interval range,
1481 RegExpNode* on_success) {
1482 ActionNode* result =
1483 new(on_success->zone()) ActionNode(CLEAR_CAPTURES, on_success);
1484 result->data_.u_clear_captures.range_from = range.from();
1485 result->data_.u_clear_captures.range_to = range.to();
1490 ActionNode* ActionNode::BeginSubmatch(int stack_reg,
1492 RegExpNode* on_success) {
1493 ActionNode* result =
1494 new(on_success->zone()) ActionNode(BEGIN_SUBMATCH, on_success);
1495 result->data_.u_submatch.stack_pointer_register = stack_reg;
1496 result->data_.u_submatch.current_position_register = position_reg;
1501 ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
1503 int clear_register_count,
1504 int clear_register_from,
1505 RegExpNode* on_success) {
1506 ActionNode* result =
1507 new(on_success->zone()) ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
1508 result->data_.u_submatch.stack_pointer_register = stack_reg;
1509 result->data_.u_submatch.current_position_register = position_reg;
1510 result->data_.u_submatch.clear_register_count = clear_register_count;
1511 result->data_.u_submatch.clear_register_from = clear_register_from;
1516 ActionNode* ActionNode::EmptyMatchCheck(int start_register,
1517 int repetition_register,
1518 int repetition_limit,
1519 RegExpNode* on_success) {
1520 ActionNode* result =
1521 new(on_success->zone()) ActionNode(EMPTY_MATCH_CHECK, on_success);
1522 result->data_.u_empty_match_check.start_register = start_register;
1523 result->data_.u_empty_match_check.repetition_register = repetition_register;
1524 result->data_.u_empty_match_check.repetition_limit = repetition_limit;
1529 #define DEFINE_ACCEPT(Type) \
1530 void Type##Node::Accept(NodeVisitor* visitor) { \
1531 visitor->Visit##Type(this); \
1533 FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
1534 #undef DEFINE_ACCEPT
1537 void LoopChoiceNode::Accept(NodeVisitor* visitor) {
1538 visitor->VisitLoopChoice(this);
1542 // -------------------------------------------------------------------
1546 void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
1549 switch (guard->op()) {
1551 DCHECK(!trace->mentions_reg(guard->reg()));
1552 macro_assembler->IfRegisterGE(guard->reg(),
1554 trace->backtrack());
1557 DCHECK(!trace->mentions_reg(guard->reg()));
1558 macro_assembler->IfRegisterLT(guard->reg(),
1560 trace->backtrack());
1566 // Returns the number of characters in the equivalence class, omitting those
1567 // that cannot occur in the source string because it is ASCII.
1568 static int GetCaseIndependentLetters(Isolate* isolate, uc16 character,
1569 bool one_byte_subject,
1570 unibrow::uchar* letters) {
1572 isolate->jsregexp_uncanonicalize()->get(character, '\0', letters);
1573 // Unibrow returns 0 or 1 for characters where case independence is
1576 letters[0] = character;
1579 if (!one_byte_subject || character <= String::kMaxOneByteCharCode) {
1583 // The standard requires that non-ASCII characters cannot have ASCII
1584 // character codes in their equivalence class.
1585 // TODO(dcarney): issue 3550 this is not actually true for Latin1 anymore,
1586 // is it? For example, \u00C5 is equivalent to \u212B.
1591 static inline bool EmitSimpleCharacter(Isolate* isolate,
1592 RegExpCompiler* compiler,
1598 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1599 bool bound_checked = false;
1601 assembler->LoadCurrentCharacter(
1605 bound_checked = true;
1607 assembler->CheckNotCharacter(c, on_failure);
1608 return bound_checked;
1612 // Only emits non-letters (things that don't have case). Only used for case
1613 // independent matches.
1614 static inline bool EmitAtomNonLetter(Isolate* isolate,
1615 RegExpCompiler* compiler,
1621 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1622 bool one_byte = compiler->one_byte();
1623 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
1624 int length = GetCaseIndependentLetters(isolate, c, one_byte, chars);
1626 // This can't match. Must be an one-byte subject and a non-one-byte
1627 // character. We do not need to do anything since the one-byte pass
1628 // already handled this.
1629 return false; // Bounds not checked.
1631 bool checked = false;
1632 // We handle the length > 1 case in a later pass.
1634 if (one_byte && c > String::kMaxOneByteCharCodeU) {
1635 // Can't match - see above.
1636 return false; // Bounds not checked.
1639 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1642 macro_assembler->CheckNotCharacter(c, on_failure);
1648 static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
1649 bool one_byte, uc16 c1, uc16 c2,
1650 Label* on_failure) {
1653 char_mask = String::kMaxOneByteCharCode;
1655 char_mask = String::kMaxUtf16CodeUnit;
1657 uc16 exor = c1 ^ c2;
1658 // Check whether exor has only one bit set.
1659 if (((exor - 1) & exor) == 0) {
1660 // If c1 and c2 differ only by one bit.
1661 // Ecma262UnCanonicalize always gives the highest number last.
1663 uc16 mask = char_mask ^ exor;
1664 macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
1668 uc16 diff = c2 - c1;
1669 if (((diff - 1) & diff) == 0 && c1 >= diff) {
1670 // If the characters differ by 2^n but don't differ by one bit then
1671 // subtract the difference from the found character, then do the or
1672 // trick. We avoid the theoretical case where negative numbers are
1673 // involved in order to simplify code generation.
1674 uc16 mask = char_mask ^ diff;
1675 macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff,
1685 typedef bool EmitCharacterFunction(Isolate* isolate,
1686 RegExpCompiler* compiler,
1693 // Only emits letters (things that have case). Only used for case independent
1695 static inline bool EmitAtomLetter(Isolate* isolate,
1696 RegExpCompiler* compiler,
1702 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1703 bool one_byte = compiler->one_byte();
1704 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
1705 int length = GetCaseIndependentLetters(isolate, c, one_byte, chars);
1706 if (length <= 1) return false;
1707 // We may not need to check against the end of the input string
1708 // if this character lies before a character that matched.
1710 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1713 DCHECK(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4);
1716 if (ShortCutEmitCharacterPair(macro_assembler, one_byte, chars[0],
1717 chars[1], on_failure)) {
1719 macro_assembler->CheckCharacter(chars[0], &ok);
1720 macro_assembler->CheckNotCharacter(chars[1], on_failure);
1721 macro_assembler->Bind(&ok);
1726 macro_assembler->CheckCharacter(chars[3], &ok);
1729 macro_assembler->CheckCharacter(chars[0], &ok);
1730 macro_assembler->CheckCharacter(chars[1], &ok);
1731 macro_assembler->CheckNotCharacter(chars[2], on_failure);
1732 macro_assembler->Bind(&ok);
1742 static void EmitBoundaryTest(RegExpMacroAssembler* masm,
1744 Label* fall_through,
1745 Label* above_or_equal,
1747 if (below != fall_through) {
1748 masm->CheckCharacterLT(border, below);
1749 if (above_or_equal != fall_through) masm->GoTo(above_or_equal);
1751 masm->CheckCharacterGT(border - 1, above_or_equal);
1756 static void EmitDoubleBoundaryTest(RegExpMacroAssembler* masm,
1759 Label* fall_through,
1761 Label* out_of_range) {
1762 if (in_range == fall_through) {
1763 if (first == last) {
1764 masm->CheckNotCharacter(first, out_of_range);
1766 masm->CheckCharacterNotInRange(first, last, out_of_range);
1769 if (first == last) {
1770 masm->CheckCharacter(first, in_range);
1772 masm->CheckCharacterInRange(first, last, in_range);
1774 if (out_of_range != fall_through) masm->GoTo(out_of_range);
1779 // even_label is for ranges[i] to ranges[i + 1] where i - start_index is even.
1780 // odd_label is for ranges[i] to ranges[i + 1] where i - start_index is odd.
1781 static void EmitUseLookupTable(
1782 RegExpMacroAssembler* masm,
1783 ZoneList<int>* ranges,
1787 Label* fall_through,
1790 static const int kSize = RegExpMacroAssembler::kTableSize;
1791 static const int kMask = RegExpMacroAssembler::kTableMask;
1793 int base = (min_char & ~kMask);
1796 // Assert that everything is on one kTableSize page.
1797 for (int i = start_index; i <= end_index; i++) {
1798 DCHECK_EQ(ranges->at(i) & ~kMask, base);
1800 DCHECK(start_index == 0 || (ranges->at(start_index - 1) & ~kMask) <= base);
1804 Label* on_bit_clear;
1806 if (even_label == fall_through) {
1807 on_bit_set = odd_label;
1808 on_bit_clear = even_label;
1811 on_bit_set = even_label;
1812 on_bit_clear = odd_label;
1815 for (int i = 0; i < (ranges->at(start_index) & kMask) && i < kSize; i++) {
1820 for (int i = start_index; i < end_index; i++) {
1821 for (j = (ranges->at(i) & kMask); j < (ranges->at(i + 1) & kMask); j++) {
1826 for (int i = j; i < kSize; i++) {
1829 Factory* factory = masm->isolate()->factory();
1830 // TODO(erikcorry): Cache these.
1831 Handle<ByteArray> ba = factory->NewByteArray(kSize, TENURED);
1832 for (int i = 0; i < kSize; i++) {
1833 ba->set(i, templ[i]);
1835 masm->CheckBitInTable(ba, on_bit_set);
1836 if (on_bit_clear != fall_through) masm->GoTo(on_bit_clear);
1840 static void CutOutRange(RegExpMacroAssembler* masm,
1841 ZoneList<int>* ranges,
1847 bool odd = (((cut_index - start_index) & 1) == 1);
1848 Label* in_range_label = odd ? odd_label : even_label;
1850 EmitDoubleBoundaryTest(masm,
1851 ranges->at(cut_index),
1852 ranges->at(cut_index + 1) - 1,
1856 DCHECK(!dummy.is_linked());
1857 // Cut out the single range by rewriting the array. This creates a new
1858 // range that is a merger of the two ranges on either side of the one we
1859 // are cutting out. The oddity of the labels is preserved.
1860 for (int j = cut_index; j > start_index; j--) {
1861 ranges->at(j) = ranges->at(j - 1);
1863 for (int j = cut_index + 1; j < end_index; j++) {
1864 ranges->at(j) = ranges->at(j + 1);
1869 // Unicode case. Split the search space into kSize spaces that are handled
1871 static void SplitSearchSpace(ZoneList<int>* ranges,
1874 int* new_start_index,
1877 static const int kSize = RegExpMacroAssembler::kTableSize;
1878 static const int kMask = RegExpMacroAssembler::kTableMask;
1880 int first = ranges->at(start_index);
1881 int last = ranges->at(end_index) - 1;
1883 *new_start_index = start_index;
1884 *border = (ranges->at(start_index) & ~kMask) + kSize;
1885 while (*new_start_index < end_index) {
1886 if (ranges->at(*new_start_index) > *border) break;
1887 (*new_start_index)++;
1889 // new_start_index is the index of the first edge that is beyond the
1890 // current kSize space.
1892 // For very large search spaces we do a binary chop search of the non-Latin1
1893 // space instead of just going to the end of the current kSize space. The
1894 // heuristics are complicated a little by the fact that any 128-character
1895 // encoding space can be quickly tested with a table lookup, so we don't
1896 // wish to do binary chop search at a smaller granularity than that. A
1897 // 128-character space can take up a lot of space in the ranges array if,
1898 // for example, we only want to match every second character (eg. the lower
1899 // case characters on some Unicode pages).
1900 int binary_chop_index = (end_index + start_index) / 2;
1901 // The first test ensures that we get to the code that handles the Latin1
1902 // range with a single not-taken branch, speeding up this important
1903 // character range (even non-Latin1 charset-based text has spaces and
1905 if (*border - 1 > String::kMaxOneByteCharCode && // Latin1 case.
1906 end_index - start_index > (*new_start_index - start_index) * 2 &&
1907 last - first > kSize * 2 && binary_chop_index > *new_start_index &&
1908 ranges->at(binary_chop_index) >= first + 2 * kSize) {
1909 int scan_forward_for_section_border = binary_chop_index;;
1910 int new_border = (ranges->at(binary_chop_index) | kMask) + 1;
1912 while (scan_forward_for_section_border < end_index) {
1913 if (ranges->at(scan_forward_for_section_border) > new_border) {
1914 *new_start_index = scan_forward_for_section_border;
1915 *border = new_border;
1918 scan_forward_for_section_border++;
1922 DCHECK(*new_start_index > start_index);
1923 *new_end_index = *new_start_index - 1;
1924 if (ranges->at(*new_end_index) == *border) {
1927 if (*border >= ranges->at(end_index)) {
1928 *border = ranges->at(end_index);
1929 *new_start_index = end_index; // Won't be used.
1930 *new_end_index = end_index - 1;
1935 // Gets a series of segment boundaries representing a character class. If the
1936 // character is in the range between an even and an odd boundary (counting from
1937 // start_index) then go to even_label, otherwise go to odd_label. We already
1938 // know that the character is in the range of min_char to max_char inclusive.
1939 // Either label can be NULL indicating backtracking. Either label can also be
1940 // equal to the fall_through label.
1941 static void GenerateBranches(RegExpMacroAssembler* masm,
1942 ZoneList<int>* ranges,
1947 Label* fall_through,
1950 int first = ranges->at(start_index);
1951 int last = ranges->at(end_index) - 1;
1953 DCHECK_LT(min_char, first);
1955 // Just need to test if the character is before or on-or-after
1956 // a particular character.
1957 if (start_index == end_index) {
1958 EmitBoundaryTest(masm, first, fall_through, even_label, odd_label);
1962 // Another almost trivial case: There is one interval in the middle that is
1963 // different from the end intervals.
1964 if (start_index + 1 == end_index) {
1965 EmitDoubleBoundaryTest(
1966 masm, first, last, fall_through, even_label, odd_label);
1970 // It's not worth using table lookup if there are very few intervals in the
1972 if (end_index - start_index <= 6) {
1973 // It is faster to test for individual characters, so we look for those
1974 // first, then try arbitrary ranges in the second round.
1975 static int kNoCutIndex = -1;
1976 int cut = kNoCutIndex;
1977 for (int i = start_index; i < end_index; i++) {
1978 if (ranges->at(i) == ranges->at(i + 1) - 1) {
1983 if (cut == kNoCutIndex) cut = start_index;
1985 masm, ranges, start_index, end_index, cut, even_label, odd_label);
1986 DCHECK_GE(end_index - start_index, 2);
1987 GenerateBranches(masm,
1999 // If there are a lot of intervals in the regexp, then we will use tables to
2000 // determine whether the character is inside or outside the character class.
2001 static const int kBits = RegExpMacroAssembler::kTableSizeBits;
2003 if ((max_char >> kBits) == (min_char >> kBits)) {
2004 EmitUseLookupTable(masm,
2015 if ((min_char >> kBits) != (first >> kBits)) {
2016 masm->CheckCharacterLT(first, odd_label);
2017 GenerateBranches(masm,
2029 int new_start_index = 0;
2030 int new_end_index = 0;
2033 SplitSearchSpace(ranges,
2041 Label* above = &handle_rest;
2042 if (border == last + 1) {
2043 // We didn't find any section that started after the limit, so everything
2044 // above the border is one of the terminal labels.
2045 above = (end_index & 1) != (start_index & 1) ? odd_label : even_label;
2046 DCHECK(new_end_index == end_index - 1);
2049 DCHECK_LE(start_index, new_end_index);
2050 DCHECK_LE(new_start_index, end_index);
2051 DCHECK_LT(start_index, new_start_index);
2052 DCHECK_LT(new_end_index, end_index);
2053 DCHECK(new_end_index + 1 == new_start_index ||
2054 (new_end_index + 2 == new_start_index &&
2055 border == ranges->at(new_end_index + 1)));
2056 DCHECK_LT(min_char, border - 1);
2057 DCHECK_LT(border, max_char);
2058 DCHECK_LT(ranges->at(new_end_index), border);
2059 DCHECK(border < ranges->at(new_start_index) ||
2060 (border == ranges->at(new_start_index) &&
2061 new_start_index == end_index &&
2062 new_end_index == end_index - 1 &&
2063 border == last + 1));
2064 DCHECK(new_start_index == 0 || border >= ranges->at(new_start_index - 1));
2066 masm->CheckCharacterGT(border - 1, above);
2068 GenerateBranches(masm,
2077 if (handle_rest.is_linked()) {
2078 masm->Bind(&handle_rest);
2079 bool flip = (new_start_index & 1) != (start_index & 1);
2080 GenerateBranches(masm,
2087 flip ? odd_label : even_label,
2088 flip ? even_label : odd_label);
2093 static void EmitCharClass(RegExpMacroAssembler* macro_assembler,
2094 RegExpCharacterClass* cc, bool one_byte,
2095 Label* on_failure, int cp_offset, bool check_offset,
2096 bool preloaded, Zone* zone) {
2097 ZoneList<CharacterRange>* ranges = cc->ranges(zone);
2098 if (!CharacterRange::IsCanonical(ranges)) {
2099 CharacterRange::Canonicalize(ranges);
2104 max_char = String::kMaxOneByteCharCode;
2106 max_char = String::kMaxUtf16CodeUnit;
2109 int range_count = ranges->length();
2111 int last_valid_range = range_count - 1;
2112 while (last_valid_range >= 0) {
2113 CharacterRange& range = ranges->at(last_valid_range);
2114 if (range.from() <= max_char) {
2120 if (last_valid_range < 0) {
2121 if (!cc->is_negated()) {
2122 macro_assembler->GoTo(on_failure);
2125 macro_assembler->CheckPosition(cp_offset, on_failure);
2130 if (last_valid_range == 0 &&
2131 ranges->at(0).IsEverything(max_char)) {
2132 if (cc->is_negated()) {
2133 macro_assembler->GoTo(on_failure);
2135 // This is a common case hit by non-anchored expressions.
2137 macro_assembler->CheckPosition(cp_offset, on_failure);
2142 if (last_valid_range == 0 &&
2143 !cc->is_negated() &&
2144 ranges->at(0).IsEverything(max_char)) {
2145 // This is a common case hit by non-anchored expressions.
2147 macro_assembler->CheckPosition(cp_offset, on_failure);
2153 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset);
2156 if (cc->is_standard(zone) &&
2157 macro_assembler->CheckSpecialCharacterClass(cc->standard_type(),
2163 // A new list with ascending entries. Each entry is a code unit
2164 // where there is a boundary between code units that are part of
2165 // the class and code units that are not. Normally we insert an
2166 // entry at zero which goes to the failure label, but if there
2167 // was already one there we fall through for success on that entry.
2168 // Subsequent entries have alternating meaning (success/failure).
2169 ZoneList<int>* range_boundaries =
2170 new(zone) ZoneList<int>(last_valid_range, zone);
2172 bool zeroth_entry_is_failure = !cc->is_negated();
2174 for (int i = 0; i <= last_valid_range; i++) {
2175 CharacterRange& range = ranges->at(i);
2176 if (range.from() == 0) {
2178 zeroth_entry_is_failure = !zeroth_entry_is_failure;
2180 range_boundaries->Add(range.from(), zone);
2182 range_boundaries->Add(range.to() + 1, zone);
2184 int end_index = range_boundaries->length() - 1;
2185 if (range_boundaries->at(end_index) > max_char) {
2190 GenerateBranches(macro_assembler,
2197 zeroth_entry_is_failure ? &fall_through : on_failure,
2198 zeroth_entry_is_failure ? on_failure : &fall_through);
2199 macro_assembler->Bind(&fall_through);
2203 RegExpNode::~RegExpNode() {
2207 RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler,
2209 // If we are generating a greedy loop then don't stop and don't reuse code.
2210 if (trace->stop_node() != NULL) {
2214 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2215 if (trace->is_trivial()) {
2216 if (label_.is_bound()) {
2217 // We are being asked to generate a generic version, but that's already
2218 // been done so just go to it.
2219 macro_assembler->GoTo(&label_);
2222 if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) {
2223 // To avoid too deep recursion we push the node to the work queue and just
2224 // generate a goto here.
2225 compiler->AddWork(this);
2226 macro_assembler->GoTo(&label_);
2229 // Generate generic version of the node and bind the label for later use.
2230 macro_assembler->Bind(&label_);
2234 // We are being asked to make a non-generic version. Keep track of how many
2235 // non-generic versions we generate so as not to overdo it.
2237 if (compiler->optimize() && trace_count_ < kMaxCopiesCodeGenerated &&
2238 compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) {
2242 // If we get here code has been generated for this node too many times or
2243 // recursion is too deep. Time to switch to a generic version. The code for
2244 // generic versions above can handle deep recursion properly.
2245 trace->Flush(compiler, this);
2250 int ActionNode::EatsAtLeast(int still_to_find,
2252 bool not_at_start) {
2253 if (budget <= 0) return 0;
2254 if (action_type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input!
2255 return on_success()->EatsAtLeast(still_to_find,
2261 void ActionNode::FillInBMInfo(int offset,
2263 BoyerMooreLookahead* bm,
2264 bool not_at_start) {
2265 if (action_type_ == BEGIN_SUBMATCH) {
2266 bm->SetRest(offset);
2267 } else if (action_type_ != POSITIVE_SUBMATCH_SUCCESS) {
2268 on_success()->FillInBMInfo(offset, budget - 1, bm, not_at_start);
2270 SaveBMInfo(bm, not_at_start, offset);
2274 int AssertionNode::EatsAtLeast(int still_to_find,
2276 bool not_at_start) {
2277 if (budget <= 0) return 0;
2278 // If we know we are not at the start and we are asked "how many characters
2279 // will you match if you succeed?" then we can answer anything since false
2280 // implies false. So lets just return the max answer (still_to_find) since
2281 // that won't prevent us from preloading a lot of characters for the other
2282 // branches in the node graph.
2283 if (assertion_type() == AT_START && not_at_start) return still_to_find;
2284 return on_success()->EatsAtLeast(still_to_find,
2290 void AssertionNode::FillInBMInfo(int offset,
2292 BoyerMooreLookahead* bm,
2293 bool not_at_start) {
2294 // Match the behaviour of EatsAtLeast on this node.
2295 if (assertion_type() == AT_START && not_at_start) return;
2296 on_success()->FillInBMInfo(offset, budget - 1, bm, not_at_start);
2297 SaveBMInfo(bm, not_at_start, offset);
2301 int BackReferenceNode::EatsAtLeast(int still_to_find,
2303 bool not_at_start) {
2304 if (budget <= 0) return 0;
2305 return on_success()->EatsAtLeast(still_to_find,
2311 int TextNode::EatsAtLeast(int still_to_find,
2313 bool not_at_start) {
2314 int answer = Length();
2315 if (answer >= still_to_find) return answer;
2316 if (budget <= 0) return answer;
2317 // We are not at start after this node so we set the last argument to 'true'.
2318 return answer + on_success()->EatsAtLeast(still_to_find - answer,
2324 int NegativeLookaheadChoiceNode::EatsAtLeast(int still_to_find,
2326 bool not_at_start) {
2327 if (budget <= 0) return 0;
2328 // Alternative 0 is the negative lookahead, alternative 1 is what comes
2330 RegExpNode* node = alternatives_->at(1).node();
2331 return node->EatsAtLeast(still_to_find, budget - 1, not_at_start);
2335 void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
2336 QuickCheckDetails* details,
2337 RegExpCompiler* compiler,
2339 bool not_at_start) {
2340 // Alternative 0 is the negative lookahead, alternative 1 is what comes
2342 RegExpNode* node = alternatives_->at(1).node();
2343 return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
2347 int ChoiceNode::EatsAtLeastHelper(int still_to_find,
2349 RegExpNode* ignore_this_node,
2350 bool not_at_start) {
2351 if (budget <= 0) return 0;
2353 int choice_count = alternatives_->length();
2354 budget = (budget - 1) / choice_count;
2355 for (int i = 0; i < choice_count; i++) {
2356 RegExpNode* node = alternatives_->at(i).node();
2357 if (node == ignore_this_node) continue;
2358 int node_eats_at_least =
2359 node->EatsAtLeast(still_to_find, budget, not_at_start);
2360 if (node_eats_at_least < min) min = node_eats_at_least;
2361 if (min == 0) return 0;
2367 int LoopChoiceNode::EatsAtLeast(int still_to_find,
2369 bool not_at_start) {
2370 return EatsAtLeastHelper(still_to_find,
2377 int ChoiceNode::EatsAtLeast(int still_to_find,
2379 bool not_at_start) {
2380 return EatsAtLeastHelper(still_to_find,
2387 // Takes the left-most 1-bit and smears it out, setting all bits to its right.
2388 static inline uint32_t SmearBitsRight(uint32_t v) {
2398 bool QuickCheckDetails::Rationalize(bool asc) {
2399 bool found_useful_op = false;
2402 char_mask = String::kMaxOneByteCharCode;
2404 char_mask = String::kMaxUtf16CodeUnit;
2409 for (int i = 0; i < characters_; i++) {
2410 Position* pos = &positions_[i];
2411 if ((pos->mask & String::kMaxOneByteCharCode) != 0) {
2412 found_useful_op = true;
2414 mask_ |= (pos->mask & char_mask) << char_shift;
2415 value_ |= (pos->value & char_mask) << char_shift;
2416 char_shift += asc ? 8 : 16;
2418 return found_useful_op;
2422 bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
2423 Trace* bounds_check_trace,
2425 bool preload_has_checked_bounds,
2426 Label* on_possible_success,
2427 QuickCheckDetails* details,
2428 bool fall_through_on_failure) {
2429 if (details->characters() == 0) return false;
2430 GetQuickCheckDetails(
2431 details, compiler, 0, trace->at_start() == Trace::FALSE_VALUE);
2432 if (details->cannot_match()) return false;
2433 if (!details->Rationalize(compiler->one_byte())) return false;
2434 DCHECK(details->characters() == 1 ||
2435 compiler->macro_assembler()->CanReadUnaligned());
2436 uint32_t mask = details->mask();
2437 uint32_t value = details->value();
2439 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2441 if (trace->characters_preloaded() != details->characters()) {
2442 DCHECK(trace->cp_offset() == bounds_check_trace->cp_offset());
2443 // We are attempting to preload the minimum number of characters
2444 // any choice would eat, so if the bounds check fails, then none of the
2445 // choices can succeed, so we can just immediately backtrack, rather
2446 // than go to the next choice.
2447 assembler->LoadCurrentCharacter(trace->cp_offset(),
2448 bounds_check_trace->backtrack(),
2449 !preload_has_checked_bounds,
2450 details->characters());
2454 bool need_mask = true;
2456 if (details->characters() == 1) {
2457 // If number of characters preloaded is 1 then we used a byte or 16 bit
2458 // load so the value is already masked down.
2460 if (compiler->one_byte()) {
2461 char_mask = String::kMaxOneByteCharCode;
2463 char_mask = String::kMaxUtf16CodeUnit;
2465 if ((mask & char_mask) == char_mask) need_mask = false;
2468 // For 2-character preloads in one-byte mode or 1-character preloads in
2469 // two-byte mode we also use a 16 bit load with zero extend.
2470 if (details->characters() == 2 && compiler->one_byte()) {
2471 if ((mask & 0xffff) == 0xffff) need_mask = false;
2472 } else if (details->characters() == 1 && !compiler->one_byte()) {
2473 if ((mask & 0xffff) == 0xffff) need_mask = false;
2475 if (mask == 0xffffffff) need_mask = false;
2479 if (fall_through_on_failure) {
2481 assembler->CheckCharacterAfterAnd(value, mask, on_possible_success);
2483 assembler->CheckCharacter(value, on_possible_success);
2487 assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack());
2489 assembler->CheckNotCharacter(value, trace->backtrack());
2496 // Here is the meat of GetQuickCheckDetails (see also the comment on the
2497 // super-class in the .h file).
2499 // We iterate along the text object, building up for each character a
2500 // mask and value that can be used to test for a quick failure to match.
2501 // The masks and values for the positions will be combined into a single
2502 // machine word for the current character width in order to be used in
2503 // generating a quick check.
2504 void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
2505 RegExpCompiler* compiler,
2506 int characters_filled_in,
2507 bool not_at_start) {
2508 Isolate* isolate = compiler->macro_assembler()->isolate();
2509 DCHECK(characters_filled_in < details->characters());
2510 int characters = details->characters();
2512 if (compiler->one_byte()) {
2513 char_mask = String::kMaxOneByteCharCode;
2515 char_mask = String::kMaxUtf16CodeUnit;
2517 for (int k = 0; k < elms_->length(); k++) {
2518 TextElement elm = elms_->at(k);
2519 if (elm.text_type() == TextElement::ATOM) {
2520 Vector<const uc16> quarks = elm.atom()->data();
2521 for (int i = 0; i < characters && i < quarks.length(); i++) {
2522 QuickCheckDetails::Position* pos =
2523 details->positions(characters_filled_in);
2525 if (c > char_mask) {
2526 // If we expect a non-Latin1 character from an one-byte string,
2527 // there is no way we can match. Not even case-independent
2528 // matching can turn an Latin1 character into non-Latin1 or
2530 // TODO(dcarney): issue 3550. Verify that this works as expected.
2531 // For example, \u0178 is uppercase of \u00ff (y-umlaut).
2532 details->set_cannot_match();
2533 pos->determines_perfectly = false;
2536 if (compiler->ignore_case()) {
2537 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
2538 int length = GetCaseIndependentLetters(isolate, c,
2539 compiler->one_byte(), chars);
2540 DCHECK(length != 0); // Can only happen if c > char_mask (see above).
2542 // This letter has no case equivalents, so it's nice and simple
2543 // and the mask-compare will determine definitely whether we have
2544 // a match at this character position.
2545 pos->mask = char_mask;
2547 pos->determines_perfectly = true;
2549 uint32_t common_bits = char_mask;
2550 uint32_t bits = chars[0];
2551 for (int j = 1; j < length; j++) {
2552 uint32_t differing_bits = ((chars[j] & common_bits) ^ bits);
2553 common_bits ^= differing_bits;
2554 bits &= common_bits;
2556 // If length is 2 and common bits has only one zero in it then
2557 // our mask and compare instruction will determine definitely
2558 // whether we have a match at this character position. Otherwise
2559 // it can only be an approximate check.
2560 uint32_t one_zero = (common_bits | ~char_mask);
2561 if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) {
2562 pos->determines_perfectly = true;
2564 pos->mask = common_bits;
2568 // Don't ignore case. Nice simple case where the mask-compare will
2569 // determine definitely whether we have a match at this character
2571 pos->mask = char_mask;
2573 pos->determines_perfectly = true;
2575 characters_filled_in++;
2576 DCHECK(characters_filled_in <= details->characters());
2577 if (characters_filled_in == details->characters()) {
2582 QuickCheckDetails::Position* pos =
2583 details->positions(characters_filled_in);
2584 RegExpCharacterClass* tree = elm.char_class();
2585 ZoneList<CharacterRange>* ranges = tree->ranges(zone());
2586 if (tree->is_negated()) {
2587 // A quick check uses multi-character mask and compare. There is no
2588 // useful way to incorporate a negative char class into this scheme
2589 // so we just conservatively create a mask and value that will always
2594 int first_range = 0;
2595 while (ranges->at(first_range).from() > char_mask) {
2597 if (first_range == ranges->length()) {
2598 details->set_cannot_match();
2599 pos->determines_perfectly = false;
2603 CharacterRange range = ranges->at(first_range);
2604 uc16 from = range.from();
2605 uc16 to = range.to();
2606 if (to > char_mask) {
2609 uint32_t differing_bits = (from ^ to);
2610 // A mask and compare is only perfect if the differing bits form a
2611 // number like 00011111 with one single block of trailing 1s.
2612 if ((differing_bits & (differing_bits + 1)) == 0 &&
2613 from + differing_bits == to) {
2614 pos->determines_perfectly = true;
2616 uint32_t common_bits = ~SmearBitsRight(differing_bits);
2617 uint32_t bits = (from & common_bits);
2618 for (int i = first_range + 1; i < ranges->length(); i++) {
2619 CharacterRange range = ranges->at(i);
2620 uc16 from = range.from();
2621 uc16 to = range.to();
2622 if (from > char_mask) continue;
2623 if (to > char_mask) to = char_mask;
2624 // Here we are combining more ranges into the mask and compare
2625 // value. With each new range the mask becomes more sparse and
2626 // so the chances of a false positive rise. A character class
2627 // with multiple ranges is assumed never to be equivalent to a
2628 // mask and compare operation.
2629 pos->determines_perfectly = false;
2630 uint32_t new_common_bits = (from ^ to);
2631 new_common_bits = ~SmearBitsRight(new_common_bits);
2632 common_bits &= new_common_bits;
2633 bits &= new_common_bits;
2634 uint32_t differing_bits = (from & common_bits) ^ bits;
2635 common_bits ^= differing_bits;
2636 bits &= common_bits;
2638 pos->mask = common_bits;
2641 characters_filled_in++;
2642 DCHECK(characters_filled_in <= details->characters());
2643 if (characters_filled_in == details->characters()) {
2648 DCHECK(characters_filled_in != details->characters());
2649 if (!details->cannot_match()) {
2650 on_success()-> GetQuickCheckDetails(details,
2652 characters_filled_in,
2658 void QuickCheckDetails::Clear() {
2659 for (int i = 0; i < characters_; i++) {
2660 positions_[i].mask = 0;
2661 positions_[i].value = 0;
2662 positions_[i].determines_perfectly = false;
2668 void QuickCheckDetails::Advance(int by, bool one_byte) {
2670 if (by >= characters_) {
2674 for (int i = 0; i < characters_ - by; i++) {
2675 positions_[i] = positions_[by + i];
2677 for (int i = characters_ - by; i < characters_; i++) {
2678 positions_[i].mask = 0;
2679 positions_[i].value = 0;
2680 positions_[i].determines_perfectly = false;
2683 // We could change mask_ and value_ here but we would never advance unless
2684 // they had already been used in a check and they won't be used again because
2685 // it would gain us nothing. So there's no point.
2689 void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) {
2690 DCHECK(characters_ == other->characters_);
2691 if (other->cannot_match_) {
2694 if (cannot_match_) {
2698 for (int i = from_index; i < characters_; i++) {
2699 QuickCheckDetails::Position* pos = positions(i);
2700 QuickCheckDetails::Position* other_pos = other->positions(i);
2701 if (pos->mask != other_pos->mask ||
2702 pos->value != other_pos->value ||
2703 !other_pos->determines_perfectly) {
2704 // Our mask-compare operation will be approximate unless we have the
2705 // exact same operation on both sides of the alternation.
2706 pos->determines_perfectly = false;
2708 pos->mask &= other_pos->mask;
2709 pos->value &= pos->mask;
2710 other_pos->value &= pos->mask;
2711 uc16 differing_bits = (pos->value ^ other_pos->value);
2712 pos->mask &= ~differing_bits;
2713 pos->value &= pos->mask;
2720 explicit VisitMarker(NodeInfo* info) : info_(info) {
2721 DCHECK(!info->visited);
2722 info->visited = true;
2725 info_->visited = false;
2732 RegExpNode* SeqRegExpNode::FilterOneByte(int depth, bool ignore_case) {
2733 if (info()->replacement_calculated) return replacement();
2734 if (depth < 0) return this;
2735 DCHECK(!info()->visited);
2736 VisitMarker marker(info());
2737 return FilterSuccessor(depth - 1, ignore_case);
2741 RegExpNode* SeqRegExpNode::FilterSuccessor(int depth, bool ignore_case) {
2742 RegExpNode* next = on_success_->FilterOneByte(depth - 1, ignore_case);
2743 if (next == NULL) return set_replacement(NULL);
2745 return set_replacement(this);
2749 // We need to check for the following characters: 0x39c 0x3bc 0x178.
2750 static inline bool RangeContainsLatin1Equivalents(CharacterRange range) {
2751 // TODO(dcarney): this could be a lot more efficient.
2752 return range.Contains(0x39c) ||
2753 range.Contains(0x3bc) || range.Contains(0x178);
2757 static bool RangesContainLatin1Equivalents(ZoneList<CharacterRange>* ranges) {
2758 for (int i = 0; i < ranges->length(); i++) {
2759 // TODO(dcarney): this could be a lot more efficient.
2760 if (RangeContainsLatin1Equivalents(ranges->at(i))) return true;
2766 RegExpNode* TextNode::FilterOneByte(int depth, bool ignore_case) {
2767 if (info()->replacement_calculated) return replacement();
2768 if (depth < 0) return this;
2769 DCHECK(!info()->visited);
2770 VisitMarker marker(info());
2771 int element_count = elms_->length();
2772 for (int i = 0; i < element_count; i++) {
2773 TextElement elm = elms_->at(i);
2774 if (elm.text_type() == TextElement::ATOM) {
2775 Vector<const uc16> quarks = elm.atom()->data();
2776 for (int j = 0; j < quarks.length(); j++) {
2777 uint16_t c = quarks[j];
2778 if (c <= String::kMaxOneByteCharCode) continue;
2779 if (!ignore_case) return set_replacement(NULL);
2780 // Here, we need to check for characters whose upper and lower cases
2781 // are outside the Latin-1 range.
2782 uint16_t converted = unibrow::Latin1::ConvertNonLatin1ToLatin1(c);
2783 // Character is outside Latin-1 completely
2784 if (converted == 0) return set_replacement(NULL);
2785 // Convert quark to Latin-1 in place.
2786 uint16_t* copy = const_cast<uint16_t*>(quarks.start());
2787 copy[j] = converted;
2790 DCHECK(elm.text_type() == TextElement::CHAR_CLASS);
2791 RegExpCharacterClass* cc = elm.char_class();
2792 ZoneList<CharacterRange>* ranges = cc->ranges(zone());
2793 if (!CharacterRange::IsCanonical(ranges)) {
2794 CharacterRange::Canonicalize(ranges);
2796 // Now they are in order so we only need to look at the first.
2797 int range_count = ranges->length();
2798 if (cc->is_negated()) {
2799 if (range_count != 0 &&
2800 ranges->at(0).from() == 0 &&
2801 ranges->at(0).to() >= String::kMaxOneByteCharCode) {
2802 // This will be handled in a later filter.
2803 if (ignore_case && RangesContainLatin1Equivalents(ranges)) continue;
2804 return set_replacement(NULL);
2807 if (range_count == 0 ||
2808 ranges->at(0).from() > String::kMaxOneByteCharCode) {
2809 // This will be handled in a later filter.
2810 if (ignore_case && RangesContainLatin1Equivalents(ranges)) continue;
2811 return set_replacement(NULL);
2816 return FilterSuccessor(depth - 1, ignore_case);
2820 RegExpNode* LoopChoiceNode::FilterOneByte(int depth, bool ignore_case) {
2821 if (info()->replacement_calculated) return replacement();
2822 if (depth < 0) return this;
2823 if (info()->visited) return this;
2825 VisitMarker marker(info());
2827 RegExpNode* continue_replacement =
2828 continue_node_->FilterOneByte(depth - 1, ignore_case);
2829 // If we can't continue after the loop then there is no sense in doing the
2831 if (continue_replacement == NULL) return set_replacement(NULL);
2834 return ChoiceNode::FilterOneByte(depth - 1, ignore_case);
2838 RegExpNode* ChoiceNode::FilterOneByte(int depth, bool ignore_case) {
2839 if (info()->replacement_calculated) return replacement();
2840 if (depth < 0) return this;
2841 if (info()->visited) return this;
2842 VisitMarker marker(info());
2843 int choice_count = alternatives_->length();
2845 for (int i = 0; i < choice_count; i++) {
2846 GuardedAlternative alternative = alternatives_->at(i);
2847 if (alternative.guards() != NULL && alternative.guards()->length() != 0) {
2848 set_replacement(this);
2854 RegExpNode* survivor = NULL;
2855 for (int i = 0; i < choice_count; i++) {
2856 GuardedAlternative alternative = alternatives_->at(i);
2857 RegExpNode* replacement =
2858 alternative.node()->FilterOneByte(depth - 1, ignore_case);
2859 DCHECK(replacement != this); // No missing EMPTY_MATCH_CHECK.
2860 if (replacement != NULL) {
2861 alternatives_->at(i).set_node(replacement);
2863 survivor = replacement;
2866 if (surviving < 2) return set_replacement(survivor);
2868 set_replacement(this);
2869 if (surviving == choice_count) {
2872 // Only some of the nodes survived the filtering. We need to rebuild the
2873 // alternatives list.
2874 ZoneList<GuardedAlternative>* new_alternatives =
2875 new(zone()) ZoneList<GuardedAlternative>(surviving, zone());
2876 for (int i = 0; i < choice_count; i++) {
2877 RegExpNode* replacement =
2878 alternatives_->at(i).node()->FilterOneByte(depth - 1, ignore_case);
2879 if (replacement != NULL) {
2880 alternatives_->at(i).set_node(replacement);
2881 new_alternatives->Add(alternatives_->at(i), zone());
2884 alternatives_ = new_alternatives;
2889 RegExpNode* NegativeLookaheadChoiceNode::FilterOneByte(int depth,
2891 if (info()->replacement_calculated) return replacement();
2892 if (depth < 0) return this;
2893 if (info()->visited) return this;
2894 VisitMarker marker(info());
2895 // Alternative 0 is the negative lookahead, alternative 1 is what comes
2897 RegExpNode* node = alternatives_->at(1).node();
2898 RegExpNode* replacement = node->FilterOneByte(depth - 1, ignore_case);
2899 if (replacement == NULL) return set_replacement(NULL);
2900 alternatives_->at(1).set_node(replacement);
2902 RegExpNode* neg_node = alternatives_->at(0).node();
2903 RegExpNode* neg_replacement = neg_node->FilterOneByte(depth - 1, ignore_case);
2904 // If the negative lookahead is always going to fail then
2905 // we don't need to check it.
2906 if (neg_replacement == NULL) return set_replacement(replacement);
2907 alternatives_->at(0).set_node(neg_replacement);
2908 return set_replacement(this);
2912 void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2913 RegExpCompiler* compiler,
2914 int characters_filled_in,
2915 bool not_at_start) {
2916 if (body_can_be_zero_length_ || info()->visited) return;
2917 VisitMarker marker(info());
2918 return ChoiceNode::GetQuickCheckDetails(details,
2920 characters_filled_in,
2925 void LoopChoiceNode::FillInBMInfo(int offset,
2927 BoyerMooreLookahead* bm,
2928 bool not_at_start) {
2929 if (body_can_be_zero_length_ || budget <= 0) {
2930 bm->SetRest(offset);
2931 SaveBMInfo(bm, not_at_start, offset);
2934 ChoiceNode::FillInBMInfo(offset, budget - 1, bm, not_at_start);
2935 SaveBMInfo(bm, not_at_start, offset);
2939 void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2940 RegExpCompiler* compiler,
2941 int characters_filled_in,
2942 bool not_at_start) {
2943 not_at_start = (not_at_start || not_at_start_);
2944 int choice_count = alternatives_->length();
2945 DCHECK(choice_count > 0);
2946 alternatives_->at(0).node()->GetQuickCheckDetails(details,
2948 characters_filled_in,
2950 for (int i = 1; i < choice_count; i++) {
2951 QuickCheckDetails new_details(details->characters());
2952 RegExpNode* node = alternatives_->at(i).node();
2953 node->GetQuickCheckDetails(&new_details, compiler,
2954 characters_filled_in,
2956 // Here we merge the quick match details of the two branches.
2957 details->Merge(&new_details, characters_filled_in);
2962 // Check for [0-9A-Z_a-z].
2963 static void EmitWordCheck(RegExpMacroAssembler* assembler,
2966 bool fall_through_on_word) {
2967 if (assembler->CheckSpecialCharacterClass(
2968 fall_through_on_word ? 'w' : 'W',
2969 fall_through_on_word ? non_word : word)) {
2970 // Optimized implementation available.
2973 assembler->CheckCharacterGT('z', non_word);
2974 assembler->CheckCharacterLT('0', non_word);
2975 assembler->CheckCharacterGT('a' - 1, word);
2976 assembler->CheckCharacterLT('9' + 1, word);
2977 assembler->CheckCharacterLT('A', non_word);
2978 assembler->CheckCharacterLT('Z' + 1, word);
2979 if (fall_through_on_word) {
2980 assembler->CheckNotCharacter('_', non_word);
2982 assembler->CheckCharacter('_', word);
2987 // Emit the code to check for a ^ in multiline mode (1-character lookbehind
2988 // that matches newline or the start of input).
2989 static void EmitHat(RegExpCompiler* compiler,
2990 RegExpNode* on_success,
2992 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2993 // We will be loading the previous character into the current character
2995 Trace new_trace(*trace);
2996 new_trace.InvalidateCurrentCharacter();
2999 if (new_trace.cp_offset() == 0) {
3000 // The start of input counts as a newline in this context, so skip to
3001 // ok if we are at the start.
3002 assembler->CheckAtStart(&ok);
3004 // We already checked that we are not at the start of input so it must be
3005 // OK to load the previous character.
3006 assembler->LoadCurrentCharacter(new_trace.cp_offset() -1,
3007 new_trace.backtrack(),
3009 if (!assembler->CheckSpecialCharacterClass('n',
3010 new_trace.backtrack())) {
3011 // Newline means \n, \r, 0x2028 or 0x2029.
3012 if (!compiler->one_byte()) {
3013 assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok);
3015 assembler->CheckCharacter('\n', &ok);
3016 assembler->CheckNotCharacter('\r', new_trace.backtrack());
3018 assembler->Bind(&ok);
3019 on_success->Emit(compiler, &new_trace);
3023 // Emit the code to handle \b and \B (word-boundary or non-word-boundary).
3024 void AssertionNode::EmitBoundaryCheck(RegExpCompiler* compiler, Trace* trace) {
3025 RegExpMacroAssembler* assembler = compiler->macro_assembler();
3026 Trace::TriBool next_is_word_character = Trace::UNKNOWN;
3027 bool not_at_start = (trace->at_start() == Trace::FALSE_VALUE);
3028 BoyerMooreLookahead* lookahead = bm_info(not_at_start);
3029 if (lookahead == NULL) {
3031 Min(kMaxLookaheadForBoyerMoore, EatsAtLeast(kMaxLookaheadForBoyerMoore,
3034 if (eats_at_least >= 1) {
3035 BoyerMooreLookahead* bm =
3036 new(zone()) BoyerMooreLookahead(eats_at_least, compiler, zone());
3037 FillInBMInfo(0, kRecursionBudget, bm, not_at_start);
3038 if (bm->at(0)->is_non_word())
3039 next_is_word_character = Trace::FALSE_VALUE;
3040 if (bm->at(0)->is_word()) next_is_word_character = Trace::TRUE_VALUE;
3043 if (lookahead->at(0)->is_non_word())
3044 next_is_word_character = Trace::FALSE_VALUE;
3045 if (lookahead->at(0)->is_word())
3046 next_is_word_character = Trace::TRUE_VALUE;
3048 bool at_boundary = (assertion_type_ == AssertionNode::AT_BOUNDARY);
3049 if (next_is_word_character == Trace::UNKNOWN) {
3050 Label before_non_word;
3052 if (trace->characters_preloaded() != 1) {
3053 assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word);
3055 // Fall through on non-word.
3056 EmitWordCheck(assembler, &before_word, &before_non_word, false);
3057 // Next character is not a word character.
3058 assembler->Bind(&before_non_word);
3060 BacktrackIfPrevious(compiler, trace, at_boundary ? kIsNonWord : kIsWord);
3061 assembler->GoTo(&ok);
3063 assembler->Bind(&before_word);
3064 BacktrackIfPrevious(compiler, trace, at_boundary ? kIsWord : kIsNonWord);
3065 assembler->Bind(&ok);
3066 } else if (next_is_word_character == Trace::TRUE_VALUE) {
3067 BacktrackIfPrevious(compiler, trace, at_boundary ? kIsWord : kIsNonWord);
3069 DCHECK(next_is_word_character == Trace::FALSE_VALUE);
3070 BacktrackIfPrevious(compiler, trace, at_boundary ? kIsNonWord : kIsWord);
3075 void AssertionNode::BacktrackIfPrevious(
3076 RegExpCompiler* compiler,
3078 AssertionNode::IfPrevious backtrack_if_previous) {
3079 RegExpMacroAssembler* assembler = compiler->macro_assembler();
3080 Trace new_trace(*trace);
3081 new_trace.InvalidateCurrentCharacter();
3083 Label fall_through, dummy;
3085 Label* non_word = backtrack_if_previous == kIsNonWord ?
3086 new_trace.backtrack() :
3088 Label* word = backtrack_if_previous == kIsNonWord ?
3090 new_trace.backtrack();
3092 if (new_trace.cp_offset() == 0) {
3093 // The start of input counts as a non-word character, so the question is
3094 // decided if we are at the start.
3095 assembler->CheckAtStart(non_word);
3097 // We already checked that we are not at the start of input so it must be
3098 // OK to load the previous character.
3099 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1, &dummy, false);
3100 EmitWordCheck(assembler, word, non_word, backtrack_if_previous == kIsNonWord);
3102 assembler->Bind(&fall_through);
3103 on_success()->Emit(compiler, &new_trace);
3107 void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details,
3108 RegExpCompiler* compiler,
3110 bool not_at_start) {
3111 if (assertion_type_ == AT_START && not_at_start) {
3112 details->set_cannot_match();
3115 return on_success()->GetQuickCheckDetails(details,
3122 void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3123 RegExpMacroAssembler* assembler = compiler->macro_assembler();
3124 switch (assertion_type_) {
3127 assembler->CheckPosition(trace->cp_offset(), &ok);
3128 assembler->GoTo(trace->backtrack());
3129 assembler->Bind(&ok);
3133 if (trace->at_start() == Trace::FALSE_VALUE) {
3134 assembler->GoTo(trace->backtrack());
3137 if (trace->at_start() == Trace::UNKNOWN) {
3138 assembler->CheckNotAtStart(trace->backtrack());
3139 Trace at_start_trace = *trace;
3140 at_start_trace.set_at_start(true);
3141 on_success()->Emit(compiler, &at_start_trace);
3147 EmitHat(compiler, on_success(), trace);
3150 case AT_NON_BOUNDARY: {
3151 EmitBoundaryCheck(compiler, trace);
3155 on_success()->Emit(compiler, trace);
3159 static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) {
3160 if (quick_check == NULL) return false;
3161 if (offset >= quick_check->characters()) return false;
3162 return quick_check->positions(offset)->determines_perfectly;
3166 static void UpdateBoundsCheck(int index, int* checked_up_to) {
3167 if (index > *checked_up_to) {
3168 *checked_up_to = index;
3173 // We call this repeatedly to generate code for each pass over the text node.
3174 // The passes are in increasing order of difficulty because we hope one
3175 // of the first passes will fail in which case we are saved the work of the
3176 // later passes. for example for the case independent regexp /%[asdfghjkl]a/
3177 // we will check the '%' in the first pass, the case independent 'a' in the
3178 // second pass and the character class in the last pass.
3180 // The passes are done from right to left, so for example to test for /bar/
3181 // we will first test for an 'r' with offset 2, then an 'a' with offset 1
3182 // and then a 'b' with offset 0. This means we can avoid the end-of-input
3183 // bounds check most of the time. In the example we only need to check for
3184 // end-of-input when loading the putative 'r'.
3186 // A slight complication involves the fact that the first character may already
3187 // be fetched into a register by the previous node. In this case we want to
3188 // do the test for that character first. We do this in separate passes. The
3189 // 'preloaded' argument indicates that we are doing such a 'pass'. If such a
3190 // pass has been performed then subsequent passes will have true in
3191 // first_element_checked to indicate that that character does not need to be
3194 // In addition to all this we are passed a Trace, which can
3195 // contain an AlternativeGeneration object. In this AlternativeGeneration
3196 // object we can see details of any quick check that was already passed in
3197 // order to get to the code we are now generating. The quick check can involve
3198 // loading characters, which means we do not need to recheck the bounds
3199 // up to the limit the quick check already checked. In addition the quick
3200 // check can have involved a mask and compare operation which may simplify
3201 // or obviate the need for further checks at some character positions.
3202 void TextNode::TextEmitPass(RegExpCompiler* compiler,
3203 TextEmitPassType pass,
3206 bool first_element_checked,
3207 int* checked_up_to) {
3208 RegExpMacroAssembler* assembler = compiler->macro_assembler();
3209 Isolate* isolate = assembler->isolate();
3210 bool one_byte = compiler->one_byte();
3211 Label* backtrack = trace->backtrack();
3212 QuickCheckDetails* quick_check = trace->quick_check_performed();
3213 int element_count = elms_->length();
3214 for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) {
3215 TextElement elm = elms_->at(i);
3216 int cp_offset = trace->cp_offset() + elm.cp_offset();
3217 if (elm.text_type() == TextElement::ATOM) {
3218 Vector<const uc16> quarks = elm.atom()->data();
3219 for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) {
3220 if (first_element_checked && i == 0 && j == 0) continue;
3221 if (DeterminedAlready(quick_check, elm.cp_offset() + j)) continue;
3222 EmitCharacterFunction* emit_function = NULL;
3224 case NON_LATIN1_MATCH:
3226 if (quarks[j] > String::kMaxOneByteCharCode) {
3227 assembler->GoTo(backtrack);
3231 case NON_LETTER_CHARACTER_MATCH:
3232 emit_function = &EmitAtomNonLetter;
3234 case SIMPLE_CHARACTER_MATCH:
3235 emit_function = &EmitSimpleCharacter;
3237 case CASE_CHARACTER_MATCH:
3238 emit_function = &EmitAtomLetter;
3243 if (emit_function != NULL) {
3244 bool bound_checked = emit_function(isolate,
3249 *checked_up_to < cp_offset + j,
3251 if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
3255 DCHECK_EQ(TextElement::CHAR_CLASS, elm.text_type());
3256 if (pass == CHARACTER_CLASS_MATCH) {
3257 if (first_element_checked && i == 0) continue;
3258 if (DeterminedAlready(quick_check, elm.cp_offset())) continue;
3259 RegExpCharacterClass* cc = elm.char_class();
3260 EmitCharClass(assembler, cc, one_byte, backtrack, cp_offset,
3261 *checked_up_to < cp_offset, preloaded, zone());
3262 UpdateBoundsCheck(cp_offset, checked_up_to);
3269 int TextNode::Length() {
3270 TextElement elm = elms_->last();
3271 DCHECK(elm.cp_offset() >= 0);
3272 return elm.cp_offset() + elm.length();
3276 bool TextNode::SkipPass(int int_pass, bool ignore_case) {
3277 TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass);
3279 return pass == SIMPLE_CHARACTER_MATCH;
3281 return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH;
3286 // This generates the code to match a text node. A text node can contain
3287 // straight character sequences (possibly to be matched in a case-independent
3288 // way) and character classes. For efficiency we do not do this in a single
3289 // pass from left to right. Instead we pass over the text node several times,
3290 // emitting code for some character positions every time. See the comment on
3291 // TextEmitPass for details.
3292 void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3293 LimitResult limit_result = LimitVersions(compiler, trace);
3294 if (limit_result == DONE) return;
3295 DCHECK(limit_result == CONTINUE);
3297 if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
3298 compiler->SetRegExpTooBig();
3302 if (compiler->one_byte()) {
3304 TextEmitPass(compiler, NON_LATIN1_MATCH, false, trace, false, &dummy);
3307 bool first_elt_done = false;
3308 int bound_checked_to = trace->cp_offset() - 1;
3309 bound_checked_to += trace->bound_checked_up_to();
3311 // If a character is preloaded into the current character register then
3313 if (trace->characters_preloaded() == 1) {
3314 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
3315 if (!SkipPass(pass, compiler->ignore_case())) {
3316 TextEmitPass(compiler,
3317 static_cast<TextEmitPassType>(pass),
3324 first_elt_done = true;
3327 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
3328 if (!SkipPass(pass, compiler->ignore_case())) {
3329 TextEmitPass(compiler,
3330 static_cast<TextEmitPassType>(pass),
3338 Trace successor_trace(*trace);
3339 successor_trace.set_at_start(false);
3340 successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler);
3341 RecursionCheck rc(compiler);
3342 on_success()->Emit(compiler, &successor_trace);
3346 void Trace::InvalidateCurrentCharacter() {
3347 characters_preloaded_ = 0;
3351 void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) {
3353 // We don't have an instruction for shifting the current character register
3354 // down or for using a shifted value for anything so lets just forget that
3355 // we preloaded any characters into it.
3356 characters_preloaded_ = 0;
3357 // Adjust the offsets of the quick check performed information. This
3358 // information is used to find out what we already determined about the
3359 // characters by means of mask and compare.
3360 quick_check_performed_.Advance(by, compiler->one_byte());
3362 if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
3363 compiler->SetRegExpTooBig();
3366 bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
3370 void TextNode::MakeCaseIndependent(Isolate* isolate, bool is_one_byte) {
3371 int element_count = elms_->length();
3372 for (int i = 0; i < element_count; i++) {
3373 TextElement elm = elms_->at(i);
3374 if (elm.text_type() == TextElement::CHAR_CLASS) {
3375 RegExpCharacterClass* cc = elm.char_class();
3376 // None of the standard character classes is different in the case
3377 // independent case and it slows us down if we don't know that.
3378 if (cc->is_standard(zone())) continue;
3379 ZoneList<CharacterRange>* ranges = cc->ranges(zone());
3380 int range_count = ranges->length();
3381 for (int j = 0; j < range_count; j++) {
3382 ranges->at(j).AddCaseEquivalents(isolate, zone(), ranges, is_one_byte);
3389 int TextNode::GreedyLoopTextLength() {
3390 TextElement elm = elms_->at(elms_->length() - 1);
3391 return elm.cp_offset() + elm.length();
3395 RegExpNode* TextNode::GetSuccessorOfOmnivorousTextNode(
3396 RegExpCompiler* compiler) {
3397 if (elms_->length() != 1) return NULL;
3398 TextElement elm = elms_->at(0);
3399 if (elm.text_type() != TextElement::CHAR_CLASS) return NULL;
3400 RegExpCharacterClass* node = elm.char_class();
3401 ZoneList<CharacterRange>* ranges = node->ranges(zone());
3402 if (!CharacterRange::IsCanonical(ranges)) {
3403 CharacterRange::Canonicalize(ranges);
3405 if (node->is_negated()) {
3406 return ranges->length() == 0 ? on_success() : NULL;
3408 if (ranges->length() != 1) return NULL;
3410 if (compiler->one_byte()) {
3411 max_char = String::kMaxOneByteCharCode;
3413 max_char = String::kMaxUtf16CodeUnit;
3415 return ranges->at(0).IsEverything(max_char) ? on_success() : NULL;
3419 // Finds the fixed match length of a sequence of nodes that goes from
3420 // this alternative and back to this choice node. If there are variable
3421 // length nodes or other complications in the way then return a sentinel
3422 // value indicating that a greedy loop cannot be constructed.
3423 int ChoiceNode::GreedyLoopTextLengthForAlternative(
3424 GuardedAlternative* alternative) {
3426 RegExpNode* node = alternative->node();
3427 // Later we will generate code for all these text nodes using recursion
3428 // so we have to limit the max number.
3429 int recursion_depth = 0;
3430 while (node != this) {
3431 if (recursion_depth++ > RegExpCompiler::kMaxRecursion) {
3432 return kNodeIsTooComplexForGreedyLoops;
3434 int node_length = node->GreedyLoopTextLength();
3435 if (node_length == kNodeIsTooComplexForGreedyLoops) {
3436 return kNodeIsTooComplexForGreedyLoops;
3438 length += node_length;
3439 SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node);
3440 node = seq_node->on_success();
3446 void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
3447 DCHECK_NULL(loop_node_);
3448 AddAlternative(alt);
3449 loop_node_ = alt.node();
3453 void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
3454 DCHECK_NULL(continue_node_);
3455 AddAlternative(alt);
3456 continue_node_ = alt.node();
3460 void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3461 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
3462 if (trace->stop_node() == this) {
3463 // Back edge of greedy optimized loop node graph.
3465 GreedyLoopTextLengthForAlternative(&(alternatives_->at(0)));
3466 DCHECK(text_length != kNodeIsTooComplexForGreedyLoops);
3467 // Update the counter-based backtracking info on the stack. This is an
3468 // optimization for greedy loops (see below).
3469 DCHECK(trace->cp_offset() == text_length);
3470 macro_assembler->AdvanceCurrentPosition(text_length);
3471 macro_assembler->GoTo(trace->loop_label());
3474 DCHECK_NULL(trace->stop_node());
3475 if (!trace->is_trivial()) {
3476 trace->Flush(compiler, this);
3479 ChoiceNode::Emit(compiler, trace);
3483 int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler,
3484 int eats_at_least) {
3485 int preload_characters = Min(4, eats_at_least);
3486 if (compiler->macro_assembler()->CanReadUnaligned()) {
3487 bool one_byte = compiler->one_byte();
3489 if (preload_characters > 4) preload_characters = 4;
3490 // We can't preload 3 characters because there is no machine instruction
3491 // to do that. We can't just load 4 because we could be reading
3492 // beyond the end of the string, which could cause a memory fault.
3493 if (preload_characters == 3) preload_characters = 2;
3495 if (preload_characters > 2) preload_characters = 2;
3498 if (preload_characters > 1) preload_characters = 1;
3500 return preload_characters;
3504 // This class is used when generating the alternatives in a choice node. It
3505 // records the way the alternative is being code generated.
3506 class AlternativeGeneration: public Malloced {
3508 AlternativeGeneration()
3509 : possible_success(),
3510 expects_preload(false),
3512 quick_check_details() { }
3513 Label possible_success;
3514 bool expects_preload;
3516 QuickCheckDetails quick_check_details;
3520 // Creates a list of AlternativeGenerations. If the list has a reasonable
3521 // size then it is on the stack, otherwise the excess is on the heap.
3522 class AlternativeGenerationList {
3524 AlternativeGenerationList(int count, Zone* zone)
3525 : alt_gens_(count, zone) {
3526 for (int i = 0; i < count && i < kAFew; i++) {
3527 alt_gens_.Add(a_few_alt_gens_ + i, zone);
3529 for (int i = kAFew; i < count; i++) {
3530 alt_gens_.Add(new AlternativeGeneration(), zone);
3533 ~AlternativeGenerationList() {
3534 for (int i = kAFew; i < alt_gens_.length(); i++) {
3535 delete alt_gens_[i];
3536 alt_gens_[i] = NULL;
3540 AlternativeGeneration* at(int i) {
3541 return alt_gens_[i];
3545 static const int kAFew = 10;
3546 ZoneList<AlternativeGeneration*> alt_gens_;
3547 AlternativeGeneration a_few_alt_gens_[kAFew];
3551 // The '2' variant is has inclusive from and exclusive to.
3552 // This covers \s as defined in ECMA-262 5.1, 15.10.2.12,
3553 // which include WhiteSpace (7.2) or LineTerminator (7.3) values.
3554 static const int kSpaceRanges[] = { '\t', '\r' + 1, ' ', ' ' + 1,
3555 0x00A0, 0x00A1, 0x1680, 0x1681, 0x180E, 0x180F, 0x2000, 0x200B,
3556 0x2028, 0x202A, 0x202F, 0x2030, 0x205F, 0x2060, 0x3000, 0x3001,
3557 0xFEFF, 0xFF00, 0x10000 };
3558 static const int kSpaceRangeCount = arraysize(kSpaceRanges);
3560 static const int kWordRanges[] = {
3561 '0', '9' + 1, 'A', 'Z' + 1, '_', '_' + 1, 'a', 'z' + 1, 0x10000 };
3562 static const int kWordRangeCount = arraysize(kWordRanges);
3563 static const int kDigitRanges[] = { '0', '9' + 1, 0x10000 };
3564 static const int kDigitRangeCount = arraysize(kDigitRanges);
3565 static const int kSurrogateRanges[] = { 0xd800, 0xe000, 0x10000 };
3566 static const int kSurrogateRangeCount = arraysize(kSurrogateRanges);
3567 static const int kLineTerminatorRanges[] = { 0x000A, 0x000B, 0x000D, 0x000E,
3568 0x2028, 0x202A, 0x10000 };
3569 static const int kLineTerminatorRangeCount = arraysize(kLineTerminatorRanges);
3572 void BoyerMoorePositionInfo::Set(int character) {
3573 SetInterval(Interval(character, character));
3577 void BoyerMoorePositionInfo::SetInterval(const Interval& interval) {
3578 s_ = AddRange(s_, kSpaceRanges, kSpaceRangeCount, interval);
3579 w_ = AddRange(w_, kWordRanges, kWordRangeCount, interval);
3580 d_ = AddRange(d_, kDigitRanges, kDigitRangeCount, interval);
3582 AddRange(surrogate_, kSurrogateRanges, kSurrogateRangeCount, interval);
3583 if (interval.to() - interval.from() >= kMapSize - 1) {
3584 if (map_count_ != kMapSize) {
3585 map_count_ = kMapSize;
3586 for (int i = 0; i < kMapSize; i++) map_->at(i) = true;
3590 for (int i = interval.from(); i <= interval.to(); i++) {
3591 int mod_character = (i & kMask);
3592 if (!map_->at(mod_character)) {
3594 map_->at(mod_character) = true;
3596 if (map_count_ == kMapSize) return;
3601 void BoyerMoorePositionInfo::SetAll() {
3602 s_ = w_ = d_ = kLatticeUnknown;
3603 if (map_count_ != kMapSize) {
3604 map_count_ = kMapSize;
3605 for (int i = 0; i < kMapSize; i++) map_->at(i) = true;
3610 BoyerMooreLookahead::BoyerMooreLookahead(
3611 int length, RegExpCompiler* compiler, Zone* zone)
3613 compiler_(compiler) {
3614 if (compiler->one_byte()) {
3615 max_char_ = String::kMaxOneByteCharCode;
3617 max_char_ = String::kMaxUtf16CodeUnit;
3619 bitmaps_ = new(zone) ZoneList<BoyerMoorePositionInfo*>(length, zone);
3620 for (int i = 0; i < length; i++) {
3621 bitmaps_->Add(new(zone) BoyerMoorePositionInfo(zone), zone);
3626 // Find the longest range of lookahead that has the fewest number of different
3627 // characters that can occur at a given position. Since we are optimizing two
3628 // different parameters at once this is a tradeoff.
3629 bool BoyerMooreLookahead::FindWorthwhileInterval(int* from, int* to) {
3630 int biggest_points = 0;
3631 // If more than 32 characters out of 128 can occur it is unlikely that we can
3632 // be lucky enough to step forwards much of the time.
3633 const int kMaxMax = 32;
3634 for (int max_number_of_chars = 4;
3635 max_number_of_chars < kMaxMax;
3636 max_number_of_chars *= 2) {
3638 FindBestInterval(max_number_of_chars, biggest_points, from, to);
3640 if (biggest_points == 0) return false;
3645 // Find the highest-points range between 0 and length_ where the character
3646 // information is not too vague. 'Too vague' means that there are more than
3647 // max_number_of_chars that can occur at this position. Calculates the number
3648 // of points as the product of width-of-the-range and
3649 // probability-of-finding-one-of-the-characters, where the probability is
3650 // calculated using the frequency distribution of the sample subject string.
3651 int BoyerMooreLookahead::FindBestInterval(
3652 int max_number_of_chars, int old_biggest_points, int* from, int* to) {
3653 int biggest_points = old_biggest_points;
3654 static const int kSize = RegExpMacroAssembler::kTableSize;
3655 for (int i = 0; i < length_; ) {
3656 while (i < length_ && Count(i) > max_number_of_chars) i++;
3657 if (i == length_) break;
3658 int remembered_from = i;
3659 bool union_map[kSize];
3660 for (int j = 0; j < kSize; j++) union_map[j] = false;
3661 while (i < length_ && Count(i) <= max_number_of_chars) {
3662 BoyerMoorePositionInfo* map = bitmaps_->at(i);
3663 for (int j = 0; j < kSize; j++) union_map[j] |= map->at(j);
3667 for (int j = 0; j < kSize; j++) {
3669 // Add 1 to the frequency to give a small per-character boost for
3670 // the cases where our sampling is not good enough and many
3671 // characters have a frequency of zero. This means the frequency
3672 // can theoretically be up to 2*kSize though we treat it mostly as
3673 // a fraction of kSize.
3674 frequency += compiler_->frequency_collator()->Frequency(j) + 1;
3677 // We use the probability of skipping times the distance we are skipping to
3678 // judge the effectiveness of this. Actually we have a cut-off: By
3679 // dividing by 2 we switch off the skipping if the probability of skipping
3680 // is less than 50%. This is because the multibyte mask-and-compare
3681 // skipping in quickcheck is more likely to do well on this case.
3682 bool in_quickcheck_range =
3683 ((i - remembered_from < 4) ||
3684 (compiler_->one_byte() ? remembered_from <= 4 : remembered_from <= 2));
3685 // Called 'probability' but it is only a rough estimate and can actually
3686 // be outside the 0-kSize range.
3687 int probability = (in_quickcheck_range ? kSize / 2 : kSize) - frequency;
3688 int points = (i - remembered_from) * probability;
3689 if (points > biggest_points) {
3690 *from = remembered_from;
3692 biggest_points = points;
3695 return biggest_points;
3699 // Take all the characters that will not prevent a successful match if they
3700 // occur in the subject string in the range between min_lookahead and
3701 // max_lookahead (inclusive) measured from the current position. If the
3702 // character at max_lookahead offset is not one of these characters, then we
3703 // can safely skip forwards by the number of characters in the range.
3704 int BoyerMooreLookahead::GetSkipTable(int min_lookahead,
3706 Handle<ByteArray> boolean_skip_table) {
3707 const int kSize = RegExpMacroAssembler::kTableSize;
3709 const int kSkipArrayEntry = 0;
3710 const int kDontSkipArrayEntry = 1;
3712 for (int i = 0; i < kSize; i++) {
3713 boolean_skip_table->set(i, kSkipArrayEntry);
3715 int skip = max_lookahead + 1 - min_lookahead;
3717 for (int i = max_lookahead; i >= min_lookahead; i--) {
3718 BoyerMoorePositionInfo* map = bitmaps_->at(i);
3719 for (int j = 0; j < kSize; j++) {
3721 boolean_skip_table->set(j, kDontSkipArrayEntry);
3730 // See comment above on the implementation of GetSkipTable.
3731 void BoyerMooreLookahead::EmitSkipInstructions(RegExpMacroAssembler* masm) {
3732 const int kSize = RegExpMacroAssembler::kTableSize;
3734 int min_lookahead = 0;
3735 int max_lookahead = 0;
3737 if (!FindWorthwhileInterval(&min_lookahead, &max_lookahead)) return;
3739 bool found_single_character = false;
3740 int single_character = 0;
3741 for (int i = max_lookahead; i >= min_lookahead; i--) {
3742 BoyerMoorePositionInfo* map = bitmaps_->at(i);
3743 if (map->map_count() > 1 ||
3744 (found_single_character && map->map_count() != 0)) {
3745 found_single_character = false;
3748 for (int j = 0; j < kSize; j++) {
3750 found_single_character = true;
3751 single_character = j;
3757 int lookahead_width = max_lookahead + 1 - min_lookahead;
3759 if (found_single_character && lookahead_width == 1 && max_lookahead < 3) {
3760 // The mask-compare can probably handle this better.
3764 if (found_single_character) {
3767 masm->LoadCurrentCharacter(max_lookahead, &cont, true);
3768 if (max_char_ > kSize) {
3769 masm->CheckCharacterAfterAnd(single_character,
3770 RegExpMacroAssembler::kTableMask,
3773 masm->CheckCharacter(single_character, &cont);
3775 masm->AdvanceCurrentPosition(lookahead_width);
3781 Factory* factory = masm->isolate()->factory();
3782 Handle<ByteArray> boolean_skip_table = factory->NewByteArray(kSize, TENURED);
3783 int skip_distance = GetSkipTable(
3784 min_lookahead, max_lookahead, boolean_skip_table);
3785 DCHECK(skip_distance != 0);
3789 masm->LoadCurrentCharacter(max_lookahead, &cont, true);
3790 masm->CheckBitInTable(boolean_skip_table, &cont);
3791 masm->AdvanceCurrentPosition(skip_distance);
3797 /* Code generation for choice nodes.
3799 * We generate quick checks that do a mask and compare to eliminate a
3800 * choice. If the quick check succeeds then it jumps to the continuation to
3801 * do slow checks and check subsequent nodes. If it fails (the common case)
3802 * it falls through to the next choice.
3804 * Here is the desired flow graph. Nodes directly below each other imply
3805 * fallthrough. Alternatives 1 and 2 have quick checks. Alternative
3806 * 3 doesn't have a quick check so we have to call the slow check.
3807 * Nodes are marked Qn for quick checks and Sn for slow checks. The entire
3808 * regexp continuation is generated directly after the Sn node, up to the
3809 * next GoTo if we decide to reuse some already generated code. Some
3810 * nodes expect preload_characters to be preloaded into the current
3811 * character register. R nodes do this preloading. Vertices are marked
3812 * F for failures and S for success (possible success in the case of quick
3813 * nodes). L, V, < and > are used as arrow heads.
3847 * For greedy loops we push the current position, then generate the code that
3848 * eats the input specially in EmitGreedyLoop. The other choice (the
3849 * continuation) is generated by the normal code in EmitChoices, and steps back
3850 * in the input to the starting position when it fails to match. The loop code
3851 * looks like this (U is the unwind code that steps back in the greedy loop).
3864 * Q2 ---> U----->backtrack
3871 GreedyLoopState::GreedyLoopState(bool not_at_start) {
3872 counter_backtrack_trace_.set_backtrack(&label_);
3873 if (not_at_start) counter_backtrack_trace_.set_at_start(false);
3877 void ChoiceNode::AssertGuardsMentionRegisters(Trace* trace) {
3879 int choice_count = alternatives_->length();
3880 for (int i = 0; i < choice_count - 1; i++) {
3881 GuardedAlternative alternative = alternatives_->at(i);
3882 ZoneList<Guard*>* guards = alternative.guards();
3883 int guard_count = (guards == NULL) ? 0 : guards->length();
3884 for (int j = 0; j < guard_count; j++) {
3885 DCHECK(!trace->mentions_reg(guards->at(j)->reg()));
3892 void ChoiceNode::SetUpPreLoad(RegExpCompiler* compiler,
3893 Trace* current_trace,
3894 PreloadState* state) {
3895 if (state->eats_at_least_ == PreloadState::kEatsAtLeastNotYetInitialized) {
3896 // Save some time by looking at most one machine word ahead.
3897 state->eats_at_least_ =
3898 EatsAtLeast(compiler->one_byte() ? 4 : 2, kRecursionBudget,
3899 current_trace->at_start() == Trace::FALSE_VALUE);
3901 state->preload_characters_ =
3902 CalculatePreloadCharacters(compiler, state->eats_at_least_);
3904 state->preload_is_current_ =
3905 (current_trace->characters_preloaded() == state->preload_characters_);
3906 state->preload_has_checked_bounds_ = state->preload_is_current_;
3910 void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3911 int choice_count = alternatives_->length();
3913 AssertGuardsMentionRegisters(trace);
3915 LimitResult limit_result = LimitVersions(compiler, trace);
3916 if (limit_result == DONE) return;
3917 DCHECK(limit_result == CONTINUE);
3919 // For loop nodes we already flushed (see LoopChoiceNode::Emit), but for
3920 // other choice nodes we only flush if we are out of code size budget.
3921 if (trace->flush_budget() == 0 && trace->actions() != NULL) {
3922 trace->Flush(compiler, this);
3926 RecursionCheck rc(compiler);
3928 PreloadState preload;
3930 GreedyLoopState greedy_loop_state(not_at_start());
3932 int text_length = GreedyLoopTextLengthForAlternative(&alternatives_->at(0));
3933 AlternativeGenerationList alt_gens(choice_count, zone());
3935 if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) {
3936 trace = EmitGreedyLoop(compiler,
3943 // TODO(erikcorry): Delete this. We don't need this label, but it makes us
3944 // match the traces produced pre-cleanup.
3945 Label second_choice;
3946 compiler->macro_assembler()->Bind(&second_choice);
3948 preload.eats_at_least_ = EmitOptimizedUnanchoredSearch(compiler, trace);
3950 EmitChoices(compiler,
3957 // At this point we need to generate slow checks for the alternatives where
3958 // the quick check was inlined. We can recognize these because the associated
3960 int new_flush_budget = trace->flush_budget() / choice_count;
3961 for (int i = 0; i < choice_count; i++) {
3962 AlternativeGeneration* alt_gen = alt_gens.at(i);
3963 Trace new_trace(*trace);
3964 // If there are actions to be flushed we have to limit how many times
3965 // they are flushed. Take the budget of the parent trace and distribute
3966 // it fairly amongst the children.
3967 if (new_trace.actions() != NULL) {
3968 new_trace.set_flush_budget(new_flush_budget);
3970 bool next_expects_preload =
3971 i == choice_count - 1 ? false : alt_gens.at(i + 1)->expects_preload;
3972 EmitOutOfLineContinuation(compiler,
3974 alternatives_->at(i),
3976 preload.preload_characters_,
3977 next_expects_preload);
3982 Trace* ChoiceNode::EmitGreedyLoop(RegExpCompiler* compiler,
3984 AlternativeGenerationList* alt_gens,
3985 PreloadState* preload,
3986 GreedyLoopState* greedy_loop_state,
3988 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
3989 // Here we have special handling for greedy loops containing only text nodes
3990 // and other simple nodes. These are handled by pushing the current
3991 // position on the stack and then incrementing the current position each
3992 // time around the switch. On backtrack we decrement the current position
3993 // and check it against the pushed value. This avoids pushing backtrack
3994 // information for each iteration of the loop, which could take up a lot of
3996 DCHECK(trace->stop_node() == NULL);
3997 macro_assembler->PushCurrentPosition();
3998 Label greedy_match_failed;
3999 Trace greedy_match_trace;
4000 if (not_at_start()) greedy_match_trace.set_at_start(false);
4001 greedy_match_trace.set_backtrack(&greedy_match_failed);
4003 macro_assembler->Bind(&loop_label);
4004 greedy_match_trace.set_stop_node(this);
4005 greedy_match_trace.set_loop_label(&loop_label);
4006 alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
4007 macro_assembler->Bind(&greedy_match_failed);
4009 Label second_choice; // For use in greedy matches.
4010 macro_assembler->Bind(&second_choice);
4012 Trace* new_trace = greedy_loop_state->counter_backtrack_trace();
4014 EmitChoices(compiler,
4020 macro_assembler->Bind(greedy_loop_state->label());
4021 // If we have unwound to the bottom then backtrack.
4022 macro_assembler->CheckGreedyLoop(trace->backtrack());
4023 // Otherwise try the second priority at an earlier position.
4024 macro_assembler->AdvanceCurrentPosition(-text_length);
4025 macro_assembler->GoTo(&second_choice);
4029 int ChoiceNode::EmitOptimizedUnanchoredSearch(RegExpCompiler* compiler,
4031 int eats_at_least = PreloadState::kEatsAtLeastNotYetInitialized;
4032 if (alternatives_->length() != 2) return eats_at_least;
4034 GuardedAlternative alt1 = alternatives_->at(1);
4035 if (alt1.guards() != NULL && alt1.guards()->length() != 0) {
4036 return eats_at_least;
4038 RegExpNode* eats_anything_node = alt1.node();
4039 if (eats_anything_node->GetSuccessorOfOmnivorousTextNode(compiler) != this) {
4040 return eats_at_least;
4043 // Really we should be creating a new trace when we execute this function,
4044 // but there is no need, because the code it generates cannot backtrack, and
4045 // we always arrive here with a trivial trace (since it's the entry to a
4046 // loop. That also implies that there are no preloaded characters, which is
4047 // good, because it means we won't be violating any assumptions by
4048 // overwriting those characters with new load instructions.
4049 DCHECK(trace->is_trivial());
4051 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
4052 // At this point we know that we are at a non-greedy loop that will eat
4053 // any character one at a time. Any non-anchored regexp has such a
4054 // loop prepended to it in order to find where it starts. We look for
4055 // a pattern of the form ...abc... where we can look 6 characters ahead
4056 // and step forwards 3 if the character is not one of abc. Abc need
4057 // not be atoms, they can be any reasonably limited character class or
4058 // small alternation.
4059 BoyerMooreLookahead* bm = bm_info(false);
4061 eats_at_least = Min(kMaxLookaheadForBoyerMoore,
4062 EatsAtLeast(kMaxLookaheadForBoyerMoore,
4065 if (eats_at_least >= 1) {
4066 bm = new(zone()) BoyerMooreLookahead(eats_at_least,
4069 GuardedAlternative alt0 = alternatives_->at(0);
4070 alt0.node()->FillInBMInfo(0, kRecursionBudget, bm, false);
4074 bm->EmitSkipInstructions(macro_assembler);
4076 return eats_at_least;
4080 void ChoiceNode::EmitChoices(RegExpCompiler* compiler,
4081 AlternativeGenerationList* alt_gens,
4084 PreloadState* preload) {
4085 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
4086 SetUpPreLoad(compiler, trace, preload);
4088 // For now we just call all choices one after the other. The idea ultimately
4089 // is to use the Dispatch table to try only the relevant ones.
4090 int choice_count = alternatives_->length();
4092 int new_flush_budget = trace->flush_budget() / choice_count;
4094 for (int i = first_choice; i < choice_count; i++) {
4095 bool is_last = i == choice_count - 1;
4096 bool fall_through_on_failure = !is_last;
4097 GuardedAlternative alternative = alternatives_->at(i);
4098 AlternativeGeneration* alt_gen = alt_gens->at(i);
4099 alt_gen->quick_check_details.set_characters(preload->preload_characters_);
4100 ZoneList<Guard*>* guards = alternative.guards();
4101 int guard_count = (guards == NULL) ? 0 : guards->length();
4102 Trace new_trace(*trace);
4103 new_trace.set_characters_preloaded(preload->preload_is_current_ ?
4104 preload->preload_characters_ :
4106 if (preload->preload_has_checked_bounds_) {
4107 new_trace.set_bound_checked_up_to(preload->preload_characters_);
4109 new_trace.quick_check_performed()->Clear();
4110 if (not_at_start_) new_trace.set_at_start(Trace::FALSE_VALUE);
4112 new_trace.set_backtrack(&alt_gen->after);
4114 alt_gen->expects_preload = preload->preload_is_current_;
4115 bool generate_full_check_inline = false;
4116 if (compiler->optimize() &&
4117 try_to_emit_quick_check_for_alternative(i == 0) &&
4118 alternative.node()->EmitQuickCheck(
4119 compiler, trace, &new_trace, preload->preload_has_checked_bounds_,
4120 &alt_gen->possible_success, &alt_gen->quick_check_details,
4121 fall_through_on_failure)) {
4122 // Quick check was generated for this choice.
4123 preload->preload_is_current_ = true;
4124 preload->preload_has_checked_bounds_ = true;
4125 // If we generated the quick check to fall through on possible success,
4126 // we now need to generate the full check inline.
4127 if (!fall_through_on_failure) {
4128 macro_assembler->Bind(&alt_gen->possible_success);
4129 new_trace.set_quick_check_performed(&alt_gen->quick_check_details);
4130 new_trace.set_characters_preloaded(preload->preload_characters_);
4131 new_trace.set_bound_checked_up_to(preload->preload_characters_);
4132 generate_full_check_inline = true;
4134 } else if (alt_gen->quick_check_details.cannot_match()) {
4135 if (!fall_through_on_failure) {
4136 macro_assembler->GoTo(trace->backtrack());
4140 // No quick check was generated. Put the full code here.
4141 // If this is not the first choice then there could be slow checks from
4142 // previous cases that go here when they fail. There's no reason to
4143 // insist that they preload characters since the slow check we are about
4144 // to generate probably can't use it.
4145 if (i != first_choice) {
4146 alt_gen->expects_preload = false;
4147 new_trace.InvalidateCurrentCharacter();
4149 generate_full_check_inline = true;
4151 if (generate_full_check_inline) {
4152 if (new_trace.actions() != NULL) {
4153 new_trace.set_flush_budget(new_flush_budget);
4155 for (int j = 0; j < guard_count; j++) {
4156 GenerateGuard(macro_assembler, guards->at(j), &new_trace);
4158 alternative.node()->Emit(compiler, &new_trace);
4159 preload->preload_is_current_ = false;
4161 macro_assembler->Bind(&alt_gen->after);
4166 void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
4168 GuardedAlternative alternative,
4169 AlternativeGeneration* alt_gen,
4170 int preload_characters,
4171 bool next_expects_preload) {
4172 if (!alt_gen->possible_success.is_linked()) return;
4174 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
4175 macro_assembler->Bind(&alt_gen->possible_success);
4176 Trace out_of_line_trace(*trace);
4177 out_of_line_trace.set_characters_preloaded(preload_characters);
4178 out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details);
4179 if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE_VALUE);
4180 ZoneList<Guard*>* guards = alternative.guards();
4181 int guard_count = (guards == NULL) ? 0 : guards->length();
4182 if (next_expects_preload) {
4183 Label reload_current_char;
4184 out_of_line_trace.set_backtrack(&reload_current_char);
4185 for (int j = 0; j < guard_count; j++) {
4186 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
4188 alternative.node()->Emit(compiler, &out_of_line_trace);
4189 macro_assembler->Bind(&reload_current_char);
4190 // Reload the current character, since the next quick check expects that.
4191 // We don't need to check bounds here because we only get into this
4192 // code through a quick check which already did the checked load.
4193 macro_assembler->LoadCurrentCharacter(trace->cp_offset(),
4196 preload_characters);
4197 macro_assembler->GoTo(&(alt_gen->after));
4199 out_of_line_trace.set_backtrack(&(alt_gen->after));
4200 for (int j = 0; j < guard_count; j++) {
4201 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
4203 alternative.node()->Emit(compiler, &out_of_line_trace);
4208 void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
4209 RegExpMacroAssembler* assembler = compiler->macro_assembler();
4210 LimitResult limit_result = LimitVersions(compiler, trace);
4211 if (limit_result == DONE) return;
4212 DCHECK(limit_result == CONTINUE);
4214 RecursionCheck rc(compiler);
4216 switch (action_type_) {
4217 case STORE_POSITION: {
4218 Trace::DeferredCapture
4219 new_capture(data_.u_position_register.reg,
4220 data_.u_position_register.is_capture,
4222 Trace new_trace = *trace;
4223 new_trace.add_action(&new_capture);
4224 on_success()->Emit(compiler, &new_trace);
4227 case INCREMENT_REGISTER: {
4228 Trace::DeferredIncrementRegister
4229 new_increment(data_.u_increment_register.reg);
4230 Trace new_trace = *trace;
4231 new_trace.add_action(&new_increment);
4232 on_success()->Emit(compiler, &new_trace);
4235 case SET_REGISTER: {
4236 Trace::DeferredSetRegister
4237 new_set(data_.u_store_register.reg, data_.u_store_register.value);
4238 Trace new_trace = *trace;
4239 new_trace.add_action(&new_set);
4240 on_success()->Emit(compiler, &new_trace);
4243 case CLEAR_CAPTURES: {
4244 Trace::DeferredClearCaptures
4245 new_capture(Interval(data_.u_clear_captures.range_from,
4246 data_.u_clear_captures.range_to));
4247 Trace new_trace = *trace;
4248 new_trace.add_action(&new_capture);
4249 on_success()->Emit(compiler, &new_trace);
4252 case BEGIN_SUBMATCH:
4253 if (!trace->is_trivial()) {
4254 trace->Flush(compiler, this);
4256 assembler->WriteCurrentPositionToRegister(
4257 data_.u_submatch.current_position_register, 0);
4258 assembler->WriteStackPointerToRegister(
4259 data_.u_submatch.stack_pointer_register);
4260 on_success()->Emit(compiler, trace);
4263 case EMPTY_MATCH_CHECK: {
4264 int start_pos_reg = data_.u_empty_match_check.start_register;
4266 int rep_reg = data_.u_empty_match_check.repetition_register;
4267 bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister);
4268 bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos);
4269 if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) {
4270 // If we know we haven't advanced and there is no minimum we
4271 // can just backtrack immediately.
4272 assembler->GoTo(trace->backtrack());
4273 } else if (know_dist && stored_pos < trace->cp_offset()) {
4274 // If we know we've advanced we can generate the continuation
4276 on_success()->Emit(compiler, trace);
4277 } else if (!trace->is_trivial()) {
4278 trace->Flush(compiler, this);
4280 Label skip_empty_check;
4281 // If we have a minimum number of repetitions we check the current
4282 // number first and skip the empty check if it's not enough.
4284 int limit = data_.u_empty_match_check.repetition_limit;
4285 assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check);
4287 // If the match is empty we bail out, otherwise we fall through
4288 // to the on-success continuation.
4289 assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register,
4290 trace->backtrack());
4291 assembler->Bind(&skip_empty_check);
4292 on_success()->Emit(compiler, trace);
4296 case POSITIVE_SUBMATCH_SUCCESS: {
4297 if (!trace->is_trivial()) {
4298 trace->Flush(compiler, this);
4301 assembler->ReadCurrentPositionFromRegister(
4302 data_.u_submatch.current_position_register);
4303 assembler->ReadStackPointerFromRegister(
4304 data_.u_submatch.stack_pointer_register);
4305 int clear_register_count = data_.u_submatch.clear_register_count;
4306 if (clear_register_count == 0) {
4307 on_success()->Emit(compiler, trace);
4310 int clear_registers_from = data_.u_submatch.clear_register_from;
4311 Label clear_registers_backtrack;
4312 Trace new_trace = *trace;
4313 new_trace.set_backtrack(&clear_registers_backtrack);
4314 on_success()->Emit(compiler, &new_trace);
4316 assembler->Bind(&clear_registers_backtrack);
4317 int clear_registers_to = clear_registers_from + clear_register_count - 1;
4318 assembler->ClearRegisters(clear_registers_from, clear_registers_to);
4320 DCHECK(trace->backtrack() == NULL);
4321 assembler->Backtrack();
4330 void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
4331 RegExpMacroAssembler* assembler = compiler->macro_assembler();
4332 if (!trace->is_trivial()) {
4333 trace->Flush(compiler, this);
4337 LimitResult limit_result = LimitVersions(compiler, trace);
4338 if (limit_result == DONE) return;
4339 DCHECK(limit_result == CONTINUE);
4341 RecursionCheck rc(compiler);
4343 DCHECK_EQ(start_reg_ + 1, end_reg_);
4344 if (compiler->ignore_case()) {
4345 assembler->CheckNotBackReferenceIgnoreCase(start_reg_,
4346 trace->backtrack());
4348 assembler->CheckNotBackReference(start_reg_, trace->backtrack());
4350 on_success()->Emit(compiler, trace);
4354 // -------------------------------------------------------------------
4361 class DotPrinter: public NodeVisitor {
4363 DotPrinter(std::ostream& os, bool ignore_case) // NOLINT
4365 ignore_case_(ignore_case) {}
4366 void PrintNode(const char* label, RegExpNode* node);
4367 void Visit(RegExpNode* node);
4368 void PrintAttributes(RegExpNode* from);
4369 void PrintOnFailure(RegExpNode* from, RegExpNode* to);
4370 #define DECLARE_VISIT(Type) \
4371 virtual void Visit##Type(Type##Node* that);
4372 FOR_EACH_NODE_TYPE(DECLARE_VISIT)
4373 #undef DECLARE_VISIT
4380 void DotPrinter::PrintNode(const char* label, RegExpNode* node) {
4381 os_ << "digraph G {\n graph [label=\"";
4382 for (int i = 0; label[i]; i++) {
4397 os_ << "}" << std::endl;
4401 void DotPrinter::Visit(RegExpNode* node) {
4402 if (node->info()->visited) return;
4403 node->info()->visited = true;
4408 void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
4409 os_ << " n" << from << " -> n" << on_failure << " [style=dotted];\n";
4414 class TableEntryBodyPrinter {
4416 TableEntryBodyPrinter(std::ostream& os, ChoiceNode* choice) // NOLINT
4419 void Call(uc16 from, DispatchTable::Entry entry) {
4420 OutSet* out_set = entry.out_set();
4421 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
4422 if (out_set->Get(i)) {
4423 os_ << " n" << choice() << ":s" << from << "o" << i << " -> n"
4424 << choice()->alternatives()->at(i).node() << ";\n";
4429 ChoiceNode* choice() { return choice_; }
4431 ChoiceNode* choice_;
4435 class TableEntryHeaderPrinter {
4437 explicit TableEntryHeaderPrinter(std::ostream& os) // NOLINT
4440 void Call(uc16 from, DispatchTable::Entry entry) {
4446 os_ << "{\\" << AsUC16(from) << "-\\" << AsUC16(entry.to()) << "|{";
4447 OutSet* out_set = entry.out_set();
4449 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
4450 if (out_set->Get(i)) {
4451 if (priority > 0) os_ << "|";
4452 os_ << "<s" << from << "o" << i << "> " << priority;
4465 class AttributePrinter {
4467 explicit AttributePrinter(std::ostream& os) // NOLINT
4470 void PrintSeparator() {
4477 void PrintBit(const char* name, bool value) {
4480 os_ << "{" << name << "}";
4482 void PrintPositive(const char* name, int value) {
4483 if (value < 0) return;
4485 os_ << "{" << name << "|" << value << "}";
4494 void DotPrinter::PrintAttributes(RegExpNode* that) {
4495 os_ << " a" << that << " [shape=Mrecord, color=grey, fontcolor=grey, "
4496 << "margin=0.1, fontsize=10, label=\"{";
4497 AttributePrinter printer(os_);
4498 NodeInfo* info = that->info();
4499 printer.PrintBit("NI", info->follows_newline_interest);
4500 printer.PrintBit("WI", info->follows_word_interest);
4501 printer.PrintBit("SI", info->follows_start_interest);
4502 Label* label = that->label();
4503 if (label->is_bound())
4504 printer.PrintPositive("@", label->pos());
4506 << " a" << that << " -> n" << that
4507 << " [style=dashed, color=grey, arrowhead=none];\n";
4511 static const bool kPrintDispatchTable = false;
4512 void DotPrinter::VisitChoice(ChoiceNode* that) {
4513 if (kPrintDispatchTable) {
4514 os_ << " n" << that << " [shape=Mrecord, label=\"";
4515 TableEntryHeaderPrinter header_printer(os_);
4516 that->GetTable(ignore_case_)->ForEach(&header_printer);
4518 PrintAttributes(that);
4519 TableEntryBodyPrinter body_printer(os_, that);
4520 that->GetTable(ignore_case_)->ForEach(&body_printer);
4522 os_ << " n" << that << " [shape=Mrecord, label=\"?\"];\n";
4523 for (int i = 0; i < that->alternatives()->length(); i++) {
4524 GuardedAlternative alt = that->alternatives()->at(i);
4525 os_ << " n" << that << " -> n" << alt.node();
4528 for (int i = 0; i < that->alternatives()->length(); i++) {
4529 GuardedAlternative alt = that->alternatives()->at(i);
4530 alt.node()->Accept(this);
4535 void DotPrinter::VisitText(TextNode* that) {
4536 Zone* zone = that->zone();
4537 os_ << " n" << that << " [label=\"";
4538 for (int i = 0; i < that->elements()->length(); i++) {
4539 if (i > 0) os_ << " ";
4540 TextElement elm = that->elements()->at(i);
4541 switch (elm.text_type()) {
4542 case TextElement::ATOM: {
4543 Vector<const uc16> data = elm.atom()->data();
4544 for (int i = 0; i < data.length(); i++) {
4545 os_ << static_cast<char>(data[i]);
4549 case TextElement::CHAR_CLASS: {
4550 RegExpCharacterClass* node = elm.char_class();
4552 if (node->is_negated()) os_ << "^";
4553 for (int j = 0; j < node->ranges(zone)->length(); j++) {
4554 CharacterRange range = node->ranges(zone)->at(j);
4555 os_ << AsUC16(range.from()) << "-" << AsUC16(range.to());
4564 os_ << "\", shape=box, peripheries=2];\n";
4565 PrintAttributes(that);
4566 os_ << " n" << that << " -> n" << that->on_success() << ";\n";
4567 Visit(that->on_success());
4571 void DotPrinter::VisitBackReference(BackReferenceNode* that) {
4572 os_ << " n" << that << " [label=\"$" << that->start_register() << "..$"
4573 << that->end_register() << "\", shape=doubleoctagon];\n";
4574 PrintAttributes(that);
4575 os_ << " n" << that << " -> n" << that->on_success() << ";\n";
4576 Visit(that->on_success());
4580 void DotPrinter::VisitEnd(EndNode* that) {
4581 os_ << " n" << that << " [style=bold, shape=point];\n";
4582 PrintAttributes(that);
4586 void DotPrinter::VisitAssertion(AssertionNode* that) {
4587 os_ << " n" << that << " [";
4588 switch (that->assertion_type()) {
4589 case AssertionNode::AT_END:
4590 os_ << "label=\"$\", shape=septagon";
4592 case AssertionNode::AT_START:
4593 os_ << "label=\"^\", shape=septagon";
4595 case AssertionNode::AT_BOUNDARY:
4596 os_ << "label=\"\\b\", shape=septagon";
4598 case AssertionNode::AT_NON_BOUNDARY:
4599 os_ << "label=\"\\B\", shape=septagon";
4601 case AssertionNode::AFTER_NEWLINE:
4602 os_ << "label=\"(?<=\\n)\", shape=septagon";
4606 PrintAttributes(that);
4607 RegExpNode* successor = that->on_success();
4608 os_ << " n" << that << " -> n" << successor << ";\n";
4613 void DotPrinter::VisitAction(ActionNode* that) {
4614 os_ << " n" << that << " [";
4615 switch (that->action_type_) {
4616 case ActionNode::SET_REGISTER:
4617 os_ << "label=\"$" << that->data_.u_store_register.reg
4618 << ":=" << that->data_.u_store_register.value << "\", shape=octagon";
4620 case ActionNode::INCREMENT_REGISTER:
4621 os_ << "label=\"$" << that->data_.u_increment_register.reg
4622 << "++\", shape=octagon";
4624 case ActionNode::STORE_POSITION:
4625 os_ << "label=\"$" << that->data_.u_position_register.reg
4626 << ":=$pos\", shape=octagon";
4628 case ActionNode::BEGIN_SUBMATCH:
4629 os_ << "label=\"$" << that->data_.u_submatch.current_position_register
4630 << ":=$pos,begin\", shape=septagon";
4632 case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
4633 os_ << "label=\"escape\", shape=septagon";
4635 case ActionNode::EMPTY_MATCH_CHECK:
4636 os_ << "label=\"$" << that->data_.u_empty_match_check.start_register
4637 << "=$pos?,$" << that->data_.u_empty_match_check.repetition_register
4638 << "<" << that->data_.u_empty_match_check.repetition_limit
4639 << "?\", shape=septagon";
4641 case ActionNode::CLEAR_CAPTURES: {
4642 os_ << "label=\"clear $" << that->data_.u_clear_captures.range_from
4643 << " to $" << that->data_.u_clear_captures.range_to
4644 << "\", shape=septagon";
4649 PrintAttributes(that);
4650 RegExpNode* successor = that->on_success();
4651 os_ << " n" << that << " -> n" << successor << ";\n";
4656 class DispatchTableDumper {
4658 explicit DispatchTableDumper(std::ostream& os) : os_(os) {}
4659 void Call(uc16 key, DispatchTable::Entry entry);
4665 void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) {
4666 os_ << "[" << AsUC16(key) << "-" << AsUC16(entry.to()) << "]: {";
4667 OutSet* set = entry.out_set();
4669 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
4683 void DispatchTable::Dump() {
4684 OFStream os(stderr);
4685 DispatchTableDumper dumper(os);
4686 tree()->ForEach(&dumper);
4690 void RegExpEngine::DotPrint(const char* label,
4693 OFStream os(stdout);
4694 DotPrinter printer(os, ignore_case);
4695 printer.PrintNode(label, node);
4702 // -------------------------------------------------------------------
4703 // Tree to graph conversion
4705 RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
4706 RegExpNode* on_success) {
4707 ZoneList<TextElement>* elms =
4708 new(compiler->zone()) ZoneList<TextElement>(1, compiler->zone());
4709 elms->Add(TextElement::Atom(this), compiler->zone());
4710 return new(compiler->zone()) TextNode(elms, on_success);
4714 RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
4715 RegExpNode* on_success) {
4716 return new(compiler->zone()) TextNode(elements(), on_success);
4720 static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
4721 const int* special_class,
4723 length--; // Remove final 0x10000.
4724 DCHECK(special_class[length] == 0x10000);
4725 DCHECK(ranges->length() != 0);
4726 DCHECK(length != 0);
4727 DCHECK(special_class[0] != 0);
4728 if (ranges->length() != (length >> 1) + 1) {
4731 CharacterRange range = ranges->at(0);
4732 if (range.from() != 0) {
4735 for (int i = 0; i < length; i += 2) {
4736 if (special_class[i] != (range.to() + 1)) {
4739 range = ranges->at((i >> 1) + 1);
4740 if (special_class[i+1] != range.from()) {
4744 if (range.to() != 0xffff) {
4751 static bool CompareRanges(ZoneList<CharacterRange>* ranges,
4752 const int* special_class,
4754 length--; // Remove final 0x10000.
4755 DCHECK(special_class[length] == 0x10000);
4756 if (ranges->length() * 2 != length) {
4759 for (int i = 0; i < length; i += 2) {
4760 CharacterRange range = ranges->at(i >> 1);
4761 if (range.from() != special_class[i] ||
4762 range.to() != special_class[i + 1] - 1) {
4770 bool RegExpCharacterClass::is_standard(Zone* zone) {
4771 // TODO(lrn): Remove need for this function, by not throwing away information
4776 if (set_.is_standard()) {
4779 if (CompareRanges(set_.ranges(zone), kSpaceRanges, kSpaceRangeCount)) {
4780 set_.set_standard_set_type('s');
4783 if (CompareInverseRanges(set_.ranges(zone), kSpaceRanges, kSpaceRangeCount)) {
4784 set_.set_standard_set_type('S');
4787 if (CompareInverseRanges(set_.ranges(zone),
4788 kLineTerminatorRanges,
4789 kLineTerminatorRangeCount)) {
4790 set_.set_standard_set_type('.');
4793 if (CompareRanges(set_.ranges(zone),
4794 kLineTerminatorRanges,
4795 kLineTerminatorRangeCount)) {
4796 set_.set_standard_set_type('n');
4799 if (CompareRanges(set_.ranges(zone), kWordRanges, kWordRangeCount)) {
4800 set_.set_standard_set_type('w');
4803 if (CompareInverseRanges(set_.ranges(zone), kWordRanges, kWordRangeCount)) {
4804 set_.set_standard_set_type('W');
4811 RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
4812 RegExpNode* on_success) {
4813 return new(compiler->zone()) TextNode(this, on_success);
4817 RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
4818 RegExpNode* on_success) {
4819 ZoneList<RegExpTree*>* alternatives = this->alternatives();
4820 int length = alternatives->length();
4821 ChoiceNode* result =
4822 new(compiler->zone()) ChoiceNode(length, compiler->zone());
4823 for (int i = 0; i < length; i++) {
4824 GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler,
4826 result->AddAlternative(alternative);
4832 RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
4833 RegExpNode* on_success) {
4834 return ToNode(min(),
4843 // Scoped object to keep track of how much we unroll quantifier loops in the
4844 // regexp graph generator.
4845 class RegExpExpansionLimiter {
4847 static const int kMaxExpansionFactor = 6;
4848 RegExpExpansionLimiter(RegExpCompiler* compiler, int factor)
4849 : compiler_(compiler),
4850 saved_expansion_factor_(compiler->current_expansion_factor()),
4851 ok_to_expand_(saved_expansion_factor_ <= kMaxExpansionFactor) {
4853 if (ok_to_expand_) {
4854 if (factor > kMaxExpansionFactor) {
4855 // Avoid integer overflow of the current expansion factor.
4856 ok_to_expand_ = false;
4857 compiler->set_current_expansion_factor(kMaxExpansionFactor + 1);
4859 int new_factor = saved_expansion_factor_ * factor;
4860 ok_to_expand_ = (new_factor <= kMaxExpansionFactor);
4861 compiler->set_current_expansion_factor(new_factor);
4866 ~RegExpExpansionLimiter() {
4867 compiler_->set_current_expansion_factor(saved_expansion_factor_);
4870 bool ok_to_expand() { return ok_to_expand_; }
4873 RegExpCompiler* compiler_;
4874 int saved_expansion_factor_;
4877 DISALLOW_IMPLICIT_CONSTRUCTORS(RegExpExpansionLimiter);
4881 RegExpNode* RegExpQuantifier::ToNode(int min,
4885 RegExpCompiler* compiler,
4886 RegExpNode* on_success,
4887 bool not_at_start) {
4888 // x{f, t} becomes this:
4894 // (r=0)-->(?)---/ [if r < t]
4896 // [if r >= f] \----> ...
4899 // 15.10.2.5 RepeatMatcher algorithm.
4900 // The parser has already eliminated the case where max is 0. In the case
4901 // where max_match is zero the parser has removed the quantifier if min was
4902 // > 0 and removed the atom if min was 0. See AddQuantifierToAtom.
4904 // If we know that we cannot match zero length then things are a little
4905 // simpler since we don't need to make the special zero length match check
4906 // from step 2.1. If the min and max are small we can unroll a little in
4908 static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,}
4909 static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3}
4910 if (max == 0) return on_success; // This can happen due to recursion.
4911 bool body_can_be_empty = (body->min_match() == 0);
4912 int body_start_reg = RegExpCompiler::kNoRegister;
4913 Interval capture_registers = body->CaptureRegisters();
4914 bool needs_capture_clearing = !capture_registers.is_empty();
4915 Zone* zone = compiler->zone();
4917 if (body_can_be_empty) {
4918 body_start_reg = compiler->AllocateRegister();
4919 } else if (compiler->optimize() && !needs_capture_clearing) {
4920 // Only unroll if there are no captures and the body can't be
4923 RegExpExpansionLimiter limiter(
4924 compiler, min + ((max != min) ? 1 : 0));
4925 if (min > 0 && min <= kMaxUnrolledMinMatches && limiter.ok_to_expand()) {
4926 int new_max = (max == kInfinity) ? max : max - min;
4927 // Recurse once to get the loop or optional matches after the fixed
4929 RegExpNode* answer = ToNode(
4930 0, new_max, is_greedy, body, compiler, on_success, true);
4931 // Unroll the forced matches from 0 to min. This can cause chains of
4932 // TextNodes (which the parser does not generate). These should be
4933 // combined if it turns out they hinder good code generation.
4934 for (int i = 0; i < min; i++) {
4935 answer = body->ToNode(compiler, answer);
4940 if (max <= kMaxUnrolledMaxMatches && min == 0) {
4941 DCHECK(max > 0); // Due to the 'if' above.
4942 RegExpExpansionLimiter limiter(compiler, max);
4943 if (limiter.ok_to_expand()) {
4944 // Unroll the optional matches up to max.
4945 RegExpNode* answer = on_success;
4946 for (int i = 0; i < max; i++) {
4947 ChoiceNode* alternation = new(zone) ChoiceNode(2, zone);
4949 alternation->AddAlternative(
4950 GuardedAlternative(body->ToNode(compiler, answer)));
4951 alternation->AddAlternative(GuardedAlternative(on_success));
4953 alternation->AddAlternative(GuardedAlternative(on_success));
4954 alternation->AddAlternative(
4955 GuardedAlternative(body->ToNode(compiler, answer)));
4957 answer = alternation;
4958 if (not_at_start) alternation->set_not_at_start();
4964 bool has_min = min > 0;
4965 bool has_max = max < RegExpTree::kInfinity;
4966 bool needs_counter = has_min || has_max;
4967 int reg_ctr = needs_counter
4968 ? compiler->AllocateRegister()
4969 : RegExpCompiler::kNoRegister;
4970 LoopChoiceNode* center = new(zone) LoopChoiceNode(body->min_match() == 0,
4972 if (not_at_start) center->set_not_at_start();
4973 RegExpNode* loop_return = needs_counter
4974 ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
4975 : static_cast<RegExpNode*>(center);
4976 if (body_can_be_empty) {
4977 // If the body can be empty we need to check if it was and then
4979 loop_return = ActionNode::EmptyMatchCheck(body_start_reg,
4984 RegExpNode* body_node = body->ToNode(compiler, loop_return);
4985 if (body_can_be_empty) {
4986 // If the body can be empty we need to store the start position
4987 // so we can bail out if it was empty.
4988 body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
4990 if (needs_capture_clearing) {
4991 // Before entering the body of this loop we need to clear captures.
4992 body_node = ActionNode::ClearCaptures(capture_registers, body_node);
4994 GuardedAlternative body_alt(body_node);
4997 new(zone) Guard(reg_ctr, Guard::LT, max);
4998 body_alt.AddGuard(body_guard, zone);
5000 GuardedAlternative rest_alt(on_success);
5002 Guard* rest_guard = new(compiler->zone()) Guard(reg_ctr, Guard::GEQ, min);
5003 rest_alt.AddGuard(rest_guard, zone);
5006 center->AddLoopAlternative(body_alt);
5007 center->AddContinueAlternative(rest_alt);
5009 center->AddContinueAlternative(rest_alt);
5010 center->AddLoopAlternative(body_alt);
5012 if (needs_counter) {
5013 return ActionNode::SetRegister(reg_ctr, 0, center);
5020 RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
5021 RegExpNode* on_success) {
5023 Zone* zone = compiler->zone();
5025 switch (assertion_type()) {
5027 return AssertionNode::AfterNewline(on_success);
5028 case START_OF_INPUT:
5029 return AssertionNode::AtStart(on_success);
5031 return AssertionNode::AtBoundary(on_success);
5033 return AssertionNode::AtNonBoundary(on_success);
5035 return AssertionNode::AtEnd(on_success);
5037 // Compile $ in multiline regexps as an alternation with a positive
5038 // lookahead in one side and an end-of-input on the other side.
5039 // We need two registers for the lookahead.
5040 int stack_pointer_register = compiler->AllocateRegister();
5041 int position_register = compiler->AllocateRegister();
5042 // The ChoiceNode to distinguish between a newline and end-of-input.
5043 ChoiceNode* result = new(zone) ChoiceNode(2, zone);
5044 // Create a newline atom.
5045 ZoneList<CharacterRange>* newline_ranges =
5046 new(zone) ZoneList<CharacterRange>(3, zone);
5047 CharacterRange::AddClassEscape('n', newline_ranges, zone);
5048 RegExpCharacterClass* newline_atom = new(zone) RegExpCharacterClass('n');
5049 TextNode* newline_matcher = new(zone) TextNode(
5051 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
5053 0, // No captures inside.
5054 -1, // Ignored if no captures.
5056 // Create an end-of-input matcher.
5057 RegExpNode* end_of_line = ActionNode::BeginSubmatch(
5058 stack_pointer_register,
5061 // Add the two alternatives to the ChoiceNode.
5062 GuardedAlternative eol_alternative(end_of_line);
5063 result->AddAlternative(eol_alternative);
5064 GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
5065 result->AddAlternative(end_alternative);
5075 RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
5076 RegExpNode* on_success) {
5077 return new(compiler->zone())
5078 BackReferenceNode(RegExpCapture::StartRegister(index()),
5079 RegExpCapture::EndRegister(index()),
5084 RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
5085 RegExpNode* on_success) {
5090 RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler,
5091 RegExpNode* on_success) {
5092 int stack_pointer_register = compiler->AllocateRegister();
5093 int position_register = compiler->AllocateRegister();
5095 const int registers_per_capture = 2;
5096 const int register_of_first_capture = 2;
5097 int register_count = capture_count_ * registers_per_capture;
5098 int register_start =
5099 register_of_first_capture + capture_from_ * registers_per_capture;
5101 RegExpNode* success;
5102 if (is_positive()) {
5103 RegExpNode* node = ActionNode::BeginSubmatch(
5104 stack_pointer_register,
5108 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
5115 // We use a ChoiceNode for a negative lookahead because it has most of
5116 // the characteristics we need. It has the body of the lookahead as its
5117 // first alternative and the expression after the lookahead of the second
5118 // alternative. If the first alternative succeeds then the
5119 // NegativeSubmatchSuccess will unwind the stack including everything the
5120 // choice node set up and backtrack. If the first alternative fails then
5121 // the second alternative is tried, which is exactly the desired result
5122 // for a negative lookahead. The NegativeLookaheadChoiceNode is a special
5123 // ChoiceNode that knows to ignore the first exit when calculating quick
5125 Zone* zone = compiler->zone();
5127 GuardedAlternative body_alt(
5130 success = new(zone) NegativeSubmatchSuccess(stack_pointer_register,
5135 ChoiceNode* choice_node =
5136 new(zone) NegativeLookaheadChoiceNode(body_alt,
5137 GuardedAlternative(on_success),
5139 return ActionNode::BeginSubmatch(stack_pointer_register,
5146 RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
5147 RegExpNode* on_success) {
5148 return ToNode(body(), index(), compiler, on_success);
5152 RegExpNode* RegExpCapture::ToNode(RegExpTree* body,
5154 RegExpCompiler* compiler,
5155 RegExpNode* on_success) {
5156 int start_reg = RegExpCapture::StartRegister(index);
5157 int end_reg = RegExpCapture::EndRegister(index);
5158 RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
5159 RegExpNode* body_node = body->ToNode(compiler, store_end);
5160 return ActionNode::StorePosition(start_reg, true, body_node);
5164 RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
5165 RegExpNode* on_success) {
5166 ZoneList<RegExpTree*>* children = nodes();
5167 RegExpNode* current = on_success;
5168 for (int i = children->length() - 1; i >= 0; i--) {
5169 current = children->at(i)->ToNode(compiler, current);
5175 static void AddClass(const int* elmv,
5177 ZoneList<CharacterRange>* ranges,
5180 DCHECK(elmv[elmc] == 0x10000);
5181 for (int i = 0; i < elmc; i += 2) {
5182 DCHECK(elmv[i] < elmv[i + 1]);
5183 ranges->Add(CharacterRange(elmv[i], elmv[i + 1] - 1), zone);
5188 static void AddClassNegated(const int *elmv,
5190 ZoneList<CharacterRange>* ranges,
5193 DCHECK(elmv[elmc] == 0x10000);
5194 DCHECK(elmv[0] != 0x0000);
5195 DCHECK(elmv[elmc-1] != String::kMaxUtf16CodeUnit);
5197 for (int i = 0; i < elmc; i += 2) {
5198 DCHECK(last <= elmv[i] - 1);
5199 DCHECK(elmv[i] < elmv[i + 1]);
5200 ranges->Add(CharacterRange(last, elmv[i] - 1), zone);
5203 ranges->Add(CharacterRange(last, String::kMaxUtf16CodeUnit), zone);
5207 void CharacterRange::AddClassEscape(uc16 type,
5208 ZoneList<CharacterRange>* ranges,
5212 AddClass(kSpaceRanges, kSpaceRangeCount, ranges, zone);
5215 AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges, zone);
5218 AddClass(kWordRanges, kWordRangeCount, ranges, zone);
5221 AddClassNegated(kWordRanges, kWordRangeCount, ranges, zone);
5224 AddClass(kDigitRanges, kDigitRangeCount, ranges, zone);
5227 AddClassNegated(kDigitRanges, kDigitRangeCount, ranges, zone);
5230 AddClassNegated(kLineTerminatorRanges,
5231 kLineTerminatorRangeCount,
5235 // This is not a character range as defined by the spec but a
5236 // convenient shorthand for a character class that matches any
5239 ranges->Add(CharacterRange::Everything(), zone);
5241 // This is the set of characters matched by the $ and ^ symbols
5242 // in multiline mode.
5244 AddClass(kLineTerminatorRanges,
5245 kLineTerminatorRangeCount,
5255 Vector<const int> CharacterRange::GetWordBounds() {
5256 return Vector<const int>(kWordRanges, kWordRangeCount - 1);
5260 class CharacterRangeSplitter {
5262 CharacterRangeSplitter(ZoneList<CharacterRange>** included,
5263 ZoneList<CharacterRange>** excluded,
5265 : included_(included),
5266 excluded_(excluded),
5268 void Call(uc16 from, DispatchTable::Entry entry);
5270 static const int kInBase = 0;
5271 static const int kInOverlay = 1;
5274 ZoneList<CharacterRange>** included_;
5275 ZoneList<CharacterRange>** excluded_;
5280 void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) {
5281 if (!entry.out_set()->Get(kInBase)) return;
5282 ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay)
5285 if (*target == NULL) *target = new(zone_) ZoneList<CharacterRange>(2, zone_);
5286 (*target)->Add(CharacterRange(entry.from(), entry.to()), zone_);
5290 void CharacterRange::Split(ZoneList<CharacterRange>* base,
5291 Vector<const int> overlay,
5292 ZoneList<CharacterRange>** included,
5293 ZoneList<CharacterRange>** excluded,
5295 DCHECK_NULL(*included);
5296 DCHECK_NULL(*excluded);
5297 DispatchTable table(zone);
5298 for (int i = 0; i < base->length(); i++)
5299 table.AddRange(base->at(i), CharacterRangeSplitter::kInBase, zone);
5300 for (int i = 0; i < overlay.length(); i += 2) {
5301 table.AddRange(CharacterRange(overlay[i], overlay[i + 1] - 1),
5302 CharacterRangeSplitter::kInOverlay, zone);
5304 CharacterRangeSplitter callback(included, excluded, zone);
5305 table.ForEach(&callback);
5309 void CharacterRange::AddCaseEquivalents(Isolate* isolate, Zone* zone,
5310 ZoneList<CharacterRange>* ranges,
5312 uc16 bottom = from();
5314 if (is_one_byte && !RangeContainsLatin1Equivalents(*this)) {
5315 if (bottom > String::kMaxOneByteCharCode) return;
5316 if (top > String::kMaxOneByteCharCode) top = String::kMaxOneByteCharCode;
5318 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
5319 if (top == bottom) {
5320 // If this is a singleton we just expand the one character.
5321 int length = isolate->jsregexp_uncanonicalize()->get(bottom, '\0', chars);
5322 for (int i = 0; i < length; i++) {
5323 uc32 chr = chars[i];
5324 if (chr != bottom) {
5325 ranges->Add(CharacterRange::Singleton(chars[i]), zone);
5329 // If this is a range we expand the characters block by block,
5330 // expanding contiguous subranges (blocks) one at a time.
5331 // The approach is as follows. For a given start character we
5332 // look up the remainder of the block that contains it (represented
5333 // by the end point), for instance we find 'z' if the character
5334 // is 'c'. A block is characterized by the property
5335 // that all characters uncanonicalize in the same way, except that
5336 // each entry in the result is incremented by the distance from the first
5337 // element. So a-z is a block because 'a' uncanonicalizes to ['a', 'A'] and
5338 // the k'th letter uncanonicalizes to ['a' + k, 'A' + k].
5339 // Once we've found the end point we look up its uncanonicalization
5340 // and produce a range for each element. For instance for [c-f]
5341 // we look up ['z', 'Z'] and produce [c-f] and [C-F]. We then only
5342 // add a range if it is not already contained in the input, so [c-f]
5343 // will be skipped but [C-F] will be added. If this range is not
5344 // completely contained in a block we do this for all the blocks
5345 // covered by the range (handling characters that is not in a block
5346 // as a "singleton block").
5347 unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth];
5349 while (pos <= top) {
5350 int length = isolate->jsregexp_canonrange()->get(pos, '\0', range);
5355 DCHECK_EQ(1, length);
5356 block_end = range[0];
5358 int end = (block_end > top) ? top : block_end;
5359 length = isolate->jsregexp_uncanonicalize()->get(block_end, '\0', range);
5360 for (int i = 0; i < length; i++) {
5362 uc16 range_from = c - (block_end - pos);
5363 uc16 range_to = c - (block_end - end);
5364 if (!(bottom <= range_from && range_to <= top)) {
5365 ranges->Add(CharacterRange(range_from, range_to), zone);
5374 bool CharacterRange::IsCanonical(ZoneList<CharacterRange>* ranges) {
5375 DCHECK_NOT_NULL(ranges);
5376 int n = ranges->length();
5377 if (n <= 1) return true;
5378 int max = ranges->at(0).to();
5379 for (int i = 1; i < n; i++) {
5380 CharacterRange next_range = ranges->at(i);
5381 if (next_range.from() <= max + 1) return false;
5382 max = next_range.to();
5388 ZoneList<CharacterRange>* CharacterSet::ranges(Zone* zone) {
5389 if (ranges_ == NULL) {
5390 ranges_ = new(zone) ZoneList<CharacterRange>(2, zone);
5391 CharacterRange::AddClassEscape(standard_set_type_, ranges_, zone);
5397 // Move a number of elements in a zonelist to another position
5398 // in the same list. Handles overlapping source and target areas.
5399 static void MoveRanges(ZoneList<CharacterRange>* list,
5403 // Ranges are potentially overlapping.
5405 for (int i = count - 1; i >= 0; i--) {
5406 list->at(to + i) = list->at(from + i);
5409 for (int i = 0; i < count; i++) {
5410 list->at(to + i) = list->at(from + i);
5416 static int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list,
5418 CharacterRange insert) {
5419 // Inserts a range into list[0..count[, which must be sorted
5420 // by from value and non-overlapping and non-adjacent, using at most
5421 // list[0..count] for the result. Returns the number of resulting
5422 // canonicalized ranges. Inserting a range may collapse existing ranges into
5423 // fewer ranges, so the return value can be anything in the range 1..count+1.
5424 uc16 from = insert.from();
5425 uc16 to = insert.to();
5427 int end_pos = count;
5428 for (int i = count - 1; i >= 0; i--) {
5429 CharacterRange current = list->at(i);
5430 if (current.from() > to + 1) {
5432 } else if (current.to() + 1 < from) {
5438 // Inserted range overlaps, or is adjacent to, ranges at positions
5439 // [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are
5440 // not affected by the insertion.
5441 // If start_pos == end_pos, the range must be inserted before start_pos.
5442 // if start_pos < end_pos, the entire range from start_pos to end_pos
5443 // must be merged with the insert range.
5445 if (start_pos == end_pos) {
5446 // Insert between existing ranges at position start_pos.
5447 if (start_pos < count) {
5448 MoveRanges(list, start_pos, start_pos + 1, count - start_pos);
5450 list->at(start_pos) = insert;
5453 if (start_pos + 1 == end_pos) {
5454 // Replace single existing range at position start_pos.
5455 CharacterRange to_replace = list->at(start_pos);
5456 int new_from = Min(to_replace.from(), from);
5457 int new_to = Max(to_replace.to(), to);
5458 list->at(start_pos) = CharacterRange(new_from, new_to);
5461 // Replace a number of existing ranges from start_pos to end_pos - 1.
5462 // Move the remaining ranges down.
5464 int new_from = Min(list->at(start_pos).from(), from);
5465 int new_to = Max(list->at(end_pos - 1).to(), to);
5466 if (end_pos < count) {
5467 MoveRanges(list, end_pos, start_pos + 1, count - end_pos);
5469 list->at(start_pos) = CharacterRange(new_from, new_to);
5470 return count - (end_pos - start_pos) + 1;
5474 void CharacterSet::Canonicalize() {
5475 // Special/default classes are always considered canonical. The result
5476 // of calling ranges() will be sorted.
5477 if (ranges_ == NULL) return;
5478 CharacterRange::Canonicalize(ranges_);
5482 void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) {
5483 if (character_ranges->length() <= 1) return;
5484 // Check whether ranges are already canonical (increasing, non-overlapping,
5486 int n = character_ranges->length();
5487 int max = character_ranges->at(0).to();
5490 CharacterRange current = character_ranges->at(i);
5491 if (current.from() <= max + 1) {
5497 // Canonical until the i'th range. If that's all of them, we are done.
5500 // The ranges at index i and forward are not canonicalized. Make them so by
5501 // doing the equivalent of insertion sort (inserting each into the previous
5503 // Notice that inserting a range can reduce the number of ranges in the
5504 // result due to combining of adjacent and overlapping ranges.
5505 int read = i; // Range to insert.
5506 int num_canonical = i; // Length of canonicalized part of list.
5508 num_canonical = InsertRangeInCanonicalList(character_ranges,
5510 character_ranges->at(read));
5513 character_ranges->Rewind(num_canonical);
5515 DCHECK(CharacterRange::IsCanonical(character_ranges));
5519 void CharacterRange::Negate(ZoneList<CharacterRange>* ranges,
5520 ZoneList<CharacterRange>* negated_ranges,
5522 DCHECK(CharacterRange::IsCanonical(ranges));
5523 DCHECK_EQ(0, negated_ranges->length());
5524 int range_count = ranges->length();
5527 if (range_count > 0 && ranges->at(0).from() == 0) {
5528 from = ranges->at(0).to();
5531 while (i < range_count) {
5532 CharacterRange range = ranges->at(i);
5533 negated_ranges->Add(CharacterRange(from + 1, range.from() - 1), zone);
5537 if (from < String::kMaxUtf16CodeUnit) {
5538 negated_ranges->Add(CharacterRange(from + 1, String::kMaxUtf16CodeUnit),
5544 // -------------------------------------------------------------------
5548 OutSet* OutSet::Extend(unsigned value, Zone* zone) {
5551 if (successors(zone) != NULL) {
5552 for (int i = 0; i < successors(zone)->length(); i++) {
5553 OutSet* successor = successors(zone)->at(i);
5554 if (successor->Get(value))
5558 successors_ = new(zone) ZoneList<OutSet*>(2, zone);
5560 OutSet* result = new(zone) OutSet(first_, remaining_);
5561 result->Set(value, zone);
5562 successors(zone)->Add(result, zone);
5567 void OutSet::Set(unsigned value, Zone *zone) {
5568 if (value < kFirstLimit) {
5569 first_ |= (1 << value);
5571 if (remaining_ == NULL)
5572 remaining_ = new(zone) ZoneList<unsigned>(1, zone);
5573 if (remaining_->is_empty() || !remaining_->Contains(value))
5574 remaining_->Add(value, zone);
5579 bool OutSet::Get(unsigned value) const {
5580 if (value < kFirstLimit) {
5581 return (first_ & (1 << value)) != 0;
5582 } else if (remaining_ == NULL) {
5585 return remaining_->Contains(value);
5590 const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
5593 void DispatchTable::AddRange(CharacterRange full_range, int value,
5595 CharacterRange current = full_range;
5596 if (tree()->is_empty()) {
5597 // If this is the first range we just insert into the table.
5598 ZoneSplayTree<Config>::Locator loc;
5599 bool inserted = tree()->Insert(current.from(), &loc);
5602 loc.set_value(Entry(current.from(), current.to(),
5603 empty()->Extend(value, zone)));
5606 // First see if there is a range to the left of this one that
5608 ZoneSplayTree<Config>::Locator loc;
5609 if (tree()->FindGreatestLessThan(current.from(), &loc)) {
5610 Entry* entry = &loc.value();
5611 // If we've found a range that overlaps with this one, and it
5612 // starts strictly to the left of this one, we have to fix it
5613 // because the following code only handles ranges that start on
5614 // or after the start point of the range we're adding.
5615 if (entry->from() < current.from() && entry->to() >= current.from()) {
5616 // Snap the overlapping range in half around the start point of
5617 // the range we're adding.
5618 CharacterRange left(entry->from(), current.from() - 1);
5619 CharacterRange right(current.from(), entry->to());
5620 // The left part of the overlapping range doesn't overlap.
5621 // Truncate the whole entry to be just the left part.
5622 entry->set_to(left.to());
5623 // The right part is the one that overlaps. We add this part
5624 // to the map and let the next step deal with merging it with
5625 // the range we're adding.
5626 ZoneSplayTree<Config>::Locator loc;
5627 bool inserted = tree()->Insert(right.from(), &loc);
5630 loc.set_value(Entry(right.from(),
5635 while (current.is_valid()) {
5636 if (tree()->FindLeastGreaterThan(current.from(), &loc) &&
5637 (loc.value().from() <= current.to()) &&
5638 (loc.value().to() >= current.from())) {
5639 Entry* entry = &loc.value();
5640 // We have overlap. If there is space between the start point of
5641 // the range we're adding and where the overlapping range starts
5642 // then we have to add a range covering just that space.
5643 if (current.from() < entry->from()) {
5644 ZoneSplayTree<Config>::Locator ins;
5645 bool inserted = tree()->Insert(current.from(), &ins);
5648 ins.set_value(Entry(current.from(),
5650 empty()->Extend(value, zone)));
5651 current.set_from(entry->from());
5653 DCHECK_EQ(current.from(), entry->from());
5654 // If the overlapping range extends beyond the one we want to add
5655 // we have to snap the right part off and add it separately.
5656 if (entry->to() > current.to()) {
5657 ZoneSplayTree<Config>::Locator ins;
5658 bool inserted = tree()->Insert(current.to() + 1, &ins);
5661 ins.set_value(Entry(current.to() + 1,
5664 entry->set_to(current.to());
5666 DCHECK(entry->to() <= current.to());
5667 // The overlapping range is now completely contained by the range
5668 // we're adding so we can just update it and move the start point
5669 // of the range we're adding just past it.
5670 entry->AddValue(value, zone);
5671 // Bail out if the last interval ended at 0xFFFF since otherwise
5672 // adding 1 will wrap around to 0.
5673 if (entry->to() == String::kMaxUtf16CodeUnit)
5675 DCHECK(entry->to() + 1 > current.from());
5676 current.set_from(entry->to() + 1);
5678 // There is no overlap so we can just add the range
5679 ZoneSplayTree<Config>::Locator ins;
5680 bool inserted = tree()->Insert(current.from(), &ins);
5683 ins.set_value(Entry(current.from(),
5685 empty()->Extend(value, zone)));
5692 OutSet* DispatchTable::Get(uc16 value) {
5693 ZoneSplayTree<Config>::Locator loc;
5694 if (!tree()->FindGreatestLessThan(value, &loc))
5696 Entry* entry = &loc.value();
5697 if (value <= entry->to())
5698 return entry->out_set();
5704 // -------------------------------------------------------------------
5708 void Analysis::EnsureAnalyzed(RegExpNode* that) {
5709 StackLimitCheck check(isolate());
5710 if (check.HasOverflowed()) {
5711 fail("Stack overflow");
5714 if (that->info()->been_analyzed || that->info()->being_analyzed)
5716 that->info()->being_analyzed = true;
5718 that->info()->being_analyzed = false;
5719 that->info()->been_analyzed = true;
5723 void Analysis::VisitEnd(EndNode* that) {
5728 void TextNode::CalculateOffsets() {
5729 int element_count = elements()->length();
5730 // Set up the offsets of the elements relative to the start. This is a fixed
5731 // quantity since a TextNode can only contain fixed-width things.
5733 for (int i = 0; i < element_count; i++) {
5734 TextElement& elm = elements()->at(i);
5735 elm.set_cp_offset(cp_offset);
5736 cp_offset += elm.length();
5741 void Analysis::VisitText(TextNode* that) {
5743 that->MakeCaseIndependent(isolate(), is_one_byte_);
5745 EnsureAnalyzed(that->on_success());
5746 if (!has_failed()) {
5747 that->CalculateOffsets();
5752 void Analysis::VisitAction(ActionNode* that) {
5753 RegExpNode* target = that->on_success();
5754 EnsureAnalyzed(target);
5755 if (!has_failed()) {
5756 // If the next node is interested in what it follows then this node
5757 // has to be interested too so it can pass the information on.
5758 that->info()->AddFromFollowing(target->info());
5763 void Analysis::VisitChoice(ChoiceNode* that) {
5764 NodeInfo* info = that->info();
5765 for (int i = 0; i < that->alternatives()->length(); i++) {
5766 RegExpNode* node = that->alternatives()->at(i).node();
5767 EnsureAnalyzed(node);
5768 if (has_failed()) return;
5769 // Anything the following nodes need to know has to be known by
5770 // this node also, so it can pass it on.
5771 info->AddFromFollowing(node->info());
5776 void Analysis::VisitLoopChoice(LoopChoiceNode* that) {
5777 NodeInfo* info = that->info();
5778 for (int i = 0; i < that->alternatives()->length(); i++) {
5779 RegExpNode* node = that->alternatives()->at(i).node();
5780 if (node != that->loop_node()) {
5781 EnsureAnalyzed(node);
5782 if (has_failed()) return;
5783 info->AddFromFollowing(node->info());
5786 // Check the loop last since it may need the value of this node
5787 // to get a correct result.
5788 EnsureAnalyzed(that->loop_node());
5789 if (!has_failed()) {
5790 info->AddFromFollowing(that->loop_node()->info());
5795 void Analysis::VisitBackReference(BackReferenceNode* that) {
5796 EnsureAnalyzed(that->on_success());
5800 void Analysis::VisitAssertion(AssertionNode* that) {
5801 EnsureAnalyzed(that->on_success());
5805 void BackReferenceNode::FillInBMInfo(int offset,
5807 BoyerMooreLookahead* bm,
5808 bool not_at_start) {
5809 // Working out the set of characters that a backreference can match is too
5810 // hard, so we just say that any character can match.
5811 bm->SetRest(offset);
5812 SaveBMInfo(bm, not_at_start, offset);
5816 STATIC_ASSERT(BoyerMoorePositionInfo::kMapSize ==
5817 RegExpMacroAssembler::kTableSize);
5820 void ChoiceNode::FillInBMInfo(int offset,
5822 BoyerMooreLookahead* bm,
5823 bool not_at_start) {
5824 ZoneList<GuardedAlternative>* alts = alternatives();
5825 budget = (budget - 1) / alts->length();
5826 for (int i = 0; i < alts->length(); i++) {
5827 GuardedAlternative& alt = alts->at(i);
5828 if (alt.guards() != NULL && alt.guards()->length() != 0) {
5829 bm->SetRest(offset); // Give up trying to fill in info.
5830 SaveBMInfo(bm, not_at_start, offset);
5833 alt.node()->FillInBMInfo(offset, budget, bm, not_at_start);
5835 SaveBMInfo(bm, not_at_start, offset);
5839 void TextNode::FillInBMInfo(int initial_offset,
5841 BoyerMooreLookahead* bm,
5842 bool not_at_start) {
5843 if (initial_offset >= bm->length()) return;
5844 int offset = initial_offset;
5845 int max_char = bm->max_char();
5846 for (int i = 0; i < elements()->length(); i++) {
5847 if (offset >= bm->length()) {
5848 if (initial_offset == 0) set_bm_info(not_at_start, bm);
5851 TextElement text = elements()->at(i);
5852 if (text.text_type() == TextElement::ATOM) {
5853 RegExpAtom* atom = text.atom();
5854 for (int j = 0; j < atom->length(); j++, offset++) {
5855 if (offset >= bm->length()) {
5856 if (initial_offset == 0) set_bm_info(not_at_start, bm);
5859 uc16 character = atom->data()[j];
5860 if (bm->compiler()->ignore_case()) {
5861 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
5862 int length = GetCaseIndependentLetters(
5865 bm->max_char() == String::kMaxOneByteCharCode,
5867 for (int j = 0; j < length; j++) {
5868 bm->Set(offset, chars[j]);
5871 if (character <= max_char) bm->Set(offset, character);
5875 DCHECK_EQ(TextElement::CHAR_CLASS, text.text_type());
5876 RegExpCharacterClass* char_class = text.char_class();
5877 ZoneList<CharacterRange>* ranges = char_class->ranges(zone());
5878 if (char_class->is_negated()) {
5881 for (int k = 0; k < ranges->length(); k++) {
5882 CharacterRange& range = ranges->at(k);
5883 if (range.from() > max_char) continue;
5884 int to = Min(max_char, static_cast<int>(range.to()));
5885 bm->SetInterval(offset, Interval(range.from(), to));
5891 if (offset >= bm->length()) {
5892 if (initial_offset == 0) set_bm_info(not_at_start, bm);
5895 on_success()->FillInBMInfo(offset,
5898 true); // Not at start after a text node.
5899 if (initial_offset == 0) set_bm_info(not_at_start, bm);
5903 // -------------------------------------------------------------------
5904 // Dispatch table construction
5907 void DispatchTableConstructor::VisitEnd(EndNode* that) {
5908 AddRange(CharacterRange::Everything());
5912 void DispatchTableConstructor::BuildTable(ChoiceNode* node) {
5913 node->set_being_calculated(true);
5914 ZoneList<GuardedAlternative>* alternatives = node->alternatives();
5915 for (int i = 0; i < alternatives->length(); i++) {
5916 set_choice_index(i);
5917 alternatives->at(i).node()->Accept(this);
5919 node->set_being_calculated(false);
5923 class AddDispatchRange {
5925 explicit AddDispatchRange(DispatchTableConstructor* constructor)
5926 : constructor_(constructor) { }
5927 void Call(uc32 from, DispatchTable::Entry entry);
5929 DispatchTableConstructor* constructor_;
5933 void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
5934 CharacterRange range(from, entry.to());
5935 constructor_->AddRange(range);
5939 void DispatchTableConstructor::VisitChoice(ChoiceNode* node) {
5940 if (node->being_calculated())
5942 DispatchTable* table = node->GetTable(ignore_case_);
5943 AddDispatchRange adder(this);
5944 table->ForEach(&adder);
5948 void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) {
5949 // TODO(160): Find the node that we refer back to and propagate its start
5950 // set back to here. For now we just accept anything.
5951 AddRange(CharacterRange::Everything());
5955 void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
5956 RegExpNode* target = that->on_success();
5957 target->Accept(this);
5961 static int CompareRangeByFrom(const CharacterRange* a,
5962 const CharacterRange* b) {
5963 return Compare<uc16>(a->from(), b->from());
5967 void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) {
5968 ranges->Sort(CompareRangeByFrom);
5970 for (int i = 0; i < ranges->length(); i++) {
5971 CharacterRange range = ranges->at(i);
5972 if (last < range.from())
5973 AddRange(CharacterRange(last, range.from() - 1));
5974 if (range.to() >= last) {
5975 if (range.to() == String::kMaxUtf16CodeUnit) {
5978 last = range.to() + 1;
5982 AddRange(CharacterRange(last, String::kMaxUtf16CodeUnit));
5986 void DispatchTableConstructor::VisitText(TextNode* that) {
5987 TextElement elm = that->elements()->at(0);
5988 switch (elm.text_type()) {
5989 case TextElement::ATOM: {
5990 uc16 c = elm.atom()->data()[0];
5991 AddRange(CharacterRange(c, c));
5994 case TextElement::CHAR_CLASS: {
5995 RegExpCharacterClass* tree = elm.char_class();
5996 ZoneList<CharacterRange>* ranges = tree->ranges(that->zone());
5997 if (tree->is_negated()) {
6000 for (int i = 0; i < ranges->length(); i++)
6001 AddRange(ranges->at(i));
6012 void DispatchTableConstructor::VisitAction(ActionNode* that) {
6013 RegExpNode* target = that->on_success();
6014 target->Accept(this);
6018 RegExpEngine::CompilationResult RegExpEngine::Compile(
6019 Isolate* isolate, Zone* zone, RegExpCompileData* data, bool ignore_case,
6020 bool is_global, bool is_multiline, bool is_sticky, Handle<String> pattern,
6021 Handle<String> sample_subject, bool is_one_byte) {
6022 if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) {
6023 return IrregexpRegExpTooBig(isolate);
6025 RegExpCompiler compiler(isolate, zone, data->capture_count, ignore_case,
6028 compiler.set_optimize(!TooMuchRegExpCode(pattern));
6030 // Sample some characters from the middle of the string.
6031 static const int kSampleSize = 128;
6033 sample_subject = String::Flatten(sample_subject);
6034 int chars_sampled = 0;
6035 int half_way = (sample_subject->length() - kSampleSize) / 2;
6036 for (int i = Max(0, half_way);
6037 i < sample_subject->length() && chars_sampled < kSampleSize;
6038 i++, chars_sampled++) {
6039 compiler.frequency_collator()->CountCharacter(sample_subject->Get(i));
6042 // Wrap the body of the regexp in capture #0.
6043 RegExpNode* captured_body = RegExpCapture::ToNode(data->tree,
6047 RegExpNode* node = captured_body;
6048 bool is_end_anchored = data->tree->IsAnchoredAtEnd();
6049 bool is_start_anchored = data->tree->IsAnchoredAtStart();
6050 int max_length = data->tree->max_match();
6051 if (!is_start_anchored && !is_sticky) {
6052 // Add a .*? at the beginning, outside the body capture, unless
6053 // this expression is anchored at the beginning or sticky.
6054 RegExpNode* loop_node =
6055 RegExpQuantifier::ToNode(0,
6056 RegExpTree::kInfinity,
6058 new(zone) RegExpCharacterClass('*'),
6061 data->contains_anchor);
6063 if (data->contains_anchor) {
6064 // Unroll loop once, to take care of the case that might start
6065 // at the start of input.
6066 ChoiceNode* first_step_node = new(zone) ChoiceNode(2, zone);
6067 first_step_node->AddAlternative(GuardedAlternative(captured_body));
6068 first_step_node->AddAlternative(GuardedAlternative(
6069 new(zone) TextNode(new(zone) RegExpCharacterClass('*'), loop_node)));
6070 node = first_step_node;
6076 node = node->FilterOneByte(RegExpCompiler::kMaxRecursion, ignore_case);
6077 // Do it again to propagate the new nodes to places where they were not
6078 // put because they had not been calculated yet.
6080 node = node->FilterOneByte(RegExpCompiler::kMaxRecursion, ignore_case);
6084 if (node == NULL) node = new(zone) EndNode(EndNode::BACKTRACK, zone);
6086 Analysis analysis(isolate, ignore_case, is_one_byte);
6087 analysis.EnsureAnalyzed(node);
6088 if (analysis.has_failed()) {
6089 const char* error_message = analysis.error_message();
6090 return CompilationResult(isolate, error_message);
6093 // Create the correct assembler for the architecture.
6094 #ifndef V8_INTERPRETED_REGEXP
6095 // Native regexp implementation.
6097 NativeRegExpMacroAssembler::Mode mode =
6098 is_one_byte ? NativeRegExpMacroAssembler::LATIN1
6099 : NativeRegExpMacroAssembler::UC16;
6101 #if V8_TARGET_ARCH_IA32
6102 RegExpMacroAssemblerIA32 macro_assembler(isolate, zone, mode,
6103 (data->capture_count + 1) * 2);
6104 #elif V8_TARGET_ARCH_X64
6105 RegExpMacroAssemblerX64 macro_assembler(isolate, zone, mode,
6106 (data->capture_count + 1) * 2);
6107 #elif V8_TARGET_ARCH_ARM
6108 RegExpMacroAssemblerARM macro_assembler(isolate, zone, mode,
6109 (data->capture_count + 1) * 2);
6110 #elif V8_TARGET_ARCH_ARM64
6111 RegExpMacroAssemblerARM64 macro_assembler(isolate, zone, mode,
6112 (data->capture_count + 1) * 2);
6113 #elif V8_TARGET_ARCH_PPC
6114 RegExpMacroAssemblerPPC macro_assembler(isolate, zone, mode,
6115 (data->capture_count + 1) * 2);
6116 #elif V8_TARGET_ARCH_MIPS
6117 RegExpMacroAssemblerMIPS macro_assembler(isolate, zone, mode,
6118 (data->capture_count + 1) * 2);
6119 #elif V8_TARGET_ARCH_MIPS64
6120 RegExpMacroAssemblerMIPS macro_assembler(isolate, zone, mode,
6121 (data->capture_count + 1) * 2);
6122 #elif V8_TARGET_ARCH_X87
6123 RegExpMacroAssemblerX87 macro_assembler(isolate, zone, mode,
6124 (data->capture_count + 1) * 2);
6126 #error "Unsupported architecture"
6129 #else // V8_INTERPRETED_REGEXP
6130 // Interpreted regexp implementation.
6131 EmbeddedVector<byte, 1024> codes;
6132 RegExpMacroAssemblerIrregexp macro_assembler(isolate, codes, zone);
6133 #endif // V8_INTERPRETED_REGEXP
6135 macro_assembler.set_slow_safe(TooMuchRegExpCode(pattern));
6137 // Inserted here, instead of in Assembler, because it depends on information
6138 // in the AST that isn't replicated in the Node structure.
6139 static const int kMaxBacksearchLimit = 1024;
6140 if (is_end_anchored &&
6141 !is_start_anchored &&
6142 max_length < kMaxBacksearchLimit) {
6143 macro_assembler.SetCurrentPositionFromEnd(max_length);
6147 macro_assembler.set_global_mode(
6148 (data->tree->min_match() > 0)
6149 ? RegExpMacroAssembler::GLOBAL_NO_ZERO_LENGTH_CHECK
6150 : RegExpMacroAssembler::GLOBAL);
6153 return compiler.Assemble(¯o_assembler,
6155 data->capture_count,
6160 bool RegExpEngine::TooMuchRegExpCode(Handle<String> pattern) {
6161 Heap* heap = pattern->GetHeap();
6162 bool too_much = pattern->length() > RegExpImpl::kRegExpTooLargeToOptimize;
6163 if (heap->total_regexp_code_generated() > RegExpImpl::kRegExpCompiledLimit &&
6164 heap->isolate()->memory_allocator()->SizeExecutable() >
6165 RegExpImpl::kRegExpExecutableMemoryLimit) {
6170 }} // namespace v8::internal