1 // Copyright 2012 the V8 project authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
8 #include "src/base/platform/platform.h"
9 #include "src/compilation-cache.h"
10 #include "src/compiler.h"
11 #include "src/execution.h"
12 #include "src/factory.h"
13 #include "src/jsregexp-inl.h"
14 #include "src/jsregexp.h"
15 #include "src/ostreams.h"
16 #include "src/parser.h"
17 #include "src/regexp-macro-assembler.h"
18 #include "src/regexp-macro-assembler-irregexp.h"
19 #include "src/regexp-macro-assembler-tracer.h"
20 #include "src/regexp-stack.h"
21 #include "src/runtime/runtime.h"
22 #include "src/string-search.h"
23 #include "src/unicode-decoder.h"
25 #ifndef V8_INTERPRETED_REGEXP
26 #if V8_TARGET_ARCH_IA32
27 #include "src/ia32/regexp-macro-assembler-ia32.h" // NOLINT
28 #elif V8_TARGET_ARCH_X64
29 #include "src/x64/regexp-macro-assembler-x64.h" // NOLINT
30 #elif V8_TARGET_ARCH_ARM64
31 #include "src/arm64/regexp-macro-assembler-arm64.h" // NOLINT
32 #elif V8_TARGET_ARCH_ARM
33 #include "src/arm/regexp-macro-assembler-arm.h" // NOLINT
34 #elif V8_TARGET_ARCH_MIPS
35 #include "src/mips/regexp-macro-assembler-mips.h" // NOLINT
36 #elif V8_TARGET_ARCH_MIPS64
37 #include "src/mips64/regexp-macro-assembler-mips64.h" // NOLINT
38 #elif V8_TARGET_ARCH_X87
39 #include "src/x87/regexp-macro-assembler-x87.h" // NOLINT
41 #error Unsupported target architecture.
45 #include "src/interpreter-irregexp.h"
51 MaybeHandle<Object> RegExpImpl::CreateRegExpLiteral(
52 Handle<JSFunction> constructor,
53 Handle<String> pattern,
54 Handle<String> flags) {
55 // Call the construct code with 2 arguments.
56 Handle<Object> argv[] = { pattern, flags };
57 return Execution::New(constructor, arraysize(argv), argv);
62 static inline MaybeHandle<Object> ThrowRegExpException(
64 Handle<String> pattern,
65 Handle<String> error_text,
66 const char* message) {
67 Isolate* isolate = re->GetIsolate();
68 Factory* factory = isolate->factory();
69 Handle<FixedArray> elements = factory->NewFixedArray(2);
70 elements->set(0, *pattern);
71 elements->set(1, *error_text);
72 Handle<JSArray> array = factory->NewJSArrayWithElements(elements);
73 Handle<Object> regexp_err;
74 THROW_NEW_ERROR(isolate, NewSyntaxError(message, array), Object);
78 ContainedInLattice AddRange(ContainedInLattice containment,
82 DCHECK((ranges_length & 1) == 1);
83 DCHECK(ranges[ranges_length - 1] == String::kMaxUtf16CodeUnit + 1);
84 if (containment == kLatticeUnknown) return containment;
87 for (int i = 0; i < ranges_length; inside = !inside, last = ranges[i], i++) {
88 // Consider the range from last to ranges[i].
89 // We haven't got to the new range yet.
90 if (ranges[i] <= new_range.from()) continue;
91 // New range is wholly inside last-ranges[i]. Note that new_range.to() is
92 // inclusive, but the values in ranges are not.
93 if (last <= new_range.from() && new_range.to() < ranges[i]) {
94 return Combine(containment, inside ? kLatticeIn : kLatticeOut);
96 return kLatticeUnknown;
102 // More makes code generation slower, less makes V8 benchmark score lower.
103 const int kMaxLookaheadForBoyerMoore = 8;
104 // In a 3-character pattern you can maximally step forwards 3 characters
105 // at a time, which is not always enough to pay for the extra logic.
106 const int kPatternTooShortForBoyerMoore = 2;
109 // Identifies the sort of regexps where the regexp engine is faster
110 // than the code used for atom matches.
111 static bool HasFewDifferentCharacters(Handle<String> pattern) {
112 int length = Min(kMaxLookaheadForBoyerMoore, pattern->length());
113 if (length <= kPatternTooShortForBoyerMoore) return false;
114 const int kMod = 128;
115 bool character_found[kMod];
117 memset(&character_found[0], 0, sizeof(character_found));
118 for (int i = 0; i < length; i++) {
119 int ch = (pattern->Get(i) & (kMod - 1));
120 if (!character_found[ch]) {
121 character_found[ch] = true;
123 // We declare a regexp low-alphabet if it has at least 3 times as many
124 // characters as it has different characters.
125 if (different * 3 > length) return false;
132 // Generic RegExp methods. Dispatches to implementation specific methods.
135 MaybeHandle<Object> RegExpImpl::Compile(Handle<JSRegExp> re,
136 Handle<String> pattern,
137 JSRegExp::Flags flags) {
138 Isolate* isolate = re->GetIsolate();
140 CompilationCache* compilation_cache = isolate->compilation_cache();
141 MaybeHandle<FixedArray> maybe_cached =
142 compilation_cache->LookupRegExp(pattern, flags);
143 Handle<FixedArray> cached;
144 bool in_cache = maybe_cached.ToHandle(&cached);
145 LOG(isolate, RegExpCompileEvent(re, in_cache));
147 Handle<Object> result;
149 re->set_data(*cached);
152 pattern = String::Flatten(pattern);
153 PostponeInterruptsScope postpone(isolate);
154 RegExpCompileData parse_result;
155 FlatStringReader reader(isolate, pattern);
156 if (!RegExpParser::ParseRegExp(&reader, flags.is_multiline(),
157 &parse_result, &zone)) {
158 // Throw an exception if we fail to parse the pattern.
159 return ThrowRegExpException(re,
165 bool has_been_compiled = false;
167 if (parse_result.simple &&
168 !flags.is_ignore_case() &&
169 !flags.is_sticky() &&
170 !HasFewDifferentCharacters(pattern)) {
171 // Parse-tree is a single atom that is equal to the pattern.
172 AtomCompile(re, pattern, flags, pattern);
173 has_been_compiled = true;
174 } else if (parse_result.tree->IsAtom() &&
175 !flags.is_ignore_case() &&
176 !flags.is_sticky() &&
177 parse_result.capture_count == 0) {
178 RegExpAtom* atom = parse_result.tree->AsAtom();
179 Vector<const uc16> atom_pattern = atom->data();
180 Handle<String> atom_string;
181 ASSIGN_RETURN_ON_EXCEPTION(
182 isolate, atom_string,
183 isolate->factory()->NewStringFromTwoByte(atom_pattern),
185 if (!HasFewDifferentCharacters(atom_string)) {
186 AtomCompile(re, pattern, flags, atom_string);
187 has_been_compiled = true;
190 if (!has_been_compiled) {
191 IrregexpInitialize(re, pattern, flags, parse_result.capture_count);
193 DCHECK(re->data()->IsFixedArray());
194 // Compilation succeeded so the data is set on the regexp
195 // and we can store it in the cache.
196 Handle<FixedArray> data(FixedArray::cast(re->data()));
197 compilation_cache->PutRegExp(pattern, flags, data);
203 MaybeHandle<Object> RegExpImpl::Exec(Handle<JSRegExp> regexp,
204 Handle<String> subject,
206 Handle<JSArray> last_match_info) {
207 switch (regexp->TypeTag()) {
209 return AtomExec(regexp, subject, index, last_match_info);
210 case JSRegExp::IRREGEXP: {
211 return IrregexpExec(regexp, subject, index, last_match_info);
215 return MaybeHandle<Object>();
220 // RegExp Atom implementation: Simple string search using indexOf.
223 void RegExpImpl::AtomCompile(Handle<JSRegExp> re,
224 Handle<String> pattern,
225 JSRegExp::Flags flags,
226 Handle<String> match_pattern) {
227 re->GetIsolate()->factory()->SetRegExpAtomData(re,
235 static void SetAtomLastCapture(FixedArray* array,
239 SealHandleScope shs(array->GetIsolate());
240 RegExpImpl::SetLastCaptureCount(array, 2);
241 RegExpImpl::SetLastSubject(array, subject);
242 RegExpImpl::SetLastInput(array, subject);
243 RegExpImpl::SetCapture(array, 0, from);
244 RegExpImpl::SetCapture(array, 1, to);
248 int RegExpImpl::AtomExecRaw(Handle<JSRegExp> regexp,
249 Handle<String> subject,
253 Isolate* isolate = regexp->GetIsolate();
256 DCHECK(index <= subject->length());
258 subject = String::Flatten(subject);
259 DisallowHeapAllocation no_gc; // ensure vectors stay valid
261 String* needle = String::cast(regexp->DataAt(JSRegExp::kAtomPatternIndex));
262 int needle_len = needle->length();
263 DCHECK(needle->IsFlat());
264 DCHECK_LT(0, needle_len);
266 if (index + needle_len > subject->length()) {
267 return RegExpImpl::RE_FAILURE;
270 for (int i = 0; i < output_size; i += 2) {
271 String::FlatContent needle_content = needle->GetFlatContent();
272 String::FlatContent subject_content = subject->GetFlatContent();
273 DCHECK(needle_content.IsFlat());
274 DCHECK(subject_content.IsFlat());
275 // dispatch on type of strings
277 (needle_content.IsOneByte()
278 ? (subject_content.IsOneByte()
279 ? SearchString(isolate, subject_content.ToOneByteVector(),
280 needle_content.ToOneByteVector(), index)
281 : SearchString(isolate, subject_content.ToUC16Vector(),
282 needle_content.ToOneByteVector(), index))
283 : (subject_content.IsOneByte()
284 ? SearchString(isolate, subject_content.ToOneByteVector(),
285 needle_content.ToUC16Vector(), index)
286 : SearchString(isolate, subject_content.ToUC16Vector(),
287 needle_content.ToUC16Vector(), index)));
289 return i / 2; // Return number of matches.
292 output[i+1] = index + needle_len;
296 return output_size / 2;
300 Handle<Object> RegExpImpl::AtomExec(Handle<JSRegExp> re,
301 Handle<String> subject,
303 Handle<JSArray> last_match_info) {
304 Isolate* isolate = re->GetIsolate();
306 static const int kNumRegisters = 2;
307 STATIC_ASSERT(kNumRegisters <= Isolate::kJSRegexpStaticOffsetsVectorSize);
308 int32_t* output_registers = isolate->jsregexp_static_offsets_vector();
310 int res = AtomExecRaw(re, subject, index, output_registers, kNumRegisters);
312 if (res == RegExpImpl::RE_FAILURE) return isolate->factory()->null_value();
314 DCHECK_EQ(res, RegExpImpl::RE_SUCCESS);
315 SealHandleScope shs(isolate);
316 FixedArray* array = FixedArray::cast(last_match_info->elements());
317 SetAtomLastCapture(array, *subject, output_registers[0], output_registers[1]);
318 return last_match_info;
322 // Irregexp implementation.
324 // Ensures that the regexp object contains a compiled version of the
325 // source for either one-byte or two-byte subject strings.
326 // If the compiled version doesn't already exist, it is compiled
327 // from the source pattern.
328 // If compilation fails, an exception is thrown and this function
330 bool RegExpImpl::EnsureCompiledIrregexp(Handle<JSRegExp> re,
331 Handle<String> sample_subject,
333 Object* compiled_code = re->DataAt(JSRegExp::code_index(is_one_byte));
334 #ifdef V8_INTERPRETED_REGEXP
335 if (compiled_code->IsByteArray()) return true;
336 #else // V8_INTERPRETED_REGEXP (RegExp native code)
337 if (compiled_code->IsCode()) return true;
339 // We could potentially have marked this as flushable, but have kept
340 // a saved version if we did not flush it yet.
341 Object* saved_code = re->DataAt(JSRegExp::saved_code_index(is_one_byte));
342 if (saved_code->IsCode()) {
343 // Reinstate the code in the original place.
344 re->SetDataAt(JSRegExp::code_index(is_one_byte), saved_code);
345 DCHECK(compiled_code->IsSmi());
348 return CompileIrregexp(re, sample_subject, is_one_byte);
352 static void CreateRegExpErrorObjectAndThrow(Handle<JSRegExp> re,
353 Handle<String> error_message,
355 Factory* factory = isolate->factory();
356 Handle<FixedArray> elements = factory->NewFixedArray(2);
357 elements->set(0, re->Pattern());
358 elements->set(1, *error_message);
359 Handle<JSArray> array = factory->NewJSArrayWithElements(elements);
360 Handle<Object> error;
361 MaybeHandle<Object> maybe_error =
362 factory->NewSyntaxError("malformed_regexp", array);
363 if (maybe_error.ToHandle(&error)) isolate->Throw(*error);
367 bool RegExpImpl::CompileIrregexp(Handle<JSRegExp> re,
368 Handle<String> sample_subject,
370 // Compile the RegExp.
371 Isolate* isolate = re->GetIsolate();
373 PostponeInterruptsScope postpone(isolate);
374 // If we had a compilation error the last time this is saved at the
376 Object* entry = re->DataAt(JSRegExp::code_index(is_one_byte));
377 // When arriving here entry can only be a smi, either representing an
378 // uncompiled regexp, a previous compilation error, or code that has
380 DCHECK(entry->IsSmi());
381 int entry_value = Smi::cast(entry)->value();
382 DCHECK(entry_value == JSRegExp::kUninitializedValue ||
383 entry_value == JSRegExp::kCompilationErrorValue ||
384 (entry_value < JSRegExp::kCodeAgeMask && entry_value >= 0));
386 if (entry_value == JSRegExp::kCompilationErrorValue) {
387 // A previous compilation failed and threw an error which we store in
388 // the saved code index (we store the error message, not the actual
389 // error). Recreate the error object and throw it.
390 Object* error_string = re->DataAt(JSRegExp::saved_code_index(is_one_byte));
391 DCHECK(error_string->IsString());
392 Handle<String> error_message(String::cast(error_string));
393 CreateRegExpErrorObjectAndThrow(re, error_message, isolate);
397 JSRegExp::Flags flags = re->GetFlags();
399 Handle<String> pattern(re->Pattern());
400 pattern = String::Flatten(pattern);
401 RegExpCompileData compile_data;
402 FlatStringReader reader(isolate, pattern);
403 if (!RegExpParser::ParseRegExp(&reader, flags.is_multiline(),
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 &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(int capture_count, 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 Zone* zone() const { return zone_; }
1018 static const int kNoRegister = -1;
1023 List<RegExpNode*>* work_list_;
1024 int recursion_depth_;
1025 RegExpMacroAssembler* macro_assembler_;
1028 bool reg_exp_too_big_;
1030 int current_expansion_factor_;
1031 FrequencyCollator frequency_collator_;
1036 class RecursionCheck {
1038 explicit RecursionCheck(RegExpCompiler* compiler) : compiler_(compiler) {
1039 compiler->IncrementRecursionDepth();
1041 ~RecursionCheck() { compiler_->DecrementRecursionDepth(); }
1043 RegExpCompiler* compiler_;
1047 static RegExpEngine::CompilationResult IrregexpRegExpTooBig(Isolate* isolate) {
1048 return RegExpEngine::CompilationResult(isolate, "RegExp too big");
1052 // Attempts to compile the regexp using an Irregexp code generator. Returns
1053 // a fixed array or a null handle depending on whether it succeeded.
1054 RegExpCompiler::RegExpCompiler(int capture_count, bool ignore_case,
1055 bool one_byte, Zone* zone)
1056 : next_register_(2 * (capture_count + 1)),
1058 recursion_depth_(0),
1059 ignore_case_(ignore_case),
1060 one_byte_(one_byte),
1061 reg_exp_too_big_(false),
1062 optimize_(FLAG_regexp_optimization),
1063 current_expansion_factor_(1),
1064 frequency_collator_(),
1066 accept_ = new(zone) EndNode(EndNode::ACCEPT, zone);
1067 DCHECK(next_register_ - 1 <= RegExpMacroAssembler::kMaxRegister);
1071 RegExpEngine::CompilationResult RegExpCompiler::Assemble(
1072 RegExpMacroAssembler* macro_assembler,
1075 Handle<String> pattern) {
1076 Heap* heap = pattern->GetHeap();
1079 if (FLAG_trace_regexp_assembler)
1080 macro_assembler_ = new RegExpMacroAssemblerTracer(macro_assembler);
1083 macro_assembler_ = macro_assembler;
1085 List <RegExpNode*> work_list(0);
1086 work_list_ = &work_list;
1088 macro_assembler_->PushBacktrack(&fail);
1090 start->Emit(this, &new_trace);
1091 macro_assembler_->Bind(&fail);
1092 macro_assembler_->Fail();
1093 while (!work_list.is_empty()) {
1094 work_list.RemoveLast()->Emit(this, &new_trace);
1096 if (reg_exp_too_big_) return IrregexpRegExpTooBig(zone_->isolate());
1098 Handle<HeapObject> code = macro_assembler_->GetCode(pattern);
1099 heap->IncreaseTotalRegexpCodeGenerated(code->Size());
1101 #ifdef ENABLE_DISASSEMBLER
1102 if (FLAG_print_code) {
1103 CodeTracer::Scope trace_scope(heap->isolate()->GetCodeTracer());
1104 OFStream os(trace_scope.file());
1105 Handle<Code>::cast(code)->Disassemble(pattern->ToCString().get(), os);
1109 if (FLAG_trace_regexp_assembler) {
1110 delete macro_assembler_;
1113 return RegExpEngine::CompilationResult(*code, next_register_);
1117 bool Trace::DeferredAction::Mentions(int that) {
1118 if (action_type() == ActionNode::CLEAR_CAPTURES) {
1119 Interval range = static_cast<DeferredClearCaptures*>(this)->range();
1120 return range.Contains(that);
1122 return reg() == that;
1127 bool Trace::mentions_reg(int reg) {
1128 for (DeferredAction* action = actions_;
1130 action = action->next()) {
1131 if (action->Mentions(reg))
1138 bool Trace::GetStoredPosition(int reg, int* cp_offset) {
1139 DCHECK_EQ(0, *cp_offset);
1140 for (DeferredAction* action = actions_;
1142 action = action->next()) {
1143 if (action->Mentions(reg)) {
1144 if (action->action_type() == ActionNode::STORE_POSITION) {
1145 *cp_offset = static_cast<DeferredCapture*>(action)->cp_offset();
1156 int Trace::FindAffectedRegisters(OutSet* affected_registers,
1158 int max_register = RegExpCompiler::kNoRegister;
1159 for (DeferredAction* action = actions_;
1161 action = action->next()) {
1162 if (action->action_type() == ActionNode::CLEAR_CAPTURES) {
1163 Interval range = static_cast<DeferredClearCaptures*>(action)->range();
1164 for (int i = range.from(); i <= range.to(); i++)
1165 affected_registers->Set(i, zone);
1166 if (range.to() > max_register) max_register = range.to();
1168 affected_registers->Set(action->reg(), zone);
1169 if (action->reg() > max_register) max_register = action->reg();
1172 return max_register;
1176 void Trace::RestoreAffectedRegisters(RegExpMacroAssembler* assembler,
1178 const OutSet& registers_to_pop,
1179 const OutSet& registers_to_clear) {
1180 for (int reg = max_register; reg >= 0; reg--) {
1181 if (registers_to_pop.Get(reg)) {
1182 assembler->PopRegister(reg);
1183 } else if (registers_to_clear.Get(reg)) {
1185 while (reg > 0 && registers_to_clear.Get(reg - 1)) {
1188 assembler->ClearRegisters(reg, clear_to);
1194 void Trace::PerformDeferredActions(RegExpMacroAssembler* assembler,
1196 const OutSet& affected_registers,
1197 OutSet* registers_to_pop,
1198 OutSet* registers_to_clear,
1200 // The "+1" is to avoid a push_limit of zero if stack_limit_slack() is 1.
1201 const int push_limit = (assembler->stack_limit_slack() + 1) / 2;
1203 // Count pushes performed to force a stack limit check occasionally.
1206 for (int reg = 0; reg <= max_register; reg++) {
1207 if (!affected_registers.Get(reg)) {
1211 // The chronologically first deferred action in the trace
1212 // is used to infer the action needed to restore a register
1213 // to its previous state (or not, if it's safe to ignore it).
1214 enum DeferredActionUndoType { IGNORE, RESTORE, CLEAR };
1215 DeferredActionUndoType undo_action = IGNORE;
1218 bool absolute = false;
1220 int store_position = -1;
1221 // This is a little tricky because we are scanning the actions in reverse
1222 // historical order (newest first).
1223 for (DeferredAction* action = actions_;
1225 action = action->next()) {
1226 if (action->Mentions(reg)) {
1227 switch (action->action_type()) {
1228 case ActionNode::SET_REGISTER: {
1229 Trace::DeferredSetRegister* psr =
1230 static_cast<Trace::DeferredSetRegister*>(action);
1232 value += psr->value();
1235 // SET_REGISTER is currently only used for newly introduced loop
1236 // counters. They can have a significant previous value if they
1237 // occour in a loop. TODO(lrn): Propagate this information, so
1238 // we can set undo_action to IGNORE if we know there is no value to
1240 undo_action = RESTORE;
1241 DCHECK_EQ(store_position, -1);
1245 case ActionNode::INCREMENT_REGISTER:
1249 DCHECK_EQ(store_position, -1);
1251 undo_action = RESTORE;
1253 case ActionNode::STORE_POSITION: {
1254 Trace::DeferredCapture* pc =
1255 static_cast<Trace::DeferredCapture*>(action);
1256 if (!clear && store_position == -1) {
1257 store_position = pc->cp_offset();
1260 // For captures we know that stores and clears alternate.
1261 // Other register, are never cleared, and if the occur
1262 // inside a loop, they might be assigned more than once.
1264 // Registers zero and one, aka "capture zero", is
1265 // always set correctly if we succeed. There is no
1266 // need to undo a setting on backtrack, because we
1267 // will set it again or fail.
1268 undo_action = IGNORE;
1270 undo_action = pc->is_capture() ? CLEAR : RESTORE;
1273 DCHECK_EQ(value, 0);
1276 case ActionNode::CLEAR_CAPTURES: {
1277 // Since we're scanning in reverse order, if we've already
1278 // set the position we have to ignore historically earlier
1279 // clearing operations.
1280 if (store_position == -1) {
1283 undo_action = RESTORE;
1285 DCHECK_EQ(value, 0);
1294 // Prepare for the undo-action (e.g., push if it's going to be popped).
1295 if (undo_action == RESTORE) {
1297 RegExpMacroAssembler::StackCheckFlag stack_check =
1298 RegExpMacroAssembler::kNoStackLimitCheck;
1299 if (pushes == push_limit) {
1300 stack_check = RegExpMacroAssembler::kCheckStackLimit;
1304 assembler->PushRegister(reg, stack_check);
1305 registers_to_pop->Set(reg, zone);
1306 } else if (undo_action == CLEAR) {
1307 registers_to_clear->Set(reg, zone);
1309 // Perform the chronologically last action (or accumulated increment)
1310 // for the register.
1311 if (store_position != -1) {
1312 assembler->WriteCurrentPositionToRegister(reg, store_position);
1314 assembler->ClearRegisters(reg, reg);
1315 } else if (absolute) {
1316 assembler->SetRegister(reg, value);
1317 } else if (value != 0) {
1318 assembler->AdvanceRegister(reg, value);
1324 // This is called as we come into a loop choice node and some other tricky
1325 // nodes. It normalizes the state of the code generator to ensure we can
1326 // generate generic code.
1327 void Trace::Flush(RegExpCompiler* compiler, RegExpNode* successor) {
1328 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1330 DCHECK(!is_trivial());
1332 if (actions_ == NULL && backtrack() == NULL) {
1333 // Here we just have some deferred cp advances to fix and we are back to
1334 // a normal situation. We may also have to forget some information gained
1335 // through a quick check that was already performed.
1336 if (cp_offset_ != 0) assembler->AdvanceCurrentPosition(cp_offset_);
1337 // Create a new trivial state and generate the node with that.
1339 successor->Emit(compiler, &new_state);
1343 // Generate deferred actions here along with code to undo them again.
1344 OutSet affected_registers;
1346 if (backtrack() != NULL) {
1347 // Here we have a concrete backtrack location. These are set up by choice
1348 // nodes and so they indicate that we have a deferred save of the current
1349 // position which we may need to emit here.
1350 assembler->PushCurrentPosition();
1353 int max_register = FindAffectedRegisters(&affected_registers,
1355 OutSet registers_to_pop;
1356 OutSet registers_to_clear;
1357 PerformDeferredActions(assembler,
1361 ®isters_to_clear,
1363 if (cp_offset_ != 0) {
1364 assembler->AdvanceCurrentPosition(cp_offset_);
1367 // Create a new trivial state and generate the node with that.
1369 assembler->PushBacktrack(&undo);
1371 successor->Emit(compiler, &new_state);
1373 // On backtrack we need to restore state.
1374 assembler->Bind(&undo);
1375 RestoreAffectedRegisters(assembler,
1378 registers_to_clear);
1379 if (backtrack() == NULL) {
1380 assembler->Backtrack();
1382 assembler->PopCurrentPosition();
1383 assembler->GoTo(backtrack());
1388 void NegativeSubmatchSuccess::Emit(RegExpCompiler* compiler, Trace* trace) {
1389 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1391 // Omit flushing the trace. We discard the entire stack frame anyway.
1393 if (!label()->is_bound()) {
1394 // We are completely independent of the trace, since we ignore it,
1395 // so this code can be used as the generic version.
1396 assembler->Bind(label());
1399 // Throw away everything on the backtrack stack since the start
1400 // of the negative submatch and restore the character position.
1401 assembler->ReadCurrentPositionFromRegister(current_position_register_);
1402 assembler->ReadStackPointerFromRegister(stack_pointer_register_);
1403 if (clear_capture_count_ > 0) {
1404 // Clear any captures that might have been performed during the success
1405 // of the body of the negative look-ahead.
1406 int clear_capture_end = clear_capture_start_ + clear_capture_count_ - 1;
1407 assembler->ClearRegisters(clear_capture_start_, clear_capture_end);
1409 // Now that we have unwound the stack we find at the top of the stack the
1410 // backtrack that the BeginSubmatch node got.
1411 assembler->Backtrack();
1415 void EndNode::Emit(RegExpCompiler* compiler, Trace* trace) {
1416 if (!trace->is_trivial()) {
1417 trace->Flush(compiler, this);
1420 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1421 if (!label()->is_bound()) {
1422 assembler->Bind(label());
1426 assembler->Succeed();
1429 assembler->GoTo(trace->backtrack());
1431 case NEGATIVE_SUBMATCH_SUCCESS:
1432 // This case is handled in a different virtual method.
1439 void GuardedAlternative::AddGuard(Guard* guard, Zone* zone) {
1440 if (guards_ == NULL)
1441 guards_ = new(zone) ZoneList<Guard*>(1, zone);
1442 guards_->Add(guard, zone);
1446 ActionNode* ActionNode::SetRegister(int reg,
1448 RegExpNode* on_success) {
1449 ActionNode* result =
1450 new(on_success->zone()) ActionNode(SET_REGISTER, on_success);
1451 result->data_.u_store_register.reg = reg;
1452 result->data_.u_store_register.value = val;
1457 ActionNode* ActionNode::IncrementRegister(int reg, RegExpNode* on_success) {
1458 ActionNode* result =
1459 new(on_success->zone()) ActionNode(INCREMENT_REGISTER, on_success);
1460 result->data_.u_increment_register.reg = reg;
1465 ActionNode* ActionNode::StorePosition(int reg,
1467 RegExpNode* on_success) {
1468 ActionNode* result =
1469 new(on_success->zone()) ActionNode(STORE_POSITION, on_success);
1470 result->data_.u_position_register.reg = reg;
1471 result->data_.u_position_register.is_capture = is_capture;
1476 ActionNode* ActionNode::ClearCaptures(Interval range,
1477 RegExpNode* on_success) {
1478 ActionNode* result =
1479 new(on_success->zone()) ActionNode(CLEAR_CAPTURES, on_success);
1480 result->data_.u_clear_captures.range_from = range.from();
1481 result->data_.u_clear_captures.range_to = range.to();
1486 ActionNode* ActionNode::BeginSubmatch(int stack_reg,
1488 RegExpNode* on_success) {
1489 ActionNode* result =
1490 new(on_success->zone()) ActionNode(BEGIN_SUBMATCH, on_success);
1491 result->data_.u_submatch.stack_pointer_register = stack_reg;
1492 result->data_.u_submatch.current_position_register = position_reg;
1497 ActionNode* ActionNode::PositiveSubmatchSuccess(int stack_reg,
1499 int clear_register_count,
1500 int clear_register_from,
1501 RegExpNode* on_success) {
1502 ActionNode* result =
1503 new(on_success->zone()) ActionNode(POSITIVE_SUBMATCH_SUCCESS, on_success);
1504 result->data_.u_submatch.stack_pointer_register = stack_reg;
1505 result->data_.u_submatch.current_position_register = position_reg;
1506 result->data_.u_submatch.clear_register_count = clear_register_count;
1507 result->data_.u_submatch.clear_register_from = clear_register_from;
1512 ActionNode* ActionNode::EmptyMatchCheck(int start_register,
1513 int repetition_register,
1514 int repetition_limit,
1515 RegExpNode* on_success) {
1516 ActionNode* result =
1517 new(on_success->zone()) ActionNode(EMPTY_MATCH_CHECK, on_success);
1518 result->data_.u_empty_match_check.start_register = start_register;
1519 result->data_.u_empty_match_check.repetition_register = repetition_register;
1520 result->data_.u_empty_match_check.repetition_limit = repetition_limit;
1525 #define DEFINE_ACCEPT(Type) \
1526 void Type##Node::Accept(NodeVisitor* visitor) { \
1527 visitor->Visit##Type(this); \
1529 FOR_EACH_NODE_TYPE(DEFINE_ACCEPT)
1530 #undef DEFINE_ACCEPT
1533 void LoopChoiceNode::Accept(NodeVisitor* visitor) {
1534 visitor->VisitLoopChoice(this);
1538 // -------------------------------------------------------------------
1542 void ChoiceNode::GenerateGuard(RegExpMacroAssembler* macro_assembler,
1545 switch (guard->op()) {
1547 DCHECK(!trace->mentions_reg(guard->reg()));
1548 macro_assembler->IfRegisterGE(guard->reg(),
1550 trace->backtrack());
1553 DCHECK(!trace->mentions_reg(guard->reg()));
1554 macro_assembler->IfRegisterLT(guard->reg(),
1556 trace->backtrack());
1562 // Returns the number of characters in the equivalence class, omitting those
1563 // that cannot occur in the source string because it is ASCII.
1564 static int GetCaseIndependentLetters(Isolate* isolate, uc16 character,
1565 bool one_byte_subject,
1566 unibrow::uchar* letters) {
1568 isolate->jsregexp_uncanonicalize()->get(character, '\0', letters);
1569 // Unibrow returns 0 or 1 for characters where case independence is
1572 letters[0] = character;
1575 if (!one_byte_subject || character <= String::kMaxOneByteCharCode) {
1579 // The standard requires that non-ASCII characters cannot have ASCII
1580 // character codes in their equivalence class.
1581 // TODO(dcarney): issue 3550 this is not actually true for Latin1 anymore,
1582 // is it? For example, \u00C5 is equivalent to \u212B.
1587 static inline bool EmitSimpleCharacter(Isolate* isolate,
1588 RegExpCompiler* compiler,
1594 RegExpMacroAssembler* assembler = compiler->macro_assembler();
1595 bool bound_checked = false;
1597 assembler->LoadCurrentCharacter(
1601 bound_checked = true;
1603 assembler->CheckNotCharacter(c, on_failure);
1604 return bound_checked;
1608 // Only emits non-letters (things that don't have case). Only used for case
1609 // independent matches.
1610 static inline bool EmitAtomNonLetter(Isolate* isolate,
1611 RegExpCompiler* compiler,
1617 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1618 bool one_byte = compiler->one_byte();
1619 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
1620 int length = GetCaseIndependentLetters(isolate, c, one_byte, chars);
1622 // This can't match. Must be an one-byte subject and a non-one-byte
1623 // character. We do not need to do anything since the one-byte pass
1624 // already handled this.
1625 return false; // Bounds not checked.
1627 bool checked = false;
1628 // We handle the length > 1 case in a later pass.
1630 if (one_byte && c > String::kMaxOneByteCharCodeU) {
1631 // Can't match - see above.
1632 return false; // Bounds not checked.
1635 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1638 macro_assembler->CheckNotCharacter(c, on_failure);
1644 static bool ShortCutEmitCharacterPair(RegExpMacroAssembler* macro_assembler,
1645 bool one_byte, uc16 c1, uc16 c2,
1646 Label* on_failure) {
1649 char_mask = String::kMaxOneByteCharCode;
1651 char_mask = String::kMaxUtf16CodeUnit;
1653 uc16 exor = c1 ^ c2;
1654 // Check whether exor has only one bit set.
1655 if (((exor - 1) & exor) == 0) {
1656 // If c1 and c2 differ only by one bit.
1657 // Ecma262UnCanonicalize always gives the highest number last.
1659 uc16 mask = char_mask ^ exor;
1660 macro_assembler->CheckNotCharacterAfterAnd(c1, mask, on_failure);
1664 uc16 diff = c2 - c1;
1665 if (((diff - 1) & diff) == 0 && c1 >= diff) {
1666 // If the characters differ by 2^n but don't differ by one bit then
1667 // subtract the difference from the found character, then do the or
1668 // trick. We avoid the theoretical case where negative numbers are
1669 // involved in order to simplify code generation.
1670 uc16 mask = char_mask ^ diff;
1671 macro_assembler->CheckNotCharacterAfterMinusAnd(c1 - diff,
1681 typedef bool EmitCharacterFunction(Isolate* isolate,
1682 RegExpCompiler* compiler,
1689 // Only emits letters (things that have case). Only used for case independent
1691 static inline bool EmitAtomLetter(Isolate* isolate,
1692 RegExpCompiler* compiler,
1698 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
1699 bool one_byte = compiler->one_byte();
1700 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
1701 int length = GetCaseIndependentLetters(isolate, c, one_byte, chars);
1702 if (length <= 1) return false;
1703 // We may not need to check against the end of the input string
1704 // if this character lies before a character that matched.
1706 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check);
1709 DCHECK(unibrow::Ecma262UnCanonicalize::kMaxWidth == 4);
1712 if (ShortCutEmitCharacterPair(macro_assembler, one_byte, chars[0],
1713 chars[1], on_failure)) {
1715 macro_assembler->CheckCharacter(chars[0], &ok);
1716 macro_assembler->CheckNotCharacter(chars[1], on_failure);
1717 macro_assembler->Bind(&ok);
1722 macro_assembler->CheckCharacter(chars[3], &ok);
1725 macro_assembler->CheckCharacter(chars[0], &ok);
1726 macro_assembler->CheckCharacter(chars[1], &ok);
1727 macro_assembler->CheckNotCharacter(chars[2], on_failure);
1728 macro_assembler->Bind(&ok);
1738 static void EmitBoundaryTest(RegExpMacroAssembler* masm,
1740 Label* fall_through,
1741 Label* above_or_equal,
1743 if (below != fall_through) {
1744 masm->CheckCharacterLT(border, below);
1745 if (above_or_equal != fall_through) masm->GoTo(above_or_equal);
1747 masm->CheckCharacterGT(border - 1, above_or_equal);
1752 static void EmitDoubleBoundaryTest(RegExpMacroAssembler* masm,
1755 Label* fall_through,
1757 Label* out_of_range) {
1758 if (in_range == fall_through) {
1759 if (first == last) {
1760 masm->CheckNotCharacter(first, out_of_range);
1762 masm->CheckCharacterNotInRange(first, last, out_of_range);
1765 if (first == last) {
1766 masm->CheckCharacter(first, in_range);
1768 masm->CheckCharacterInRange(first, last, in_range);
1770 if (out_of_range != fall_through) masm->GoTo(out_of_range);
1775 // even_label is for ranges[i] to ranges[i + 1] where i - start_index is even.
1776 // odd_label is for ranges[i] to ranges[i + 1] where i - start_index is odd.
1777 static void EmitUseLookupTable(
1778 RegExpMacroAssembler* masm,
1779 ZoneList<int>* ranges,
1783 Label* fall_through,
1786 static const int kSize = RegExpMacroAssembler::kTableSize;
1787 static const int kMask = RegExpMacroAssembler::kTableMask;
1789 int base = (min_char & ~kMask);
1792 // Assert that everything is on one kTableSize page.
1793 for (int i = start_index; i <= end_index; i++) {
1794 DCHECK_EQ(ranges->at(i) & ~kMask, base);
1796 DCHECK(start_index == 0 || (ranges->at(start_index - 1) & ~kMask) <= base);
1800 Label* on_bit_clear;
1802 if (even_label == fall_through) {
1803 on_bit_set = odd_label;
1804 on_bit_clear = even_label;
1807 on_bit_set = even_label;
1808 on_bit_clear = odd_label;
1811 for (int i = 0; i < (ranges->at(start_index) & kMask) && i < kSize; i++) {
1816 for (int i = start_index; i < end_index; i++) {
1817 for (j = (ranges->at(i) & kMask); j < (ranges->at(i + 1) & kMask); j++) {
1822 for (int i = j; i < kSize; i++) {
1825 Factory* factory = masm->zone()->isolate()->factory();
1826 // TODO(erikcorry): Cache these.
1827 Handle<ByteArray> ba = factory->NewByteArray(kSize, TENURED);
1828 for (int i = 0; i < kSize; i++) {
1829 ba->set(i, templ[i]);
1831 masm->CheckBitInTable(ba, on_bit_set);
1832 if (on_bit_clear != fall_through) masm->GoTo(on_bit_clear);
1836 static void CutOutRange(RegExpMacroAssembler* masm,
1837 ZoneList<int>* ranges,
1843 bool odd = (((cut_index - start_index) & 1) == 1);
1844 Label* in_range_label = odd ? odd_label : even_label;
1846 EmitDoubleBoundaryTest(masm,
1847 ranges->at(cut_index),
1848 ranges->at(cut_index + 1) - 1,
1852 DCHECK(!dummy.is_linked());
1853 // Cut out the single range by rewriting the array. This creates a new
1854 // range that is a merger of the two ranges on either side of the one we
1855 // are cutting out. The oddity of the labels is preserved.
1856 for (int j = cut_index; j > start_index; j--) {
1857 ranges->at(j) = ranges->at(j - 1);
1859 for (int j = cut_index + 1; j < end_index; j++) {
1860 ranges->at(j) = ranges->at(j + 1);
1865 // Unicode case. Split the search space into kSize spaces that are handled
1867 static void SplitSearchSpace(ZoneList<int>* ranges,
1870 int* new_start_index,
1873 static const int kSize = RegExpMacroAssembler::kTableSize;
1874 static const int kMask = RegExpMacroAssembler::kTableMask;
1876 int first = ranges->at(start_index);
1877 int last = ranges->at(end_index) - 1;
1879 *new_start_index = start_index;
1880 *border = (ranges->at(start_index) & ~kMask) + kSize;
1881 while (*new_start_index < end_index) {
1882 if (ranges->at(*new_start_index) > *border) break;
1883 (*new_start_index)++;
1885 // new_start_index is the index of the first edge that is beyond the
1886 // current kSize space.
1888 // For very large search spaces we do a binary chop search of the non-Latin1
1889 // space instead of just going to the end of the current kSize space. The
1890 // heuristics are complicated a little by the fact that any 128-character
1891 // encoding space can be quickly tested with a table lookup, so we don't
1892 // wish to do binary chop search at a smaller granularity than that. A
1893 // 128-character space can take up a lot of space in the ranges array if,
1894 // for example, we only want to match every second character (eg. the lower
1895 // case characters on some Unicode pages).
1896 int binary_chop_index = (end_index + start_index) / 2;
1897 // The first test ensures that we get to the code that handles the Latin1
1898 // range with a single not-taken branch, speeding up this important
1899 // character range (even non-Latin1 charset-based text has spaces and
1901 if (*border - 1 > String::kMaxOneByteCharCode && // Latin1 case.
1902 end_index - start_index > (*new_start_index - start_index) * 2 &&
1903 last - first > kSize * 2 && binary_chop_index > *new_start_index &&
1904 ranges->at(binary_chop_index) >= first + 2 * kSize) {
1905 int scan_forward_for_section_border = binary_chop_index;;
1906 int new_border = (ranges->at(binary_chop_index) | kMask) + 1;
1908 while (scan_forward_for_section_border < end_index) {
1909 if (ranges->at(scan_forward_for_section_border) > new_border) {
1910 *new_start_index = scan_forward_for_section_border;
1911 *border = new_border;
1914 scan_forward_for_section_border++;
1918 DCHECK(*new_start_index > start_index);
1919 *new_end_index = *new_start_index - 1;
1920 if (ranges->at(*new_end_index) == *border) {
1923 if (*border >= ranges->at(end_index)) {
1924 *border = ranges->at(end_index);
1925 *new_start_index = end_index; // Won't be used.
1926 *new_end_index = end_index - 1;
1931 // Gets a series of segment boundaries representing a character class. If the
1932 // character is in the range between an even and an odd boundary (counting from
1933 // start_index) then go to even_label, otherwise go to odd_label. We already
1934 // know that the character is in the range of min_char to max_char inclusive.
1935 // Either label can be NULL indicating backtracking. Either label can also be
1936 // equal to the fall_through label.
1937 static void GenerateBranches(RegExpMacroAssembler* masm,
1938 ZoneList<int>* ranges,
1943 Label* fall_through,
1946 int first = ranges->at(start_index);
1947 int last = ranges->at(end_index) - 1;
1949 DCHECK_LT(min_char, first);
1951 // Just need to test if the character is before or on-or-after
1952 // a particular character.
1953 if (start_index == end_index) {
1954 EmitBoundaryTest(masm, first, fall_through, even_label, odd_label);
1958 // Another almost trivial case: There is one interval in the middle that is
1959 // different from the end intervals.
1960 if (start_index + 1 == end_index) {
1961 EmitDoubleBoundaryTest(
1962 masm, first, last, fall_through, even_label, odd_label);
1966 // It's not worth using table lookup if there are very few intervals in the
1968 if (end_index - start_index <= 6) {
1969 // It is faster to test for individual characters, so we look for those
1970 // first, then try arbitrary ranges in the second round.
1971 static int kNoCutIndex = -1;
1972 int cut = kNoCutIndex;
1973 for (int i = start_index; i < end_index; i++) {
1974 if (ranges->at(i) == ranges->at(i + 1) - 1) {
1979 if (cut == kNoCutIndex) cut = start_index;
1981 masm, ranges, start_index, end_index, cut, even_label, odd_label);
1982 DCHECK_GE(end_index - start_index, 2);
1983 GenerateBranches(masm,
1995 // If there are a lot of intervals in the regexp, then we will use tables to
1996 // determine whether the character is inside or outside the character class.
1997 static const int kBits = RegExpMacroAssembler::kTableSizeBits;
1999 if ((max_char >> kBits) == (min_char >> kBits)) {
2000 EmitUseLookupTable(masm,
2011 if ((min_char >> kBits) != (first >> kBits)) {
2012 masm->CheckCharacterLT(first, odd_label);
2013 GenerateBranches(masm,
2025 int new_start_index = 0;
2026 int new_end_index = 0;
2029 SplitSearchSpace(ranges,
2037 Label* above = &handle_rest;
2038 if (border == last + 1) {
2039 // We didn't find any section that started after the limit, so everything
2040 // above the border is one of the terminal labels.
2041 above = (end_index & 1) != (start_index & 1) ? odd_label : even_label;
2042 DCHECK(new_end_index == end_index - 1);
2045 DCHECK_LE(start_index, new_end_index);
2046 DCHECK_LE(new_start_index, end_index);
2047 DCHECK_LT(start_index, new_start_index);
2048 DCHECK_LT(new_end_index, end_index);
2049 DCHECK(new_end_index + 1 == new_start_index ||
2050 (new_end_index + 2 == new_start_index &&
2051 border == ranges->at(new_end_index + 1)));
2052 DCHECK_LT(min_char, border - 1);
2053 DCHECK_LT(border, max_char);
2054 DCHECK_LT(ranges->at(new_end_index), border);
2055 DCHECK(border < ranges->at(new_start_index) ||
2056 (border == ranges->at(new_start_index) &&
2057 new_start_index == end_index &&
2058 new_end_index == end_index - 1 &&
2059 border == last + 1));
2060 DCHECK(new_start_index == 0 || border >= ranges->at(new_start_index - 1));
2062 masm->CheckCharacterGT(border - 1, above);
2064 GenerateBranches(masm,
2073 if (handle_rest.is_linked()) {
2074 masm->Bind(&handle_rest);
2075 bool flip = (new_start_index & 1) != (start_index & 1);
2076 GenerateBranches(masm,
2083 flip ? odd_label : even_label,
2084 flip ? even_label : odd_label);
2089 static void EmitCharClass(RegExpMacroAssembler* macro_assembler,
2090 RegExpCharacterClass* cc, bool one_byte,
2091 Label* on_failure, int cp_offset, bool check_offset,
2092 bool preloaded, Zone* zone) {
2093 ZoneList<CharacterRange>* ranges = cc->ranges(zone);
2094 if (!CharacterRange::IsCanonical(ranges)) {
2095 CharacterRange::Canonicalize(ranges);
2100 max_char = String::kMaxOneByteCharCode;
2102 max_char = String::kMaxUtf16CodeUnit;
2105 int range_count = ranges->length();
2107 int last_valid_range = range_count - 1;
2108 while (last_valid_range >= 0) {
2109 CharacterRange& range = ranges->at(last_valid_range);
2110 if (range.from() <= max_char) {
2116 if (last_valid_range < 0) {
2117 if (!cc->is_negated()) {
2118 macro_assembler->GoTo(on_failure);
2121 macro_assembler->CheckPosition(cp_offset, on_failure);
2126 if (last_valid_range == 0 &&
2127 ranges->at(0).IsEverything(max_char)) {
2128 if (cc->is_negated()) {
2129 macro_assembler->GoTo(on_failure);
2131 // This is a common case hit by non-anchored expressions.
2133 macro_assembler->CheckPosition(cp_offset, on_failure);
2138 if (last_valid_range == 0 &&
2139 !cc->is_negated() &&
2140 ranges->at(0).IsEverything(max_char)) {
2141 // This is a common case hit by non-anchored expressions.
2143 macro_assembler->CheckPosition(cp_offset, on_failure);
2149 macro_assembler->LoadCurrentCharacter(cp_offset, on_failure, check_offset);
2152 if (cc->is_standard(zone) &&
2153 macro_assembler->CheckSpecialCharacterClass(cc->standard_type(),
2159 // A new list with ascending entries. Each entry is a code unit
2160 // where there is a boundary between code units that are part of
2161 // the class and code units that are not. Normally we insert an
2162 // entry at zero which goes to the failure label, but if there
2163 // was already one there we fall through for success on that entry.
2164 // Subsequent entries have alternating meaning (success/failure).
2165 ZoneList<int>* range_boundaries =
2166 new(zone) ZoneList<int>(last_valid_range, zone);
2168 bool zeroth_entry_is_failure = !cc->is_negated();
2170 for (int i = 0; i <= last_valid_range; i++) {
2171 CharacterRange& range = ranges->at(i);
2172 if (range.from() == 0) {
2174 zeroth_entry_is_failure = !zeroth_entry_is_failure;
2176 range_boundaries->Add(range.from(), zone);
2178 range_boundaries->Add(range.to() + 1, zone);
2180 int end_index = range_boundaries->length() - 1;
2181 if (range_boundaries->at(end_index) > max_char) {
2186 GenerateBranches(macro_assembler,
2193 zeroth_entry_is_failure ? &fall_through : on_failure,
2194 zeroth_entry_is_failure ? on_failure : &fall_through);
2195 macro_assembler->Bind(&fall_through);
2199 RegExpNode::~RegExpNode() {
2203 RegExpNode::LimitResult RegExpNode::LimitVersions(RegExpCompiler* compiler,
2205 // If we are generating a greedy loop then don't stop and don't reuse code.
2206 if (trace->stop_node() != NULL) {
2210 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
2211 if (trace->is_trivial()) {
2212 if (label_.is_bound()) {
2213 // We are being asked to generate a generic version, but that's already
2214 // been done so just go to it.
2215 macro_assembler->GoTo(&label_);
2218 if (compiler->recursion_depth() >= RegExpCompiler::kMaxRecursion) {
2219 // To avoid too deep recursion we push the node to the work queue and just
2220 // generate a goto here.
2221 compiler->AddWork(this);
2222 macro_assembler->GoTo(&label_);
2225 // Generate generic version of the node and bind the label for later use.
2226 macro_assembler->Bind(&label_);
2230 // We are being asked to make a non-generic version. Keep track of how many
2231 // non-generic versions we generate so as not to overdo it.
2233 if (compiler->optimize() && trace_count_ < kMaxCopiesCodeGenerated &&
2234 compiler->recursion_depth() <= RegExpCompiler::kMaxRecursion) {
2238 // If we get here code has been generated for this node too many times or
2239 // recursion is too deep. Time to switch to a generic version. The code for
2240 // generic versions above can handle deep recursion properly.
2241 trace->Flush(compiler, this);
2246 int ActionNode::EatsAtLeast(int still_to_find,
2248 bool not_at_start) {
2249 if (budget <= 0) return 0;
2250 if (action_type_ == POSITIVE_SUBMATCH_SUCCESS) return 0; // Rewinds input!
2251 return on_success()->EatsAtLeast(still_to_find,
2257 void ActionNode::FillInBMInfo(int offset,
2259 BoyerMooreLookahead* bm,
2260 bool not_at_start) {
2261 if (action_type_ == BEGIN_SUBMATCH) {
2262 bm->SetRest(offset);
2263 } else if (action_type_ != POSITIVE_SUBMATCH_SUCCESS) {
2264 on_success()->FillInBMInfo(offset, budget - 1, bm, not_at_start);
2266 SaveBMInfo(bm, not_at_start, offset);
2270 int AssertionNode::EatsAtLeast(int still_to_find,
2272 bool not_at_start) {
2273 if (budget <= 0) return 0;
2274 // If we know we are not at the start and we are asked "how many characters
2275 // will you match if you succeed?" then we can answer anything since false
2276 // implies false. So lets just return the max answer (still_to_find) since
2277 // that won't prevent us from preloading a lot of characters for the other
2278 // branches in the node graph.
2279 if (assertion_type() == AT_START && not_at_start) return still_to_find;
2280 return on_success()->EatsAtLeast(still_to_find,
2286 void AssertionNode::FillInBMInfo(int offset,
2288 BoyerMooreLookahead* bm,
2289 bool not_at_start) {
2290 // Match the behaviour of EatsAtLeast on this node.
2291 if (assertion_type() == AT_START && not_at_start) return;
2292 on_success()->FillInBMInfo(offset, budget - 1, bm, not_at_start);
2293 SaveBMInfo(bm, not_at_start, offset);
2297 int BackReferenceNode::EatsAtLeast(int still_to_find,
2299 bool not_at_start) {
2300 if (budget <= 0) return 0;
2301 return on_success()->EatsAtLeast(still_to_find,
2307 int TextNode::EatsAtLeast(int still_to_find,
2309 bool not_at_start) {
2310 int answer = Length();
2311 if (answer >= still_to_find) return answer;
2312 if (budget <= 0) return answer;
2313 // We are not at start after this node so we set the last argument to 'true'.
2314 return answer + on_success()->EatsAtLeast(still_to_find - answer,
2320 int NegativeLookaheadChoiceNode::EatsAtLeast(int still_to_find,
2322 bool not_at_start) {
2323 if (budget <= 0) return 0;
2324 // Alternative 0 is the negative lookahead, alternative 1 is what comes
2326 RegExpNode* node = alternatives_->at(1).node();
2327 return node->EatsAtLeast(still_to_find, budget - 1, not_at_start);
2331 void NegativeLookaheadChoiceNode::GetQuickCheckDetails(
2332 QuickCheckDetails* details,
2333 RegExpCompiler* compiler,
2335 bool not_at_start) {
2336 // Alternative 0 is the negative lookahead, alternative 1 is what comes
2338 RegExpNode* node = alternatives_->at(1).node();
2339 return node->GetQuickCheckDetails(details, compiler, filled_in, not_at_start);
2343 int ChoiceNode::EatsAtLeastHelper(int still_to_find,
2345 RegExpNode* ignore_this_node,
2346 bool not_at_start) {
2347 if (budget <= 0) return 0;
2349 int choice_count = alternatives_->length();
2350 budget = (budget - 1) / choice_count;
2351 for (int i = 0; i < choice_count; i++) {
2352 RegExpNode* node = alternatives_->at(i).node();
2353 if (node == ignore_this_node) continue;
2354 int node_eats_at_least =
2355 node->EatsAtLeast(still_to_find, budget, not_at_start);
2356 if (node_eats_at_least < min) min = node_eats_at_least;
2357 if (min == 0) return 0;
2363 int LoopChoiceNode::EatsAtLeast(int still_to_find,
2365 bool not_at_start) {
2366 return EatsAtLeastHelper(still_to_find,
2373 int ChoiceNode::EatsAtLeast(int still_to_find,
2375 bool not_at_start) {
2376 return EatsAtLeastHelper(still_to_find,
2383 // Takes the left-most 1-bit and smears it out, setting all bits to its right.
2384 static inline uint32_t SmearBitsRight(uint32_t v) {
2394 bool QuickCheckDetails::Rationalize(bool asc) {
2395 bool found_useful_op = false;
2398 char_mask = String::kMaxOneByteCharCode;
2400 char_mask = String::kMaxUtf16CodeUnit;
2405 for (int i = 0; i < characters_; i++) {
2406 Position* pos = &positions_[i];
2407 if ((pos->mask & String::kMaxOneByteCharCode) != 0) {
2408 found_useful_op = true;
2410 mask_ |= (pos->mask & char_mask) << char_shift;
2411 value_ |= (pos->value & char_mask) << char_shift;
2412 char_shift += asc ? 8 : 16;
2414 return found_useful_op;
2418 bool RegExpNode::EmitQuickCheck(RegExpCompiler* compiler,
2419 Trace* bounds_check_trace,
2421 bool preload_has_checked_bounds,
2422 Label* on_possible_success,
2423 QuickCheckDetails* details,
2424 bool fall_through_on_failure) {
2425 if (details->characters() == 0) return false;
2426 GetQuickCheckDetails(
2427 details, compiler, 0, trace->at_start() == Trace::FALSE_VALUE);
2428 if (details->cannot_match()) return false;
2429 if (!details->Rationalize(compiler->one_byte())) return false;
2430 DCHECK(details->characters() == 1 ||
2431 compiler->macro_assembler()->CanReadUnaligned());
2432 uint32_t mask = details->mask();
2433 uint32_t value = details->value();
2435 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2437 if (trace->characters_preloaded() != details->characters()) {
2438 DCHECK(trace->cp_offset() == bounds_check_trace->cp_offset());
2439 // We are attempting to preload the minimum number of characters
2440 // any choice would eat, so if the bounds check fails, then none of the
2441 // choices can succeed, so we can just immediately backtrack, rather
2442 // than go to the next choice.
2443 assembler->LoadCurrentCharacter(trace->cp_offset(),
2444 bounds_check_trace->backtrack(),
2445 !preload_has_checked_bounds,
2446 details->characters());
2450 bool need_mask = true;
2452 if (details->characters() == 1) {
2453 // If number of characters preloaded is 1 then we used a byte or 16 bit
2454 // load so the value is already masked down.
2456 if (compiler->one_byte()) {
2457 char_mask = String::kMaxOneByteCharCode;
2459 char_mask = String::kMaxUtf16CodeUnit;
2461 if ((mask & char_mask) == char_mask) need_mask = false;
2464 // For 2-character preloads in one-byte mode or 1-character preloads in
2465 // two-byte mode we also use a 16 bit load with zero extend.
2466 if (details->characters() == 2 && compiler->one_byte()) {
2467 if ((mask & 0xffff) == 0xffff) need_mask = false;
2468 } else if (details->characters() == 1 && !compiler->one_byte()) {
2469 if ((mask & 0xffff) == 0xffff) need_mask = false;
2471 if (mask == 0xffffffff) need_mask = false;
2475 if (fall_through_on_failure) {
2477 assembler->CheckCharacterAfterAnd(value, mask, on_possible_success);
2479 assembler->CheckCharacter(value, on_possible_success);
2483 assembler->CheckNotCharacterAfterAnd(value, mask, trace->backtrack());
2485 assembler->CheckNotCharacter(value, trace->backtrack());
2492 // Here is the meat of GetQuickCheckDetails (see also the comment on the
2493 // super-class in the .h file).
2495 // We iterate along the text object, building up for each character a
2496 // mask and value that can be used to test for a quick failure to match.
2497 // The masks and values for the positions will be combined into a single
2498 // machine word for the current character width in order to be used in
2499 // generating a quick check.
2500 void TextNode::GetQuickCheckDetails(QuickCheckDetails* details,
2501 RegExpCompiler* compiler,
2502 int characters_filled_in,
2503 bool not_at_start) {
2504 Isolate* isolate = compiler->macro_assembler()->zone()->isolate();
2505 DCHECK(characters_filled_in < details->characters());
2506 int characters = details->characters();
2508 if (compiler->one_byte()) {
2509 char_mask = String::kMaxOneByteCharCode;
2511 char_mask = String::kMaxUtf16CodeUnit;
2513 for (int k = 0; k < elms_->length(); k++) {
2514 TextElement elm = elms_->at(k);
2515 if (elm.text_type() == TextElement::ATOM) {
2516 Vector<const uc16> quarks = elm.atom()->data();
2517 for (int i = 0; i < characters && i < quarks.length(); i++) {
2518 QuickCheckDetails::Position* pos =
2519 details->positions(characters_filled_in);
2521 if (c > char_mask) {
2522 // If we expect a non-Latin1 character from an one-byte string,
2523 // there is no way we can match. Not even case-independent
2524 // matching can turn an Latin1 character into non-Latin1 or
2526 // TODO(dcarney): issue 3550. Verify that this works as expected.
2527 // For example, \u0178 is uppercase of \u00ff (y-umlaut).
2528 details->set_cannot_match();
2529 pos->determines_perfectly = false;
2532 if (compiler->ignore_case()) {
2533 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
2534 int length = GetCaseIndependentLetters(isolate, c,
2535 compiler->one_byte(), chars);
2536 DCHECK(length != 0); // Can only happen if c > char_mask (see above).
2538 // This letter has no case equivalents, so it's nice and simple
2539 // and the mask-compare will determine definitely whether we have
2540 // a match at this character position.
2541 pos->mask = char_mask;
2543 pos->determines_perfectly = true;
2545 uint32_t common_bits = char_mask;
2546 uint32_t bits = chars[0];
2547 for (int j = 1; j < length; j++) {
2548 uint32_t differing_bits = ((chars[j] & common_bits) ^ bits);
2549 common_bits ^= differing_bits;
2550 bits &= common_bits;
2552 // If length is 2 and common bits has only one zero in it then
2553 // our mask and compare instruction will determine definitely
2554 // whether we have a match at this character position. Otherwise
2555 // it can only be an approximate check.
2556 uint32_t one_zero = (common_bits | ~char_mask);
2557 if (length == 2 && ((~one_zero) & ((~one_zero) - 1)) == 0) {
2558 pos->determines_perfectly = true;
2560 pos->mask = common_bits;
2564 // Don't ignore case. Nice simple case where the mask-compare will
2565 // determine definitely whether we have a match at this character
2567 pos->mask = char_mask;
2569 pos->determines_perfectly = true;
2571 characters_filled_in++;
2572 DCHECK(characters_filled_in <= details->characters());
2573 if (characters_filled_in == details->characters()) {
2578 QuickCheckDetails::Position* pos =
2579 details->positions(characters_filled_in);
2580 RegExpCharacterClass* tree = elm.char_class();
2581 ZoneList<CharacterRange>* ranges = tree->ranges(zone());
2582 if (tree->is_negated()) {
2583 // A quick check uses multi-character mask and compare. There is no
2584 // useful way to incorporate a negative char class into this scheme
2585 // so we just conservatively create a mask and value that will always
2590 int first_range = 0;
2591 while (ranges->at(first_range).from() > char_mask) {
2593 if (first_range == ranges->length()) {
2594 details->set_cannot_match();
2595 pos->determines_perfectly = false;
2599 CharacterRange range = ranges->at(first_range);
2600 uc16 from = range.from();
2601 uc16 to = range.to();
2602 if (to > char_mask) {
2605 uint32_t differing_bits = (from ^ to);
2606 // A mask and compare is only perfect if the differing bits form a
2607 // number like 00011111 with one single block of trailing 1s.
2608 if ((differing_bits & (differing_bits + 1)) == 0 &&
2609 from + differing_bits == to) {
2610 pos->determines_perfectly = true;
2612 uint32_t common_bits = ~SmearBitsRight(differing_bits);
2613 uint32_t bits = (from & common_bits);
2614 for (int i = first_range + 1; i < ranges->length(); i++) {
2615 CharacterRange range = ranges->at(i);
2616 uc16 from = range.from();
2617 uc16 to = range.to();
2618 if (from > char_mask) continue;
2619 if (to > char_mask) to = char_mask;
2620 // Here we are combining more ranges into the mask and compare
2621 // value. With each new range the mask becomes more sparse and
2622 // so the chances of a false positive rise. A character class
2623 // with multiple ranges is assumed never to be equivalent to a
2624 // mask and compare operation.
2625 pos->determines_perfectly = false;
2626 uint32_t new_common_bits = (from ^ to);
2627 new_common_bits = ~SmearBitsRight(new_common_bits);
2628 common_bits &= new_common_bits;
2629 bits &= new_common_bits;
2630 uint32_t differing_bits = (from & common_bits) ^ bits;
2631 common_bits ^= differing_bits;
2632 bits &= common_bits;
2634 pos->mask = common_bits;
2637 characters_filled_in++;
2638 DCHECK(characters_filled_in <= details->characters());
2639 if (characters_filled_in == details->characters()) {
2644 DCHECK(characters_filled_in != details->characters());
2645 if (!details->cannot_match()) {
2646 on_success()-> GetQuickCheckDetails(details,
2648 characters_filled_in,
2654 void QuickCheckDetails::Clear() {
2655 for (int i = 0; i < characters_; i++) {
2656 positions_[i].mask = 0;
2657 positions_[i].value = 0;
2658 positions_[i].determines_perfectly = false;
2664 void QuickCheckDetails::Advance(int by, bool one_byte) {
2666 if (by >= characters_) {
2670 for (int i = 0; i < characters_ - by; i++) {
2671 positions_[i] = positions_[by + i];
2673 for (int i = characters_ - by; i < characters_; i++) {
2674 positions_[i].mask = 0;
2675 positions_[i].value = 0;
2676 positions_[i].determines_perfectly = false;
2679 // We could change mask_ and value_ here but we would never advance unless
2680 // they had already been used in a check and they won't be used again because
2681 // it would gain us nothing. So there's no point.
2685 void QuickCheckDetails::Merge(QuickCheckDetails* other, int from_index) {
2686 DCHECK(characters_ == other->characters_);
2687 if (other->cannot_match_) {
2690 if (cannot_match_) {
2694 for (int i = from_index; i < characters_; i++) {
2695 QuickCheckDetails::Position* pos = positions(i);
2696 QuickCheckDetails::Position* other_pos = other->positions(i);
2697 if (pos->mask != other_pos->mask ||
2698 pos->value != other_pos->value ||
2699 !other_pos->determines_perfectly) {
2700 // Our mask-compare operation will be approximate unless we have the
2701 // exact same operation on both sides of the alternation.
2702 pos->determines_perfectly = false;
2704 pos->mask &= other_pos->mask;
2705 pos->value &= pos->mask;
2706 other_pos->value &= pos->mask;
2707 uc16 differing_bits = (pos->value ^ other_pos->value);
2708 pos->mask &= ~differing_bits;
2709 pos->value &= pos->mask;
2716 explicit VisitMarker(NodeInfo* info) : info_(info) {
2717 DCHECK(!info->visited);
2718 info->visited = true;
2721 info_->visited = false;
2728 RegExpNode* SeqRegExpNode::FilterOneByte(int depth, bool ignore_case) {
2729 if (info()->replacement_calculated) return replacement();
2730 if (depth < 0) return this;
2731 DCHECK(!info()->visited);
2732 VisitMarker marker(info());
2733 return FilterSuccessor(depth - 1, ignore_case);
2737 RegExpNode* SeqRegExpNode::FilterSuccessor(int depth, bool ignore_case) {
2738 RegExpNode* next = on_success_->FilterOneByte(depth - 1, ignore_case);
2739 if (next == NULL) return set_replacement(NULL);
2741 return set_replacement(this);
2745 // We need to check for the following characters: 0x39c 0x3bc 0x178.
2746 static inline bool RangeContainsLatin1Equivalents(CharacterRange range) {
2747 // TODO(dcarney): this could be a lot more efficient.
2748 return range.Contains(0x39c) ||
2749 range.Contains(0x3bc) || range.Contains(0x178);
2753 static bool RangesContainLatin1Equivalents(ZoneList<CharacterRange>* ranges) {
2754 for (int i = 0; i < ranges->length(); i++) {
2755 // TODO(dcarney): this could be a lot more efficient.
2756 if (RangeContainsLatin1Equivalents(ranges->at(i))) return true;
2762 RegExpNode* TextNode::FilterOneByte(int depth, bool ignore_case) {
2763 if (info()->replacement_calculated) return replacement();
2764 if (depth < 0) return this;
2765 DCHECK(!info()->visited);
2766 VisitMarker marker(info());
2767 int element_count = elms_->length();
2768 for (int i = 0; i < element_count; i++) {
2769 TextElement elm = elms_->at(i);
2770 if (elm.text_type() == TextElement::ATOM) {
2771 Vector<const uc16> quarks = elm.atom()->data();
2772 for (int j = 0; j < quarks.length(); j++) {
2773 uint16_t c = quarks[j];
2774 if (c <= String::kMaxOneByteCharCode) continue;
2775 if (!ignore_case) return set_replacement(NULL);
2776 // Here, we need to check for characters whose upper and lower cases
2777 // are outside the Latin-1 range.
2778 uint16_t converted = unibrow::Latin1::ConvertNonLatin1ToLatin1(c);
2779 // Character is outside Latin-1 completely
2780 if (converted == 0) return set_replacement(NULL);
2781 // Convert quark to Latin-1 in place.
2782 uint16_t* copy = const_cast<uint16_t*>(quarks.start());
2783 copy[j] = converted;
2786 DCHECK(elm.text_type() == TextElement::CHAR_CLASS);
2787 RegExpCharacterClass* cc = elm.char_class();
2788 ZoneList<CharacterRange>* ranges = cc->ranges(zone());
2789 if (!CharacterRange::IsCanonical(ranges)) {
2790 CharacterRange::Canonicalize(ranges);
2792 // Now they are in order so we only need to look at the first.
2793 int range_count = ranges->length();
2794 if (cc->is_negated()) {
2795 if (range_count != 0 &&
2796 ranges->at(0).from() == 0 &&
2797 ranges->at(0).to() >= String::kMaxOneByteCharCode) {
2798 // This will be handled in a later filter.
2799 if (ignore_case && RangesContainLatin1Equivalents(ranges)) continue;
2800 return set_replacement(NULL);
2803 if (range_count == 0 ||
2804 ranges->at(0).from() > String::kMaxOneByteCharCode) {
2805 // This will be handled in a later filter.
2806 if (ignore_case && RangesContainLatin1Equivalents(ranges)) continue;
2807 return set_replacement(NULL);
2812 return FilterSuccessor(depth - 1, ignore_case);
2816 RegExpNode* LoopChoiceNode::FilterOneByte(int depth, bool ignore_case) {
2817 if (info()->replacement_calculated) return replacement();
2818 if (depth < 0) return this;
2819 if (info()->visited) return this;
2821 VisitMarker marker(info());
2823 RegExpNode* continue_replacement =
2824 continue_node_->FilterOneByte(depth - 1, ignore_case);
2825 // If we can't continue after the loop then there is no sense in doing the
2827 if (continue_replacement == NULL) return set_replacement(NULL);
2830 return ChoiceNode::FilterOneByte(depth - 1, ignore_case);
2834 RegExpNode* ChoiceNode::FilterOneByte(int depth, bool ignore_case) {
2835 if (info()->replacement_calculated) return replacement();
2836 if (depth < 0) return this;
2837 if (info()->visited) return this;
2838 VisitMarker marker(info());
2839 int choice_count = alternatives_->length();
2841 for (int i = 0; i < choice_count; i++) {
2842 GuardedAlternative alternative = alternatives_->at(i);
2843 if (alternative.guards() != NULL && alternative.guards()->length() != 0) {
2844 set_replacement(this);
2850 RegExpNode* survivor = NULL;
2851 for (int i = 0; i < choice_count; i++) {
2852 GuardedAlternative alternative = alternatives_->at(i);
2853 RegExpNode* replacement =
2854 alternative.node()->FilterOneByte(depth - 1, ignore_case);
2855 DCHECK(replacement != this); // No missing EMPTY_MATCH_CHECK.
2856 if (replacement != NULL) {
2857 alternatives_->at(i).set_node(replacement);
2859 survivor = replacement;
2862 if (surviving < 2) return set_replacement(survivor);
2864 set_replacement(this);
2865 if (surviving == choice_count) {
2868 // Only some of the nodes survived the filtering. We need to rebuild the
2869 // alternatives list.
2870 ZoneList<GuardedAlternative>* new_alternatives =
2871 new(zone()) ZoneList<GuardedAlternative>(surviving, zone());
2872 for (int i = 0; i < choice_count; i++) {
2873 RegExpNode* replacement =
2874 alternatives_->at(i).node()->FilterOneByte(depth - 1, ignore_case);
2875 if (replacement != NULL) {
2876 alternatives_->at(i).set_node(replacement);
2877 new_alternatives->Add(alternatives_->at(i), zone());
2880 alternatives_ = new_alternatives;
2885 RegExpNode* NegativeLookaheadChoiceNode::FilterOneByte(int depth,
2887 if (info()->replacement_calculated) return replacement();
2888 if (depth < 0) return this;
2889 if (info()->visited) return this;
2890 VisitMarker marker(info());
2891 // Alternative 0 is the negative lookahead, alternative 1 is what comes
2893 RegExpNode* node = alternatives_->at(1).node();
2894 RegExpNode* replacement = node->FilterOneByte(depth - 1, ignore_case);
2895 if (replacement == NULL) return set_replacement(NULL);
2896 alternatives_->at(1).set_node(replacement);
2898 RegExpNode* neg_node = alternatives_->at(0).node();
2899 RegExpNode* neg_replacement = neg_node->FilterOneByte(depth - 1, ignore_case);
2900 // If the negative lookahead is always going to fail then
2901 // we don't need to check it.
2902 if (neg_replacement == NULL) return set_replacement(replacement);
2903 alternatives_->at(0).set_node(neg_replacement);
2904 return set_replacement(this);
2908 void LoopChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2909 RegExpCompiler* compiler,
2910 int characters_filled_in,
2911 bool not_at_start) {
2912 if (body_can_be_zero_length_ || info()->visited) return;
2913 VisitMarker marker(info());
2914 return ChoiceNode::GetQuickCheckDetails(details,
2916 characters_filled_in,
2921 void LoopChoiceNode::FillInBMInfo(int offset,
2923 BoyerMooreLookahead* bm,
2924 bool not_at_start) {
2925 if (body_can_be_zero_length_ || budget <= 0) {
2926 bm->SetRest(offset);
2927 SaveBMInfo(bm, not_at_start, offset);
2930 ChoiceNode::FillInBMInfo(offset, budget - 1, bm, not_at_start);
2931 SaveBMInfo(bm, not_at_start, offset);
2935 void ChoiceNode::GetQuickCheckDetails(QuickCheckDetails* details,
2936 RegExpCompiler* compiler,
2937 int characters_filled_in,
2938 bool not_at_start) {
2939 not_at_start = (not_at_start || not_at_start_);
2940 int choice_count = alternatives_->length();
2941 DCHECK(choice_count > 0);
2942 alternatives_->at(0).node()->GetQuickCheckDetails(details,
2944 characters_filled_in,
2946 for (int i = 1; i < choice_count; i++) {
2947 QuickCheckDetails new_details(details->characters());
2948 RegExpNode* node = alternatives_->at(i).node();
2949 node->GetQuickCheckDetails(&new_details, compiler,
2950 characters_filled_in,
2952 // Here we merge the quick match details of the two branches.
2953 details->Merge(&new_details, characters_filled_in);
2958 // Check for [0-9A-Z_a-z].
2959 static void EmitWordCheck(RegExpMacroAssembler* assembler,
2962 bool fall_through_on_word) {
2963 if (assembler->CheckSpecialCharacterClass(
2964 fall_through_on_word ? 'w' : 'W',
2965 fall_through_on_word ? non_word : word)) {
2966 // Optimized implementation available.
2969 assembler->CheckCharacterGT('z', non_word);
2970 assembler->CheckCharacterLT('0', non_word);
2971 assembler->CheckCharacterGT('a' - 1, word);
2972 assembler->CheckCharacterLT('9' + 1, word);
2973 assembler->CheckCharacterLT('A', non_word);
2974 assembler->CheckCharacterLT('Z' + 1, word);
2975 if (fall_through_on_word) {
2976 assembler->CheckNotCharacter('_', non_word);
2978 assembler->CheckCharacter('_', word);
2983 // Emit the code to check for a ^ in multiline mode (1-character lookbehind
2984 // that matches newline or the start of input).
2985 static void EmitHat(RegExpCompiler* compiler,
2986 RegExpNode* on_success,
2988 RegExpMacroAssembler* assembler = compiler->macro_assembler();
2989 // We will be loading the previous character into the current character
2991 Trace new_trace(*trace);
2992 new_trace.InvalidateCurrentCharacter();
2995 if (new_trace.cp_offset() == 0) {
2996 // The start of input counts as a newline in this context, so skip to
2997 // ok if we are at the start.
2998 assembler->CheckAtStart(&ok);
3000 // We already checked that we are not at the start of input so it must be
3001 // OK to load the previous character.
3002 assembler->LoadCurrentCharacter(new_trace.cp_offset() -1,
3003 new_trace.backtrack(),
3005 if (!assembler->CheckSpecialCharacterClass('n',
3006 new_trace.backtrack())) {
3007 // Newline means \n, \r, 0x2028 or 0x2029.
3008 if (!compiler->one_byte()) {
3009 assembler->CheckCharacterAfterAnd(0x2028, 0xfffe, &ok);
3011 assembler->CheckCharacter('\n', &ok);
3012 assembler->CheckNotCharacter('\r', new_trace.backtrack());
3014 assembler->Bind(&ok);
3015 on_success->Emit(compiler, &new_trace);
3019 // Emit the code to handle \b and \B (word-boundary or non-word-boundary).
3020 void AssertionNode::EmitBoundaryCheck(RegExpCompiler* compiler, Trace* trace) {
3021 RegExpMacroAssembler* assembler = compiler->macro_assembler();
3022 Trace::TriBool next_is_word_character = Trace::UNKNOWN;
3023 bool not_at_start = (trace->at_start() == Trace::FALSE_VALUE);
3024 BoyerMooreLookahead* lookahead = bm_info(not_at_start);
3025 if (lookahead == NULL) {
3027 Min(kMaxLookaheadForBoyerMoore, EatsAtLeast(kMaxLookaheadForBoyerMoore,
3030 if (eats_at_least >= 1) {
3031 BoyerMooreLookahead* bm =
3032 new(zone()) BoyerMooreLookahead(eats_at_least, compiler, zone());
3033 FillInBMInfo(0, kRecursionBudget, bm, not_at_start);
3034 if (bm->at(0)->is_non_word())
3035 next_is_word_character = Trace::FALSE_VALUE;
3036 if (bm->at(0)->is_word()) next_is_word_character = Trace::TRUE_VALUE;
3039 if (lookahead->at(0)->is_non_word())
3040 next_is_word_character = Trace::FALSE_VALUE;
3041 if (lookahead->at(0)->is_word())
3042 next_is_word_character = Trace::TRUE_VALUE;
3044 bool at_boundary = (assertion_type_ == AssertionNode::AT_BOUNDARY);
3045 if (next_is_word_character == Trace::UNKNOWN) {
3046 Label before_non_word;
3048 if (trace->characters_preloaded() != 1) {
3049 assembler->LoadCurrentCharacter(trace->cp_offset(), &before_non_word);
3051 // Fall through on non-word.
3052 EmitWordCheck(assembler, &before_word, &before_non_word, false);
3053 // Next character is not a word character.
3054 assembler->Bind(&before_non_word);
3056 BacktrackIfPrevious(compiler, trace, at_boundary ? kIsNonWord : kIsWord);
3057 assembler->GoTo(&ok);
3059 assembler->Bind(&before_word);
3060 BacktrackIfPrevious(compiler, trace, at_boundary ? kIsWord : kIsNonWord);
3061 assembler->Bind(&ok);
3062 } else if (next_is_word_character == Trace::TRUE_VALUE) {
3063 BacktrackIfPrevious(compiler, trace, at_boundary ? kIsWord : kIsNonWord);
3065 DCHECK(next_is_word_character == Trace::FALSE_VALUE);
3066 BacktrackIfPrevious(compiler, trace, at_boundary ? kIsNonWord : kIsWord);
3071 void AssertionNode::BacktrackIfPrevious(
3072 RegExpCompiler* compiler,
3074 AssertionNode::IfPrevious backtrack_if_previous) {
3075 RegExpMacroAssembler* assembler = compiler->macro_assembler();
3076 Trace new_trace(*trace);
3077 new_trace.InvalidateCurrentCharacter();
3079 Label fall_through, dummy;
3081 Label* non_word = backtrack_if_previous == kIsNonWord ?
3082 new_trace.backtrack() :
3084 Label* word = backtrack_if_previous == kIsNonWord ?
3086 new_trace.backtrack();
3088 if (new_trace.cp_offset() == 0) {
3089 // The start of input counts as a non-word character, so the question is
3090 // decided if we are at the start.
3091 assembler->CheckAtStart(non_word);
3093 // We already checked that we are not at the start of input so it must be
3094 // OK to load the previous character.
3095 assembler->LoadCurrentCharacter(new_trace.cp_offset() - 1, &dummy, false);
3096 EmitWordCheck(assembler, word, non_word, backtrack_if_previous == kIsNonWord);
3098 assembler->Bind(&fall_through);
3099 on_success()->Emit(compiler, &new_trace);
3103 void AssertionNode::GetQuickCheckDetails(QuickCheckDetails* details,
3104 RegExpCompiler* compiler,
3106 bool not_at_start) {
3107 if (assertion_type_ == AT_START && not_at_start) {
3108 details->set_cannot_match();
3111 return on_success()->GetQuickCheckDetails(details,
3118 void AssertionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3119 RegExpMacroAssembler* assembler = compiler->macro_assembler();
3120 switch (assertion_type_) {
3123 assembler->CheckPosition(trace->cp_offset(), &ok);
3124 assembler->GoTo(trace->backtrack());
3125 assembler->Bind(&ok);
3129 if (trace->at_start() == Trace::FALSE_VALUE) {
3130 assembler->GoTo(trace->backtrack());
3133 if (trace->at_start() == Trace::UNKNOWN) {
3134 assembler->CheckNotAtStart(trace->backtrack());
3135 Trace at_start_trace = *trace;
3136 at_start_trace.set_at_start(true);
3137 on_success()->Emit(compiler, &at_start_trace);
3143 EmitHat(compiler, on_success(), trace);
3146 case AT_NON_BOUNDARY: {
3147 EmitBoundaryCheck(compiler, trace);
3151 on_success()->Emit(compiler, trace);
3155 static bool DeterminedAlready(QuickCheckDetails* quick_check, int offset) {
3156 if (quick_check == NULL) return false;
3157 if (offset >= quick_check->characters()) return false;
3158 return quick_check->positions(offset)->determines_perfectly;
3162 static void UpdateBoundsCheck(int index, int* checked_up_to) {
3163 if (index > *checked_up_to) {
3164 *checked_up_to = index;
3169 // We call this repeatedly to generate code for each pass over the text node.
3170 // The passes are in increasing order of difficulty because we hope one
3171 // of the first passes will fail in which case we are saved the work of the
3172 // later passes. for example for the case independent regexp /%[asdfghjkl]a/
3173 // we will check the '%' in the first pass, the case independent 'a' in the
3174 // second pass and the character class in the last pass.
3176 // The passes are done from right to left, so for example to test for /bar/
3177 // we will first test for an 'r' with offset 2, then an 'a' with offset 1
3178 // and then a 'b' with offset 0. This means we can avoid the end-of-input
3179 // bounds check most of the time. In the example we only need to check for
3180 // end-of-input when loading the putative 'r'.
3182 // A slight complication involves the fact that the first character may already
3183 // be fetched into a register by the previous node. In this case we want to
3184 // do the test for that character first. We do this in separate passes. The
3185 // 'preloaded' argument indicates that we are doing such a 'pass'. If such a
3186 // pass has been performed then subsequent passes will have true in
3187 // first_element_checked to indicate that that character does not need to be
3190 // In addition to all this we are passed a Trace, which can
3191 // contain an AlternativeGeneration object. In this AlternativeGeneration
3192 // object we can see details of any quick check that was already passed in
3193 // order to get to the code we are now generating. The quick check can involve
3194 // loading characters, which means we do not need to recheck the bounds
3195 // up to the limit the quick check already checked. In addition the quick
3196 // check can have involved a mask and compare operation which may simplify
3197 // or obviate the need for further checks at some character positions.
3198 void TextNode::TextEmitPass(RegExpCompiler* compiler,
3199 TextEmitPassType pass,
3202 bool first_element_checked,
3203 int* checked_up_to) {
3204 RegExpMacroAssembler* assembler = compiler->macro_assembler();
3205 Isolate* isolate = assembler->zone()->isolate();
3206 bool one_byte = compiler->one_byte();
3207 Label* backtrack = trace->backtrack();
3208 QuickCheckDetails* quick_check = trace->quick_check_performed();
3209 int element_count = elms_->length();
3210 for (int i = preloaded ? 0 : element_count - 1; i >= 0; i--) {
3211 TextElement elm = elms_->at(i);
3212 int cp_offset = trace->cp_offset() + elm.cp_offset();
3213 if (elm.text_type() == TextElement::ATOM) {
3214 Vector<const uc16> quarks = elm.atom()->data();
3215 for (int j = preloaded ? 0 : quarks.length() - 1; j >= 0; j--) {
3216 if (first_element_checked && i == 0 && j == 0) continue;
3217 if (DeterminedAlready(quick_check, elm.cp_offset() + j)) continue;
3218 EmitCharacterFunction* emit_function = NULL;
3220 case NON_LATIN1_MATCH:
3222 if (quarks[j] > String::kMaxOneByteCharCode) {
3223 assembler->GoTo(backtrack);
3227 case NON_LETTER_CHARACTER_MATCH:
3228 emit_function = &EmitAtomNonLetter;
3230 case SIMPLE_CHARACTER_MATCH:
3231 emit_function = &EmitSimpleCharacter;
3233 case CASE_CHARACTER_MATCH:
3234 emit_function = &EmitAtomLetter;
3239 if (emit_function != NULL) {
3240 bool bound_checked = emit_function(isolate,
3245 *checked_up_to < cp_offset + j,
3247 if (bound_checked) UpdateBoundsCheck(cp_offset + j, checked_up_to);
3251 DCHECK_EQ(TextElement::CHAR_CLASS, elm.text_type());
3252 if (pass == CHARACTER_CLASS_MATCH) {
3253 if (first_element_checked && i == 0) continue;
3254 if (DeterminedAlready(quick_check, elm.cp_offset())) continue;
3255 RegExpCharacterClass* cc = elm.char_class();
3256 EmitCharClass(assembler, cc, one_byte, backtrack, cp_offset,
3257 *checked_up_to < cp_offset, preloaded, zone());
3258 UpdateBoundsCheck(cp_offset, checked_up_to);
3265 int TextNode::Length() {
3266 TextElement elm = elms_->last();
3267 DCHECK(elm.cp_offset() >= 0);
3268 return elm.cp_offset() + elm.length();
3272 bool TextNode::SkipPass(int int_pass, bool ignore_case) {
3273 TextEmitPassType pass = static_cast<TextEmitPassType>(int_pass);
3275 return pass == SIMPLE_CHARACTER_MATCH;
3277 return pass == NON_LETTER_CHARACTER_MATCH || pass == CASE_CHARACTER_MATCH;
3282 // This generates the code to match a text node. A text node can contain
3283 // straight character sequences (possibly to be matched in a case-independent
3284 // way) and character classes. For efficiency we do not do this in a single
3285 // pass from left to right. Instead we pass over the text node several times,
3286 // emitting code for some character positions every time. See the comment on
3287 // TextEmitPass for details.
3288 void TextNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3289 LimitResult limit_result = LimitVersions(compiler, trace);
3290 if (limit_result == DONE) return;
3291 DCHECK(limit_result == CONTINUE);
3293 if (trace->cp_offset() + Length() > RegExpMacroAssembler::kMaxCPOffset) {
3294 compiler->SetRegExpTooBig();
3298 if (compiler->one_byte()) {
3300 TextEmitPass(compiler, NON_LATIN1_MATCH, false, trace, false, &dummy);
3303 bool first_elt_done = false;
3304 int bound_checked_to = trace->cp_offset() - 1;
3305 bound_checked_to += trace->bound_checked_up_to();
3307 // If a character is preloaded into the current character register then
3309 if (trace->characters_preloaded() == 1) {
3310 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
3311 if (!SkipPass(pass, compiler->ignore_case())) {
3312 TextEmitPass(compiler,
3313 static_cast<TextEmitPassType>(pass),
3320 first_elt_done = true;
3323 for (int pass = kFirstRealPass; pass <= kLastPass; pass++) {
3324 if (!SkipPass(pass, compiler->ignore_case())) {
3325 TextEmitPass(compiler,
3326 static_cast<TextEmitPassType>(pass),
3334 Trace successor_trace(*trace);
3335 successor_trace.set_at_start(false);
3336 successor_trace.AdvanceCurrentPositionInTrace(Length(), compiler);
3337 RecursionCheck rc(compiler);
3338 on_success()->Emit(compiler, &successor_trace);
3342 void Trace::InvalidateCurrentCharacter() {
3343 characters_preloaded_ = 0;
3347 void Trace::AdvanceCurrentPositionInTrace(int by, RegExpCompiler* compiler) {
3349 // We don't have an instruction for shifting the current character register
3350 // down or for using a shifted value for anything so lets just forget that
3351 // we preloaded any characters into it.
3352 characters_preloaded_ = 0;
3353 // Adjust the offsets of the quick check performed information. This
3354 // information is used to find out what we already determined about the
3355 // characters by means of mask and compare.
3356 quick_check_performed_.Advance(by, compiler->one_byte());
3358 if (cp_offset_ > RegExpMacroAssembler::kMaxCPOffset) {
3359 compiler->SetRegExpTooBig();
3362 bound_checked_up_to_ = Max(0, bound_checked_up_to_ - by);
3366 void TextNode::MakeCaseIndependent(bool is_one_byte) {
3367 int element_count = elms_->length();
3368 for (int i = 0; i < element_count; i++) {
3369 TextElement elm = elms_->at(i);
3370 if (elm.text_type() == TextElement::CHAR_CLASS) {
3371 RegExpCharacterClass* cc = elm.char_class();
3372 // None of the standard character classes is different in the case
3373 // independent case and it slows us down if we don't know that.
3374 if (cc->is_standard(zone())) continue;
3375 ZoneList<CharacterRange>* ranges = cc->ranges(zone());
3376 int range_count = ranges->length();
3377 for (int j = 0; j < range_count; j++) {
3378 ranges->at(j).AddCaseEquivalents(ranges, is_one_byte, zone());
3385 int TextNode::GreedyLoopTextLength() {
3386 TextElement elm = elms_->at(elms_->length() - 1);
3387 return elm.cp_offset() + elm.length();
3391 RegExpNode* TextNode::GetSuccessorOfOmnivorousTextNode(
3392 RegExpCompiler* compiler) {
3393 if (elms_->length() != 1) return NULL;
3394 TextElement elm = elms_->at(0);
3395 if (elm.text_type() != TextElement::CHAR_CLASS) return NULL;
3396 RegExpCharacterClass* node = elm.char_class();
3397 ZoneList<CharacterRange>* ranges = node->ranges(zone());
3398 if (!CharacterRange::IsCanonical(ranges)) {
3399 CharacterRange::Canonicalize(ranges);
3401 if (node->is_negated()) {
3402 return ranges->length() == 0 ? on_success() : NULL;
3404 if (ranges->length() != 1) return NULL;
3406 if (compiler->one_byte()) {
3407 max_char = String::kMaxOneByteCharCode;
3409 max_char = String::kMaxUtf16CodeUnit;
3411 return ranges->at(0).IsEverything(max_char) ? on_success() : NULL;
3415 // Finds the fixed match length of a sequence of nodes that goes from
3416 // this alternative and back to this choice node. If there are variable
3417 // length nodes or other complications in the way then return a sentinel
3418 // value indicating that a greedy loop cannot be constructed.
3419 int ChoiceNode::GreedyLoopTextLengthForAlternative(
3420 GuardedAlternative* alternative) {
3422 RegExpNode* node = alternative->node();
3423 // Later we will generate code for all these text nodes using recursion
3424 // so we have to limit the max number.
3425 int recursion_depth = 0;
3426 while (node != this) {
3427 if (recursion_depth++ > RegExpCompiler::kMaxRecursion) {
3428 return kNodeIsTooComplexForGreedyLoops;
3430 int node_length = node->GreedyLoopTextLength();
3431 if (node_length == kNodeIsTooComplexForGreedyLoops) {
3432 return kNodeIsTooComplexForGreedyLoops;
3434 length += node_length;
3435 SeqRegExpNode* seq_node = static_cast<SeqRegExpNode*>(node);
3436 node = seq_node->on_success();
3442 void LoopChoiceNode::AddLoopAlternative(GuardedAlternative alt) {
3443 DCHECK_EQ(loop_node_, NULL);
3444 AddAlternative(alt);
3445 loop_node_ = alt.node();
3449 void LoopChoiceNode::AddContinueAlternative(GuardedAlternative alt) {
3450 DCHECK_EQ(continue_node_, NULL);
3451 AddAlternative(alt);
3452 continue_node_ = alt.node();
3456 void LoopChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3457 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
3458 if (trace->stop_node() == this) {
3459 // Back edge of greedy optimized loop node graph.
3461 GreedyLoopTextLengthForAlternative(&(alternatives_->at(0)));
3462 DCHECK(text_length != kNodeIsTooComplexForGreedyLoops);
3463 // Update the counter-based backtracking info on the stack. This is an
3464 // optimization for greedy loops (see below).
3465 DCHECK(trace->cp_offset() == text_length);
3466 macro_assembler->AdvanceCurrentPosition(text_length);
3467 macro_assembler->GoTo(trace->loop_label());
3470 DCHECK(trace->stop_node() == NULL);
3471 if (!trace->is_trivial()) {
3472 trace->Flush(compiler, this);
3475 ChoiceNode::Emit(compiler, trace);
3479 int ChoiceNode::CalculatePreloadCharacters(RegExpCompiler* compiler,
3480 int eats_at_least) {
3481 int preload_characters = Min(4, eats_at_least);
3482 if (compiler->macro_assembler()->CanReadUnaligned()) {
3483 bool one_byte = compiler->one_byte();
3485 if (preload_characters > 4) preload_characters = 4;
3486 // We can't preload 3 characters because there is no machine instruction
3487 // to do that. We can't just load 4 because we could be reading
3488 // beyond the end of the string, which could cause a memory fault.
3489 if (preload_characters == 3) preload_characters = 2;
3491 if (preload_characters > 2) preload_characters = 2;
3494 if (preload_characters > 1) preload_characters = 1;
3496 return preload_characters;
3500 // This class is used when generating the alternatives in a choice node. It
3501 // records the way the alternative is being code generated.
3502 class AlternativeGeneration: public Malloced {
3504 AlternativeGeneration()
3505 : possible_success(),
3506 expects_preload(false),
3508 quick_check_details() { }
3509 Label possible_success;
3510 bool expects_preload;
3512 QuickCheckDetails quick_check_details;
3516 // Creates a list of AlternativeGenerations. If the list has a reasonable
3517 // size then it is on the stack, otherwise the excess is on the heap.
3518 class AlternativeGenerationList {
3520 AlternativeGenerationList(int count, Zone* zone)
3521 : alt_gens_(count, zone) {
3522 for (int i = 0; i < count && i < kAFew; i++) {
3523 alt_gens_.Add(a_few_alt_gens_ + i, zone);
3525 for (int i = kAFew; i < count; i++) {
3526 alt_gens_.Add(new AlternativeGeneration(), zone);
3529 ~AlternativeGenerationList() {
3530 for (int i = kAFew; i < alt_gens_.length(); i++) {
3531 delete alt_gens_[i];
3532 alt_gens_[i] = NULL;
3536 AlternativeGeneration* at(int i) {
3537 return alt_gens_[i];
3541 static const int kAFew = 10;
3542 ZoneList<AlternativeGeneration*> alt_gens_;
3543 AlternativeGeneration a_few_alt_gens_[kAFew];
3547 // The '2' variant is has inclusive from and exclusive to.
3548 // This covers \s as defined in ECMA-262 5.1, 15.10.2.12,
3549 // which include WhiteSpace (7.2) or LineTerminator (7.3) values.
3550 static const int kSpaceRanges[] = { '\t', '\r' + 1, ' ', ' ' + 1,
3551 0x00A0, 0x00A1, 0x1680, 0x1681, 0x180E, 0x180F, 0x2000, 0x200B,
3552 0x2028, 0x202A, 0x202F, 0x2030, 0x205F, 0x2060, 0x3000, 0x3001,
3553 0xFEFF, 0xFF00, 0x10000 };
3554 static const int kSpaceRangeCount = arraysize(kSpaceRanges);
3556 static const int kWordRanges[] = {
3557 '0', '9' + 1, 'A', 'Z' + 1, '_', '_' + 1, 'a', 'z' + 1, 0x10000 };
3558 static const int kWordRangeCount = arraysize(kWordRanges);
3559 static const int kDigitRanges[] = { '0', '9' + 1, 0x10000 };
3560 static const int kDigitRangeCount = arraysize(kDigitRanges);
3561 static const int kSurrogateRanges[] = { 0xd800, 0xe000, 0x10000 };
3562 static const int kSurrogateRangeCount = arraysize(kSurrogateRanges);
3563 static const int kLineTerminatorRanges[] = { 0x000A, 0x000B, 0x000D, 0x000E,
3564 0x2028, 0x202A, 0x10000 };
3565 static const int kLineTerminatorRangeCount = arraysize(kLineTerminatorRanges);
3568 void BoyerMoorePositionInfo::Set(int character) {
3569 SetInterval(Interval(character, character));
3573 void BoyerMoorePositionInfo::SetInterval(const Interval& interval) {
3574 s_ = AddRange(s_, kSpaceRanges, kSpaceRangeCount, interval);
3575 w_ = AddRange(w_, kWordRanges, kWordRangeCount, interval);
3576 d_ = AddRange(d_, kDigitRanges, kDigitRangeCount, interval);
3578 AddRange(surrogate_, kSurrogateRanges, kSurrogateRangeCount, interval);
3579 if (interval.to() - interval.from() >= kMapSize - 1) {
3580 if (map_count_ != kMapSize) {
3581 map_count_ = kMapSize;
3582 for (int i = 0; i < kMapSize; i++) map_->at(i) = true;
3586 for (int i = interval.from(); i <= interval.to(); i++) {
3587 int mod_character = (i & kMask);
3588 if (!map_->at(mod_character)) {
3590 map_->at(mod_character) = true;
3592 if (map_count_ == kMapSize) return;
3597 void BoyerMoorePositionInfo::SetAll() {
3598 s_ = w_ = d_ = kLatticeUnknown;
3599 if (map_count_ != kMapSize) {
3600 map_count_ = kMapSize;
3601 for (int i = 0; i < kMapSize; i++) map_->at(i) = true;
3606 BoyerMooreLookahead::BoyerMooreLookahead(
3607 int length, RegExpCompiler* compiler, Zone* zone)
3609 compiler_(compiler) {
3610 if (compiler->one_byte()) {
3611 max_char_ = String::kMaxOneByteCharCode;
3613 max_char_ = String::kMaxUtf16CodeUnit;
3615 bitmaps_ = new(zone) ZoneList<BoyerMoorePositionInfo*>(length, zone);
3616 for (int i = 0; i < length; i++) {
3617 bitmaps_->Add(new(zone) BoyerMoorePositionInfo(zone), zone);
3622 // Find the longest range of lookahead that has the fewest number of different
3623 // characters that can occur at a given position. Since we are optimizing two
3624 // different parameters at once this is a tradeoff.
3625 bool BoyerMooreLookahead::FindWorthwhileInterval(int* from, int* to) {
3626 int biggest_points = 0;
3627 // If more than 32 characters out of 128 can occur it is unlikely that we can
3628 // be lucky enough to step forwards much of the time.
3629 const int kMaxMax = 32;
3630 for (int max_number_of_chars = 4;
3631 max_number_of_chars < kMaxMax;
3632 max_number_of_chars *= 2) {
3634 FindBestInterval(max_number_of_chars, biggest_points, from, to);
3636 if (biggest_points == 0) return false;
3641 // Find the highest-points range between 0 and length_ where the character
3642 // information is not too vague. 'Too vague' means that there are more than
3643 // max_number_of_chars that can occur at this position. Calculates the number
3644 // of points as the product of width-of-the-range and
3645 // probability-of-finding-one-of-the-characters, where the probability is
3646 // calculated using the frequency distribution of the sample subject string.
3647 int BoyerMooreLookahead::FindBestInterval(
3648 int max_number_of_chars, int old_biggest_points, int* from, int* to) {
3649 int biggest_points = old_biggest_points;
3650 static const int kSize = RegExpMacroAssembler::kTableSize;
3651 for (int i = 0; i < length_; ) {
3652 while (i < length_ && Count(i) > max_number_of_chars) i++;
3653 if (i == length_) break;
3654 int remembered_from = i;
3655 bool union_map[kSize];
3656 for (int j = 0; j < kSize; j++) union_map[j] = false;
3657 while (i < length_ && Count(i) <= max_number_of_chars) {
3658 BoyerMoorePositionInfo* map = bitmaps_->at(i);
3659 for (int j = 0; j < kSize; j++) union_map[j] |= map->at(j);
3663 for (int j = 0; j < kSize; j++) {
3665 // Add 1 to the frequency to give a small per-character boost for
3666 // the cases where our sampling is not good enough and many
3667 // characters have a frequency of zero. This means the frequency
3668 // can theoretically be up to 2*kSize though we treat it mostly as
3669 // a fraction of kSize.
3670 frequency += compiler_->frequency_collator()->Frequency(j) + 1;
3673 // We use the probability of skipping times the distance we are skipping to
3674 // judge the effectiveness of this. Actually we have a cut-off: By
3675 // dividing by 2 we switch off the skipping if the probability of skipping
3676 // is less than 50%. This is because the multibyte mask-and-compare
3677 // skipping in quickcheck is more likely to do well on this case.
3678 bool in_quickcheck_range =
3679 ((i - remembered_from < 4) ||
3680 (compiler_->one_byte() ? remembered_from <= 4 : remembered_from <= 2));
3681 // Called 'probability' but it is only a rough estimate and can actually
3682 // be outside the 0-kSize range.
3683 int probability = (in_quickcheck_range ? kSize / 2 : kSize) - frequency;
3684 int points = (i - remembered_from) * probability;
3685 if (points > biggest_points) {
3686 *from = remembered_from;
3688 biggest_points = points;
3691 return biggest_points;
3695 // Take all the characters that will not prevent a successful match if they
3696 // occur in the subject string in the range between min_lookahead and
3697 // max_lookahead (inclusive) measured from the current position. If the
3698 // character at max_lookahead offset is not one of these characters, then we
3699 // can safely skip forwards by the number of characters in the range.
3700 int BoyerMooreLookahead::GetSkipTable(int min_lookahead,
3702 Handle<ByteArray> boolean_skip_table) {
3703 const int kSize = RegExpMacroAssembler::kTableSize;
3705 const int kSkipArrayEntry = 0;
3706 const int kDontSkipArrayEntry = 1;
3708 for (int i = 0; i < kSize; i++) {
3709 boolean_skip_table->set(i, kSkipArrayEntry);
3711 int skip = max_lookahead + 1 - min_lookahead;
3713 for (int i = max_lookahead; i >= min_lookahead; i--) {
3714 BoyerMoorePositionInfo* map = bitmaps_->at(i);
3715 for (int j = 0; j < kSize; j++) {
3717 boolean_skip_table->set(j, kDontSkipArrayEntry);
3726 // See comment above on the implementation of GetSkipTable.
3727 void BoyerMooreLookahead::EmitSkipInstructions(RegExpMacroAssembler* masm) {
3728 const int kSize = RegExpMacroAssembler::kTableSize;
3730 int min_lookahead = 0;
3731 int max_lookahead = 0;
3733 if (!FindWorthwhileInterval(&min_lookahead, &max_lookahead)) return;
3735 bool found_single_character = false;
3736 int single_character = 0;
3737 for (int i = max_lookahead; i >= min_lookahead; i--) {
3738 BoyerMoorePositionInfo* map = bitmaps_->at(i);
3739 if (map->map_count() > 1 ||
3740 (found_single_character && map->map_count() != 0)) {
3741 found_single_character = false;
3744 for (int j = 0; j < kSize; j++) {
3746 found_single_character = true;
3747 single_character = j;
3753 int lookahead_width = max_lookahead + 1 - min_lookahead;
3755 if (found_single_character && lookahead_width == 1 && max_lookahead < 3) {
3756 // The mask-compare can probably handle this better.
3760 if (found_single_character) {
3763 masm->LoadCurrentCharacter(max_lookahead, &cont, true);
3764 if (max_char_ > kSize) {
3765 masm->CheckCharacterAfterAnd(single_character,
3766 RegExpMacroAssembler::kTableMask,
3769 masm->CheckCharacter(single_character, &cont);
3771 masm->AdvanceCurrentPosition(lookahead_width);
3777 Factory* factory = masm->zone()->isolate()->factory();
3778 Handle<ByteArray> boolean_skip_table = factory->NewByteArray(kSize, TENURED);
3779 int skip_distance = GetSkipTable(
3780 min_lookahead, max_lookahead, boolean_skip_table);
3781 DCHECK(skip_distance != 0);
3785 masm->LoadCurrentCharacter(max_lookahead, &cont, true);
3786 masm->CheckBitInTable(boolean_skip_table, &cont);
3787 masm->AdvanceCurrentPosition(skip_distance);
3793 /* Code generation for choice nodes.
3795 * We generate quick checks that do a mask and compare to eliminate a
3796 * choice. If the quick check succeeds then it jumps to the continuation to
3797 * do slow checks and check subsequent nodes. If it fails (the common case)
3798 * it falls through to the next choice.
3800 * Here is the desired flow graph. Nodes directly below each other imply
3801 * fallthrough. Alternatives 1 and 2 have quick checks. Alternative
3802 * 3 doesn't have a quick check so we have to call the slow check.
3803 * Nodes are marked Qn for quick checks and Sn for slow checks. The entire
3804 * regexp continuation is generated directly after the Sn node, up to the
3805 * next GoTo if we decide to reuse some already generated code. Some
3806 * nodes expect preload_characters to be preloaded into the current
3807 * character register. R nodes do this preloading. Vertices are marked
3808 * F for failures and S for success (possible success in the case of quick
3809 * nodes). L, V, < and > are used as arrow heads.
3843 * For greedy loops we push the current position, then generate the code that
3844 * eats the input specially in EmitGreedyLoop. The other choice (the
3845 * continuation) is generated by the normal code in EmitChoices, and steps back
3846 * in the input to the starting position when it fails to match. The loop code
3847 * looks like this (U is the unwind code that steps back in the greedy loop).
3860 * Q2 ---> U----->backtrack
3867 GreedyLoopState::GreedyLoopState(bool not_at_start) {
3868 counter_backtrack_trace_.set_backtrack(&label_);
3869 if (not_at_start) counter_backtrack_trace_.set_at_start(false);
3873 void ChoiceNode::AssertGuardsMentionRegisters(Trace* trace) {
3875 int choice_count = alternatives_->length();
3876 for (int i = 0; i < choice_count - 1; i++) {
3877 GuardedAlternative alternative = alternatives_->at(i);
3878 ZoneList<Guard*>* guards = alternative.guards();
3879 int guard_count = (guards == NULL) ? 0 : guards->length();
3880 for (int j = 0; j < guard_count; j++) {
3881 DCHECK(!trace->mentions_reg(guards->at(j)->reg()));
3888 void ChoiceNode::SetUpPreLoad(RegExpCompiler* compiler,
3889 Trace* current_trace,
3890 PreloadState* state) {
3891 if (state->eats_at_least_ == PreloadState::kEatsAtLeastNotYetInitialized) {
3892 // Save some time by looking at most one machine word ahead.
3893 state->eats_at_least_ =
3894 EatsAtLeast(compiler->one_byte() ? 4 : 2, kRecursionBudget,
3895 current_trace->at_start() == Trace::FALSE_VALUE);
3897 state->preload_characters_ =
3898 CalculatePreloadCharacters(compiler, state->eats_at_least_);
3900 state->preload_is_current_ =
3901 (current_trace->characters_preloaded() == state->preload_characters_);
3902 state->preload_has_checked_bounds_ = state->preload_is_current_;
3906 void ChoiceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
3907 int choice_count = alternatives_->length();
3909 AssertGuardsMentionRegisters(trace);
3911 LimitResult limit_result = LimitVersions(compiler, trace);
3912 if (limit_result == DONE) return;
3913 DCHECK(limit_result == CONTINUE);
3915 // For loop nodes we already flushed (see LoopChoiceNode::Emit), but for
3916 // other choice nodes we only flush if we are out of code size budget.
3917 if (trace->flush_budget() == 0 && trace->actions() != NULL) {
3918 trace->Flush(compiler, this);
3922 RecursionCheck rc(compiler);
3924 PreloadState preload;
3926 GreedyLoopState greedy_loop_state(not_at_start());
3928 int text_length = GreedyLoopTextLengthForAlternative(&alternatives_->at(0));
3929 AlternativeGenerationList alt_gens(choice_count, zone());
3931 if (choice_count > 1 && text_length != kNodeIsTooComplexForGreedyLoops) {
3932 trace = EmitGreedyLoop(compiler,
3939 // TODO(erikcorry): Delete this. We don't need this label, but it makes us
3940 // match the traces produced pre-cleanup.
3941 Label second_choice;
3942 compiler->macro_assembler()->Bind(&second_choice);
3944 preload.eats_at_least_ = EmitOptimizedUnanchoredSearch(compiler, trace);
3946 EmitChoices(compiler,
3953 // At this point we need to generate slow checks for the alternatives where
3954 // the quick check was inlined. We can recognize these because the associated
3956 int new_flush_budget = trace->flush_budget() / choice_count;
3957 for (int i = 0; i < choice_count; i++) {
3958 AlternativeGeneration* alt_gen = alt_gens.at(i);
3959 Trace new_trace(*trace);
3960 // If there are actions to be flushed we have to limit how many times
3961 // they are flushed. Take the budget of the parent trace and distribute
3962 // it fairly amongst the children.
3963 if (new_trace.actions() != NULL) {
3964 new_trace.set_flush_budget(new_flush_budget);
3966 bool next_expects_preload =
3967 i == choice_count - 1 ? false : alt_gens.at(i + 1)->expects_preload;
3968 EmitOutOfLineContinuation(compiler,
3970 alternatives_->at(i),
3972 preload.preload_characters_,
3973 next_expects_preload);
3978 Trace* ChoiceNode::EmitGreedyLoop(RegExpCompiler* compiler,
3980 AlternativeGenerationList* alt_gens,
3981 PreloadState* preload,
3982 GreedyLoopState* greedy_loop_state,
3984 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
3985 // Here we have special handling for greedy loops containing only text nodes
3986 // and other simple nodes. These are handled by pushing the current
3987 // position on the stack and then incrementing the current position each
3988 // time around the switch. On backtrack we decrement the current position
3989 // and check it against the pushed value. This avoids pushing backtrack
3990 // information for each iteration of the loop, which could take up a lot of
3992 DCHECK(trace->stop_node() == NULL);
3993 macro_assembler->PushCurrentPosition();
3994 Label greedy_match_failed;
3995 Trace greedy_match_trace;
3996 if (not_at_start()) greedy_match_trace.set_at_start(false);
3997 greedy_match_trace.set_backtrack(&greedy_match_failed);
3999 macro_assembler->Bind(&loop_label);
4000 greedy_match_trace.set_stop_node(this);
4001 greedy_match_trace.set_loop_label(&loop_label);
4002 alternatives_->at(0).node()->Emit(compiler, &greedy_match_trace);
4003 macro_assembler->Bind(&greedy_match_failed);
4005 Label second_choice; // For use in greedy matches.
4006 macro_assembler->Bind(&second_choice);
4008 Trace* new_trace = greedy_loop_state->counter_backtrack_trace();
4010 EmitChoices(compiler,
4016 macro_assembler->Bind(greedy_loop_state->label());
4017 // If we have unwound to the bottom then backtrack.
4018 macro_assembler->CheckGreedyLoop(trace->backtrack());
4019 // Otherwise try the second priority at an earlier position.
4020 macro_assembler->AdvanceCurrentPosition(-text_length);
4021 macro_assembler->GoTo(&second_choice);
4025 int ChoiceNode::EmitOptimizedUnanchoredSearch(RegExpCompiler* compiler,
4027 int eats_at_least = PreloadState::kEatsAtLeastNotYetInitialized;
4028 if (alternatives_->length() != 2) return eats_at_least;
4030 GuardedAlternative alt1 = alternatives_->at(1);
4031 if (alt1.guards() != NULL && alt1.guards()->length() != 0) {
4032 return eats_at_least;
4034 RegExpNode* eats_anything_node = alt1.node();
4035 if (eats_anything_node->GetSuccessorOfOmnivorousTextNode(compiler) != this) {
4036 return eats_at_least;
4039 // Really we should be creating a new trace when we execute this function,
4040 // but there is no need, because the code it generates cannot backtrack, and
4041 // we always arrive here with a trivial trace (since it's the entry to a
4042 // loop. That also implies that there are no preloaded characters, which is
4043 // good, because it means we won't be violating any assumptions by
4044 // overwriting those characters with new load instructions.
4045 DCHECK(trace->is_trivial());
4047 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
4048 // At this point we know that we are at a non-greedy loop that will eat
4049 // any character one at a time. Any non-anchored regexp has such a
4050 // loop prepended to it in order to find where it starts. We look for
4051 // a pattern of the form ...abc... where we can look 6 characters ahead
4052 // and step forwards 3 if the character is not one of abc. Abc need
4053 // not be atoms, they can be any reasonably limited character class or
4054 // small alternation.
4055 BoyerMooreLookahead* bm = bm_info(false);
4057 eats_at_least = Min(kMaxLookaheadForBoyerMoore,
4058 EatsAtLeast(kMaxLookaheadForBoyerMoore,
4061 if (eats_at_least >= 1) {
4062 bm = new(zone()) BoyerMooreLookahead(eats_at_least,
4065 GuardedAlternative alt0 = alternatives_->at(0);
4066 alt0.node()->FillInBMInfo(0, kRecursionBudget, bm, false);
4070 bm->EmitSkipInstructions(macro_assembler);
4072 return eats_at_least;
4076 void ChoiceNode::EmitChoices(RegExpCompiler* compiler,
4077 AlternativeGenerationList* alt_gens,
4080 PreloadState* preload) {
4081 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
4082 SetUpPreLoad(compiler, trace, preload);
4084 // For now we just call all choices one after the other. The idea ultimately
4085 // is to use the Dispatch table to try only the relevant ones.
4086 int choice_count = alternatives_->length();
4088 int new_flush_budget = trace->flush_budget() / choice_count;
4090 for (int i = first_choice; i < choice_count; i++) {
4091 bool is_last = i == choice_count - 1;
4092 bool fall_through_on_failure = !is_last;
4093 GuardedAlternative alternative = alternatives_->at(i);
4094 AlternativeGeneration* alt_gen = alt_gens->at(i);
4095 alt_gen->quick_check_details.set_characters(preload->preload_characters_);
4096 ZoneList<Guard*>* guards = alternative.guards();
4097 int guard_count = (guards == NULL) ? 0 : guards->length();
4098 Trace new_trace(*trace);
4099 new_trace.set_characters_preloaded(preload->preload_is_current_ ?
4100 preload->preload_characters_ :
4102 if (preload->preload_has_checked_bounds_) {
4103 new_trace.set_bound_checked_up_to(preload->preload_characters_);
4105 new_trace.quick_check_performed()->Clear();
4106 if (not_at_start_) new_trace.set_at_start(Trace::FALSE_VALUE);
4108 new_trace.set_backtrack(&alt_gen->after);
4110 alt_gen->expects_preload = preload->preload_is_current_;
4111 bool generate_full_check_inline = false;
4112 if (compiler->optimize() &&
4113 try_to_emit_quick_check_for_alternative(i == 0) &&
4114 alternative.node()->EmitQuickCheck(
4115 compiler, trace, &new_trace, preload->preload_has_checked_bounds_,
4116 &alt_gen->possible_success, &alt_gen->quick_check_details,
4117 fall_through_on_failure)) {
4118 // Quick check was generated for this choice.
4119 preload->preload_is_current_ = true;
4120 preload->preload_has_checked_bounds_ = true;
4121 // If we generated the quick check to fall through on possible success,
4122 // we now need to generate the full check inline.
4123 if (!fall_through_on_failure) {
4124 macro_assembler->Bind(&alt_gen->possible_success);
4125 new_trace.set_quick_check_performed(&alt_gen->quick_check_details);
4126 new_trace.set_characters_preloaded(preload->preload_characters_);
4127 new_trace.set_bound_checked_up_to(preload->preload_characters_);
4128 generate_full_check_inline = true;
4130 } else if (alt_gen->quick_check_details.cannot_match()) {
4131 if (!fall_through_on_failure) {
4132 macro_assembler->GoTo(trace->backtrack());
4136 // No quick check was generated. Put the full code here.
4137 // If this is not the first choice then there could be slow checks from
4138 // previous cases that go here when they fail. There's no reason to
4139 // insist that they preload characters since the slow check we are about
4140 // to generate probably can't use it.
4141 if (i != first_choice) {
4142 alt_gen->expects_preload = false;
4143 new_trace.InvalidateCurrentCharacter();
4145 generate_full_check_inline = true;
4147 if (generate_full_check_inline) {
4148 if (new_trace.actions() != NULL) {
4149 new_trace.set_flush_budget(new_flush_budget);
4151 for (int j = 0; j < guard_count; j++) {
4152 GenerateGuard(macro_assembler, guards->at(j), &new_trace);
4154 alternative.node()->Emit(compiler, &new_trace);
4155 preload->preload_is_current_ = false;
4157 macro_assembler->Bind(&alt_gen->after);
4162 void ChoiceNode::EmitOutOfLineContinuation(RegExpCompiler* compiler,
4164 GuardedAlternative alternative,
4165 AlternativeGeneration* alt_gen,
4166 int preload_characters,
4167 bool next_expects_preload) {
4168 if (!alt_gen->possible_success.is_linked()) return;
4170 RegExpMacroAssembler* macro_assembler = compiler->macro_assembler();
4171 macro_assembler->Bind(&alt_gen->possible_success);
4172 Trace out_of_line_trace(*trace);
4173 out_of_line_trace.set_characters_preloaded(preload_characters);
4174 out_of_line_trace.set_quick_check_performed(&alt_gen->quick_check_details);
4175 if (not_at_start_) out_of_line_trace.set_at_start(Trace::FALSE_VALUE);
4176 ZoneList<Guard*>* guards = alternative.guards();
4177 int guard_count = (guards == NULL) ? 0 : guards->length();
4178 if (next_expects_preload) {
4179 Label reload_current_char;
4180 out_of_line_trace.set_backtrack(&reload_current_char);
4181 for (int j = 0; j < guard_count; j++) {
4182 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
4184 alternative.node()->Emit(compiler, &out_of_line_trace);
4185 macro_assembler->Bind(&reload_current_char);
4186 // Reload the current character, since the next quick check expects that.
4187 // We don't need to check bounds here because we only get into this
4188 // code through a quick check which already did the checked load.
4189 macro_assembler->LoadCurrentCharacter(trace->cp_offset(),
4192 preload_characters);
4193 macro_assembler->GoTo(&(alt_gen->after));
4195 out_of_line_trace.set_backtrack(&(alt_gen->after));
4196 for (int j = 0; j < guard_count; j++) {
4197 GenerateGuard(macro_assembler, guards->at(j), &out_of_line_trace);
4199 alternative.node()->Emit(compiler, &out_of_line_trace);
4204 void ActionNode::Emit(RegExpCompiler* compiler, Trace* trace) {
4205 RegExpMacroAssembler* assembler = compiler->macro_assembler();
4206 LimitResult limit_result = LimitVersions(compiler, trace);
4207 if (limit_result == DONE) return;
4208 DCHECK(limit_result == CONTINUE);
4210 RecursionCheck rc(compiler);
4212 switch (action_type_) {
4213 case STORE_POSITION: {
4214 Trace::DeferredCapture
4215 new_capture(data_.u_position_register.reg,
4216 data_.u_position_register.is_capture,
4218 Trace new_trace = *trace;
4219 new_trace.add_action(&new_capture);
4220 on_success()->Emit(compiler, &new_trace);
4223 case INCREMENT_REGISTER: {
4224 Trace::DeferredIncrementRegister
4225 new_increment(data_.u_increment_register.reg);
4226 Trace new_trace = *trace;
4227 new_trace.add_action(&new_increment);
4228 on_success()->Emit(compiler, &new_trace);
4231 case SET_REGISTER: {
4232 Trace::DeferredSetRegister
4233 new_set(data_.u_store_register.reg, data_.u_store_register.value);
4234 Trace new_trace = *trace;
4235 new_trace.add_action(&new_set);
4236 on_success()->Emit(compiler, &new_trace);
4239 case CLEAR_CAPTURES: {
4240 Trace::DeferredClearCaptures
4241 new_capture(Interval(data_.u_clear_captures.range_from,
4242 data_.u_clear_captures.range_to));
4243 Trace new_trace = *trace;
4244 new_trace.add_action(&new_capture);
4245 on_success()->Emit(compiler, &new_trace);
4248 case BEGIN_SUBMATCH:
4249 if (!trace->is_trivial()) {
4250 trace->Flush(compiler, this);
4252 assembler->WriteCurrentPositionToRegister(
4253 data_.u_submatch.current_position_register, 0);
4254 assembler->WriteStackPointerToRegister(
4255 data_.u_submatch.stack_pointer_register);
4256 on_success()->Emit(compiler, trace);
4259 case EMPTY_MATCH_CHECK: {
4260 int start_pos_reg = data_.u_empty_match_check.start_register;
4262 int rep_reg = data_.u_empty_match_check.repetition_register;
4263 bool has_minimum = (rep_reg != RegExpCompiler::kNoRegister);
4264 bool know_dist = trace->GetStoredPosition(start_pos_reg, &stored_pos);
4265 if (know_dist && !has_minimum && stored_pos == trace->cp_offset()) {
4266 // If we know we haven't advanced and there is no minimum we
4267 // can just backtrack immediately.
4268 assembler->GoTo(trace->backtrack());
4269 } else if (know_dist && stored_pos < trace->cp_offset()) {
4270 // If we know we've advanced we can generate the continuation
4272 on_success()->Emit(compiler, trace);
4273 } else if (!trace->is_trivial()) {
4274 trace->Flush(compiler, this);
4276 Label skip_empty_check;
4277 // If we have a minimum number of repetitions we check the current
4278 // number first and skip the empty check if it's not enough.
4280 int limit = data_.u_empty_match_check.repetition_limit;
4281 assembler->IfRegisterLT(rep_reg, limit, &skip_empty_check);
4283 // If the match is empty we bail out, otherwise we fall through
4284 // to the on-success continuation.
4285 assembler->IfRegisterEqPos(data_.u_empty_match_check.start_register,
4286 trace->backtrack());
4287 assembler->Bind(&skip_empty_check);
4288 on_success()->Emit(compiler, trace);
4292 case POSITIVE_SUBMATCH_SUCCESS: {
4293 if (!trace->is_trivial()) {
4294 trace->Flush(compiler, this);
4297 assembler->ReadCurrentPositionFromRegister(
4298 data_.u_submatch.current_position_register);
4299 assembler->ReadStackPointerFromRegister(
4300 data_.u_submatch.stack_pointer_register);
4301 int clear_register_count = data_.u_submatch.clear_register_count;
4302 if (clear_register_count == 0) {
4303 on_success()->Emit(compiler, trace);
4306 int clear_registers_from = data_.u_submatch.clear_register_from;
4307 Label clear_registers_backtrack;
4308 Trace new_trace = *trace;
4309 new_trace.set_backtrack(&clear_registers_backtrack);
4310 on_success()->Emit(compiler, &new_trace);
4312 assembler->Bind(&clear_registers_backtrack);
4313 int clear_registers_to = clear_registers_from + clear_register_count - 1;
4314 assembler->ClearRegisters(clear_registers_from, clear_registers_to);
4316 DCHECK(trace->backtrack() == NULL);
4317 assembler->Backtrack();
4326 void BackReferenceNode::Emit(RegExpCompiler* compiler, Trace* trace) {
4327 RegExpMacroAssembler* assembler = compiler->macro_assembler();
4328 if (!trace->is_trivial()) {
4329 trace->Flush(compiler, this);
4333 LimitResult limit_result = LimitVersions(compiler, trace);
4334 if (limit_result == DONE) return;
4335 DCHECK(limit_result == CONTINUE);
4337 RecursionCheck rc(compiler);
4339 DCHECK_EQ(start_reg_ + 1, end_reg_);
4340 if (compiler->ignore_case()) {
4341 assembler->CheckNotBackReferenceIgnoreCase(start_reg_,
4342 trace->backtrack());
4344 assembler->CheckNotBackReference(start_reg_, trace->backtrack());
4346 on_success()->Emit(compiler, trace);
4350 // -------------------------------------------------------------------
4357 class DotPrinter: public NodeVisitor {
4359 DotPrinter(std::ostream& os, bool ignore_case) // NOLINT
4361 ignore_case_(ignore_case) {}
4362 void PrintNode(const char* label, RegExpNode* node);
4363 void Visit(RegExpNode* node);
4364 void PrintAttributes(RegExpNode* from);
4365 void PrintOnFailure(RegExpNode* from, RegExpNode* to);
4366 #define DECLARE_VISIT(Type) \
4367 virtual void Visit##Type(Type##Node* that);
4368 FOR_EACH_NODE_TYPE(DECLARE_VISIT)
4369 #undef DECLARE_VISIT
4376 void DotPrinter::PrintNode(const char* label, RegExpNode* node) {
4377 os_ << "digraph G {\n graph [label=\"";
4378 for (int i = 0; label[i]; i++) {
4393 os_ << "}" << std::endl;
4397 void DotPrinter::Visit(RegExpNode* node) {
4398 if (node->info()->visited) return;
4399 node->info()->visited = true;
4404 void DotPrinter::PrintOnFailure(RegExpNode* from, RegExpNode* on_failure) {
4405 os_ << " n" << from << " -> n" << on_failure << " [style=dotted];\n";
4410 class TableEntryBodyPrinter {
4412 TableEntryBodyPrinter(std::ostream& os, ChoiceNode* choice) // NOLINT
4415 void Call(uc16 from, DispatchTable::Entry entry) {
4416 OutSet* out_set = entry.out_set();
4417 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
4418 if (out_set->Get(i)) {
4419 os_ << " n" << choice() << ":s" << from << "o" << i << " -> n"
4420 << choice()->alternatives()->at(i).node() << ";\n";
4425 ChoiceNode* choice() { return choice_; }
4427 ChoiceNode* choice_;
4431 class TableEntryHeaderPrinter {
4433 explicit TableEntryHeaderPrinter(std::ostream& os) // NOLINT
4436 void Call(uc16 from, DispatchTable::Entry entry) {
4442 os_ << "{\\" << AsUC16(from) << "-\\" << AsUC16(entry.to()) << "|{";
4443 OutSet* out_set = entry.out_set();
4445 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
4446 if (out_set->Get(i)) {
4447 if (priority > 0) os_ << "|";
4448 os_ << "<s" << from << "o" << i << "> " << priority;
4461 class AttributePrinter {
4463 explicit AttributePrinter(std::ostream& os) // NOLINT
4466 void PrintSeparator() {
4473 void PrintBit(const char* name, bool value) {
4476 os_ << "{" << name << "}";
4478 void PrintPositive(const char* name, int value) {
4479 if (value < 0) return;
4481 os_ << "{" << name << "|" << value << "}";
4490 void DotPrinter::PrintAttributes(RegExpNode* that) {
4491 os_ << " a" << that << " [shape=Mrecord, color=grey, fontcolor=grey, "
4492 << "margin=0.1, fontsize=10, label=\"{";
4493 AttributePrinter printer(os_);
4494 NodeInfo* info = that->info();
4495 printer.PrintBit("NI", info->follows_newline_interest);
4496 printer.PrintBit("WI", info->follows_word_interest);
4497 printer.PrintBit("SI", info->follows_start_interest);
4498 Label* label = that->label();
4499 if (label->is_bound())
4500 printer.PrintPositive("@", label->pos());
4502 << " a" << that << " -> n" << that
4503 << " [style=dashed, color=grey, arrowhead=none];\n";
4507 static const bool kPrintDispatchTable = false;
4508 void DotPrinter::VisitChoice(ChoiceNode* that) {
4509 if (kPrintDispatchTable) {
4510 os_ << " n" << that << " [shape=Mrecord, label=\"";
4511 TableEntryHeaderPrinter header_printer(os_);
4512 that->GetTable(ignore_case_)->ForEach(&header_printer);
4514 PrintAttributes(that);
4515 TableEntryBodyPrinter body_printer(os_, that);
4516 that->GetTable(ignore_case_)->ForEach(&body_printer);
4518 os_ << " n" << that << " [shape=Mrecord, label=\"?\"];\n";
4519 for (int i = 0; i < that->alternatives()->length(); i++) {
4520 GuardedAlternative alt = that->alternatives()->at(i);
4521 os_ << " n" << that << " -> n" << alt.node();
4524 for (int i = 0; i < that->alternatives()->length(); i++) {
4525 GuardedAlternative alt = that->alternatives()->at(i);
4526 alt.node()->Accept(this);
4531 void DotPrinter::VisitText(TextNode* that) {
4532 Zone* zone = that->zone();
4533 os_ << " n" << that << " [label=\"";
4534 for (int i = 0; i < that->elements()->length(); i++) {
4535 if (i > 0) os_ << " ";
4536 TextElement elm = that->elements()->at(i);
4537 switch (elm.text_type()) {
4538 case TextElement::ATOM: {
4539 Vector<const uc16> data = elm.atom()->data();
4540 for (int i = 0; i < data.length(); i++) {
4541 os_ << static_cast<char>(data[i]);
4545 case TextElement::CHAR_CLASS: {
4546 RegExpCharacterClass* node = elm.char_class();
4548 if (node->is_negated()) os_ << "^";
4549 for (int j = 0; j < node->ranges(zone)->length(); j++) {
4550 CharacterRange range = node->ranges(zone)->at(j);
4551 os_ << AsUC16(range.from()) << "-" << AsUC16(range.to());
4560 os_ << "\", shape=box, peripheries=2];\n";
4561 PrintAttributes(that);
4562 os_ << " n" << that << " -> n" << that->on_success() << ";\n";
4563 Visit(that->on_success());
4567 void DotPrinter::VisitBackReference(BackReferenceNode* that) {
4568 os_ << " n" << that << " [label=\"$" << that->start_register() << "..$"
4569 << that->end_register() << "\", shape=doubleoctagon];\n";
4570 PrintAttributes(that);
4571 os_ << " n" << that << " -> n" << that->on_success() << ";\n";
4572 Visit(that->on_success());
4576 void DotPrinter::VisitEnd(EndNode* that) {
4577 os_ << " n" << that << " [style=bold, shape=point];\n";
4578 PrintAttributes(that);
4582 void DotPrinter::VisitAssertion(AssertionNode* that) {
4583 os_ << " n" << that << " [";
4584 switch (that->assertion_type()) {
4585 case AssertionNode::AT_END:
4586 os_ << "label=\"$\", shape=septagon";
4588 case AssertionNode::AT_START:
4589 os_ << "label=\"^\", shape=septagon";
4591 case AssertionNode::AT_BOUNDARY:
4592 os_ << "label=\"\\b\", shape=septagon";
4594 case AssertionNode::AT_NON_BOUNDARY:
4595 os_ << "label=\"\\B\", shape=septagon";
4597 case AssertionNode::AFTER_NEWLINE:
4598 os_ << "label=\"(?<=\\n)\", shape=septagon";
4602 PrintAttributes(that);
4603 RegExpNode* successor = that->on_success();
4604 os_ << " n" << that << " -> n" << successor << ";\n";
4609 void DotPrinter::VisitAction(ActionNode* that) {
4610 os_ << " n" << that << " [";
4611 switch (that->action_type_) {
4612 case ActionNode::SET_REGISTER:
4613 os_ << "label=\"$" << that->data_.u_store_register.reg
4614 << ":=" << that->data_.u_store_register.value << "\", shape=octagon";
4616 case ActionNode::INCREMENT_REGISTER:
4617 os_ << "label=\"$" << that->data_.u_increment_register.reg
4618 << "++\", shape=octagon";
4620 case ActionNode::STORE_POSITION:
4621 os_ << "label=\"$" << that->data_.u_position_register.reg
4622 << ":=$pos\", shape=octagon";
4624 case ActionNode::BEGIN_SUBMATCH:
4625 os_ << "label=\"$" << that->data_.u_submatch.current_position_register
4626 << ":=$pos,begin\", shape=septagon";
4628 case ActionNode::POSITIVE_SUBMATCH_SUCCESS:
4629 os_ << "label=\"escape\", shape=septagon";
4631 case ActionNode::EMPTY_MATCH_CHECK:
4632 os_ << "label=\"$" << that->data_.u_empty_match_check.start_register
4633 << "=$pos?,$" << that->data_.u_empty_match_check.repetition_register
4634 << "<" << that->data_.u_empty_match_check.repetition_limit
4635 << "?\", shape=septagon";
4637 case ActionNode::CLEAR_CAPTURES: {
4638 os_ << "label=\"clear $" << that->data_.u_clear_captures.range_from
4639 << " to $" << that->data_.u_clear_captures.range_to
4640 << "\", shape=septagon";
4645 PrintAttributes(that);
4646 RegExpNode* successor = that->on_success();
4647 os_ << " n" << that << " -> n" << successor << ";\n";
4652 class DispatchTableDumper {
4654 explicit DispatchTableDumper(std::ostream& os) : os_(os) {}
4655 void Call(uc16 key, DispatchTable::Entry entry);
4661 void DispatchTableDumper::Call(uc16 key, DispatchTable::Entry entry) {
4662 os_ << "[" << AsUC16(key) << "-" << AsUC16(entry.to()) << "]: {";
4663 OutSet* set = entry.out_set();
4665 for (unsigned i = 0; i < OutSet::kFirstLimit; i++) {
4679 void DispatchTable::Dump() {
4680 OFStream os(stderr);
4681 DispatchTableDumper dumper(os);
4682 tree()->ForEach(&dumper);
4686 void RegExpEngine::DotPrint(const char* label,
4689 OFStream os(stdout);
4690 DotPrinter printer(os, ignore_case);
4691 printer.PrintNode(label, node);
4698 // -------------------------------------------------------------------
4699 // Tree to graph conversion
4701 RegExpNode* RegExpAtom::ToNode(RegExpCompiler* compiler,
4702 RegExpNode* on_success) {
4703 ZoneList<TextElement>* elms =
4704 new(compiler->zone()) ZoneList<TextElement>(1, compiler->zone());
4705 elms->Add(TextElement::Atom(this), compiler->zone());
4706 return new(compiler->zone()) TextNode(elms, on_success);
4710 RegExpNode* RegExpText::ToNode(RegExpCompiler* compiler,
4711 RegExpNode* on_success) {
4712 return new(compiler->zone()) TextNode(elements(), on_success);
4716 static bool CompareInverseRanges(ZoneList<CharacterRange>* ranges,
4717 const int* special_class,
4719 length--; // Remove final 0x10000.
4720 DCHECK(special_class[length] == 0x10000);
4721 DCHECK(ranges->length() != 0);
4722 DCHECK(length != 0);
4723 DCHECK(special_class[0] != 0);
4724 if (ranges->length() != (length >> 1) + 1) {
4727 CharacterRange range = ranges->at(0);
4728 if (range.from() != 0) {
4731 for (int i = 0; i < length; i += 2) {
4732 if (special_class[i] != (range.to() + 1)) {
4735 range = ranges->at((i >> 1) + 1);
4736 if (special_class[i+1] != range.from()) {
4740 if (range.to() != 0xffff) {
4747 static bool CompareRanges(ZoneList<CharacterRange>* ranges,
4748 const int* special_class,
4750 length--; // Remove final 0x10000.
4751 DCHECK(special_class[length] == 0x10000);
4752 if (ranges->length() * 2 != length) {
4755 for (int i = 0; i < length; i += 2) {
4756 CharacterRange range = ranges->at(i >> 1);
4757 if (range.from() != special_class[i] ||
4758 range.to() != special_class[i + 1] - 1) {
4766 bool RegExpCharacterClass::is_standard(Zone* zone) {
4767 // TODO(lrn): Remove need for this function, by not throwing away information
4772 if (set_.is_standard()) {
4775 if (CompareRanges(set_.ranges(zone), kSpaceRanges, kSpaceRangeCount)) {
4776 set_.set_standard_set_type('s');
4779 if (CompareInverseRanges(set_.ranges(zone), kSpaceRanges, kSpaceRangeCount)) {
4780 set_.set_standard_set_type('S');
4783 if (CompareInverseRanges(set_.ranges(zone),
4784 kLineTerminatorRanges,
4785 kLineTerminatorRangeCount)) {
4786 set_.set_standard_set_type('.');
4789 if (CompareRanges(set_.ranges(zone),
4790 kLineTerminatorRanges,
4791 kLineTerminatorRangeCount)) {
4792 set_.set_standard_set_type('n');
4795 if (CompareRanges(set_.ranges(zone), kWordRanges, kWordRangeCount)) {
4796 set_.set_standard_set_type('w');
4799 if (CompareInverseRanges(set_.ranges(zone), kWordRanges, kWordRangeCount)) {
4800 set_.set_standard_set_type('W');
4807 RegExpNode* RegExpCharacterClass::ToNode(RegExpCompiler* compiler,
4808 RegExpNode* on_success) {
4809 return new(compiler->zone()) TextNode(this, on_success);
4813 RegExpNode* RegExpDisjunction::ToNode(RegExpCompiler* compiler,
4814 RegExpNode* on_success) {
4815 ZoneList<RegExpTree*>* alternatives = this->alternatives();
4816 int length = alternatives->length();
4817 ChoiceNode* result =
4818 new(compiler->zone()) ChoiceNode(length, compiler->zone());
4819 for (int i = 0; i < length; i++) {
4820 GuardedAlternative alternative(alternatives->at(i)->ToNode(compiler,
4822 result->AddAlternative(alternative);
4828 RegExpNode* RegExpQuantifier::ToNode(RegExpCompiler* compiler,
4829 RegExpNode* on_success) {
4830 return ToNode(min(),
4839 // Scoped object to keep track of how much we unroll quantifier loops in the
4840 // regexp graph generator.
4841 class RegExpExpansionLimiter {
4843 static const int kMaxExpansionFactor = 6;
4844 RegExpExpansionLimiter(RegExpCompiler* compiler, int factor)
4845 : compiler_(compiler),
4846 saved_expansion_factor_(compiler->current_expansion_factor()),
4847 ok_to_expand_(saved_expansion_factor_ <= kMaxExpansionFactor) {
4849 if (ok_to_expand_) {
4850 if (factor > kMaxExpansionFactor) {
4851 // Avoid integer overflow of the current expansion factor.
4852 ok_to_expand_ = false;
4853 compiler->set_current_expansion_factor(kMaxExpansionFactor + 1);
4855 int new_factor = saved_expansion_factor_ * factor;
4856 ok_to_expand_ = (new_factor <= kMaxExpansionFactor);
4857 compiler->set_current_expansion_factor(new_factor);
4862 ~RegExpExpansionLimiter() {
4863 compiler_->set_current_expansion_factor(saved_expansion_factor_);
4866 bool ok_to_expand() { return ok_to_expand_; }
4869 RegExpCompiler* compiler_;
4870 int saved_expansion_factor_;
4873 DISALLOW_IMPLICIT_CONSTRUCTORS(RegExpExpansionLimiter);
4877 RegExpNode* RegExpQuantifier::ToNode(int min,
4881 RegExpCompiler* compiler,
4882 RegExpNode* on_success,
4883 bool not_at_start) {
4884 // x{f, t} becomes this:
4890 // (r=0)-->(?)---/ [if r < t]
4892 // [if r >= f] \----> ...
4895 // 15.10.2.5 RepeatMatcher algorithm.
4896 // The parser has already eliminated the case where max is 0. In the case
4897 // where max_match is zero the parser has removed the quantifier if min was
4898 // > 0 and removed the atom if min was 0. See AddQuantifierToAtom.
4900 // If we know that we cannot match zero length then things are a little
4901 // simpler since we don't need to make the special zero length match check
4902 // from step 2.1. If the min and max are small we can unroll a little in
4904 static const int kMaxUnrolledMinMatches = 3; // Unroll (foo)+ and (foo){3,}
4905 static const int kMaxUnrolledMaxMatches = 3; // Unroll (foo)? and (foo){x,3}
4906 if (max == 0) return on_success; // This can happen due to recursion.
4907 bool body_can_be_empty = (body->min_match() == 0);
4908 int body_start_reg = RegExpCompiler::kNoRegister;
4909 Interval capture_registers = body->CaptureRegisters();
4910 bool needs_capture_clearing = !capture_registers.is_empty();
4911 Zone* zone = compiler->zone();
4913 if (body_can_be_empty) {
4914 body_start_reg = compiler->AllocateRegister();
4915 } else if (compiler->optimize() && !needs_capture_clearing) {
4916 // Only unroll if there are no captures and the body can't be
4919 RegExpExpansionLimiter limiter(
4920 compiler, min + ((max != min) ? 1 : 0));
4921 if (min > 0 && min <= kMaxUnrolledMinMatches && limiter.ok_to_expand()) {
4922 int new_max = (max == kInfinity) ? max : max - min;
4923 // Recurse once to get the loop or optional matches after the fixed
4925 RegExpNode* answer = ToNode(
4926 0, new_max, is_greedy, body, compiler, on_success, true);
4927 // Unroll the forced matches from 0 to min. This can cause chains of
4928 // TextNodes (which the parser does not generate). These should be
4929 // combined if it turns out they hinder good code generation.
4930 for (int i = 0; i < min; i++) {
4931 answer = body->ToNode(compiler, answer);
4936 if (max <= kMaxUnrolledMaxMatches && min == 0) {
4937 DCHECK(max > 0); // Due to the 'if' above.
4938 RegExpExpansionLimiter limiter(compiler, max);
4939 if (limiter.ok_to_expand()) {
4940 // Unroll the optional matches up to max.
4941 RegExpNode* answer = on_success;
4942 for (int i = 0; i < max; i++) {
4943 ChoiceNode* alternation = new(zone) ChoiceNode(2, zone);
4945 alternation->AddAlternative(
4946 GuardedAlternative(body->ToNode(compiler, answer)));
4947 alternation->AddAlternative(GuardedAlternative(on_success));
4949 alternation->AddAlternative(GuardedAlternative(on_success));
4950 alternation->AddAlternative(
4951 GuardedAlternative(body->ToNode(compiler, answer)));
4953 answer = alternation;
4954 if (not_at_start) alternation->set_not_at_start();
4960 bool has_min = min > 0;
4961 bool has_max = max < RegExpTree::kInfinity;
4962 bool needs_counter = has_min || has_max;
4963 int reg_ctr = needs_counter
4964 ? compiler->AllocateRegister()
4965 : RegExpCompiler::kNoRegister;
4966 LoopChoiceNode* center = new(zone) LoopChoiceNode(body->min_match() == 0,
4968 if (not_at_start) center->set_not_at_start();
4969 RegExpNode* loop_return = needs_counter
4970 ? static_cast<RegExpNode*>(ActionNode::IncrementRegister(reg_ctr, center))
4971 : static_cast<RegExpNode*>(center);
4972 if (body_can_be_empty) {
4973 // If the body can be empty we need to check if it was and then
4975 loop_return = ActionNode::EmptyMatchCheck(body_start_reg,
4980 RegExpNode* body_node = body->ToNode(compiler, loop_return);
4981 if (body_can_be_empty) {
4982 // If the body can be empty we need to store the start position
4983 // so we can bail out if it was empty.
4984 body_node = ActionNode::StorePosition(body_start_reg, false, body_node);
4986 if (needs_capture_clearing) {
4987 // Before entering the body of this loop we need to clear captures.
4988 body_node = ActionNode::ClearCaptures(capture_registers, body_node);
4990 GuardedAlternative body_alt(body_node);
4993 new(zone) Guard(reg_ctr, Guard::LT, max);
4994 body_alt.AddGuard(body_guard, zone);
4996 GuardedAlternative rest_alt(on_success);
4998 Guard* rest_guard = new(compiler->zone()) Guard(reg_ctr, Guard::GEQ, min);
4999 rest_alt.AddGuard(rest_guard, zone);
5002 center->AddLoopAlternative(body_alt);
5003 center->AddContinueAlternative(rest_alt);
5005 center->AddContinueAlternative(rest_alt);
5006 center->AddLoopAlternative(body_alt);
5008 if (needs_counter) {
5009 return ActionNode::SetRegister(reg_ctr, 0, center);
5016 RegExpNode* RegExpAssertion::ToNode(RegExpCompiler* compiler,
5017 RegExpNode* on_success) {
5019 Zone* zone = compiler->zone();
5021 switch (assertion_type()) {
5023 return AssertionNode::AfterNewline(on_success);
5024 case START_OF_INPUT:
5025 return AssertionNode::AtStart(on_success);
5027 return AssertionNode::AtBoundary(on_success);
5029 return AssertionNode::AtNonBoundary(on_success);
5031 return AssertionNode::AtEnd(on_success);
5033 // Compile $ in multiline regexps as an alternation with a positive
5034 // lookahead in one side and an end-of-input on the other side.
5035 // We need two registers for the lookahead.
5036 int stack_pointer_register = compiler->AllocateRegister();
5037 int position_register = compiler->AllocateRegister();
5038 // The ChoiceNode to distinguish between a newline and end-of-input.
5039 ChoiceNode* result = new(zone) ChoiceNode(2, zone);
5040 // Create a newline atom.
5041 ZoneList<CharacterRange>* newline_ranges =
5042 new(zone) ZoneList<CharacterRange>(3, zone);
5043 CharacterRange::AddClassEscape('n', newline_ranges, zone);
5044 RegExpCharacterClass* newline_atom = new(zone) RegExpCharacterClass('n');
5045 TextNode* newline_matcher = new(zone) TextNode(
5047 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
5049 0, // No captures inside.
5050 -1, // Ignored if no captures.
5052 // Create an end-of-input matcher.
5053 RegExpNode* end_of_line = ActionNode::BeginSubmatch(
5054 stack_pointer_register,
5057 // Add the two alternatives to the ChoiceNode.
5058 GuardedAlternative eol_alternative(end_of_line);
5059 result->AddAlternative(eol_alternative);
5060 GuardedAlternative end_alternative(AssertionNode::AtEnd(on_success));
5061 result->AddAlternative(end_alternative);
5071 RegExpNode* RegExpBackReference::ToNode(RegExpCompiler* compiler,
5072 RegExpNode* on_success) {
5073 return new(compiler->zone())
5074 BackReferenceNode(RegExpCapture::StartRegister(index()),
5075 RegExpCapture::EndRegister(index()),
5080 RegExpNode* RegExpEmpty::ToNode(RegExpCompiler* compiler,
5081 RegExpNode* on_success) {
5086 RegExpNode* RegExpLookahead::ToNode(RegExpCompiler* compiler,
5087 RegExpNode* on_success) {
5088 int stack_pointer_register = compiler->AllocateRegister();
5089 int position_register = compiler->AllocateRegister();
5091 const int registers_per_capture = 2;
5092 const int register_of_first_capture = 2;
5093 int register_count = capture_count_ * registers_per_capture;
5094 int register_start =
5095 register_of_first_capture + capture_from_ * registers_per_capture;
5097 RegExpNode* success;
5098 if (is_positive()) {
5099 RegExpNode* node = ActionNode::BeginSubmatch(
5100 stack_pointer_register,
5104 ActionNode::PositiveSubmatchSuccess(stack_pointer_register,
5111 // We use a ChoiceNode for a negative lookahead because it has most of
5112 // the characteristics we need. It has the body of the lookahead as its
5113 // first alternative and the expression after the lookahead of the second
5114 // alternative. If the first alternative succeeds then the
5115 // NegativeSubmatchSuccess will unwind the stack including everything the
5116 // choice node set up and backtrack. If the first alternative fails then
5117 // the second alternative is tried, which is exactly the desired result
5118 // for a negative lookahead. The NegativeLookaheadChoiceNode is a special
5119 // ChoiceNode that knows to ignore the first exit when calculating quick
5121 Zone* zone = compiler->zone();
5123 GuardedAlternative body_alt(
5126 success = new(zone) NegativeSubmatchSuccess(stack_pointer_register,
5131 ChoiceNode* choice_node =
5132 new(zone) NegativeLookaheadChoiceNode(body_alt,
5133 GuardedAlternative(on_success),
5135 return ActionNode::BeginSubmatch(stack_pointer_register,
5142 RegExpNode* RegExpCapture::ToNode(RegExpCompiler* compiler,
5143 RegExpNode* on_success) {
5144 return ToNode(body(), index(), compiler, on_success);
5148 RegExpNode* RegExpCapture::ToNode(RegExpTree* body,
5150 RegExpCompiler* compiler,
5151 RegExpNode* on_success) {
5152 int start_reg = RegExpCapture::StartRegister(index);
5153 int end_reg = RegExpCapture::EndRegister(index);
5154 RegExpNode* store_end = ActionNode::StorePosition(end_reg, true, on_success);
5155 RegExpNode* body_node = body->ToNode(compiler, store_end);
5156 return ActionNode::StorePosition(start_reg, true, body_node);
5160 RegExpNode* RegExpAlternative::ToNode(RegExpCompiler* compiler,
5161 RegExpNode* on_success) {
5162 ZoneList<RegExpTree*>* children = nodes();
5163 RegExpNode* current = on_success;
5164 for (int i = children->length() - 1; i >= 0; i--) {
5165 current = children->at(i)->ToNode(compiler, current);
5171 static void AddClass(const int* elmv,
5173 ZoneList<CharacterRange>* ranges,
5176 DCHECK(elmv[elmc] == 0x10000);
5177 for (int i = 0; i < elmc; i += 2) {
5178 DCHECK(elmv[i] < elmv[i + 1]);
5179 ranges->Add(CharacterRange(elmv[i], elmv[i + 1] - 1), zone);
5184 static void AddClassNegated(const int *elmv,
5186 ZoneList<CharacterRange>* ranges,
5189 DCHECK(elmv[elmc] == 0x10000);
5190 DCHECK(elmv[0] != 0x0000);
5191 DCHECK(elmv[elmc-1] != String::kMaxUtf16CodeUnit);
5193 for (int i = 0; i < elmc; i += 2) {
5194 DCHECK(last <= elmv[i] - 1);
5195 DCHECK(elmv[i] < elmv[i + 1]);
5196 ranges->Add(CharacterRange(last, elmv[i] - 1), zone);
5199 ranges->Add(CharacterRange(last, String::kMaxUtf16CodeUnit), zone);
5203 void CharacterRange::AddClassEscape(uc16 type,
5204 ZoneList<CharacterRange>* ranges,
5208 AddClass(kSpaceRanges, kSpaceRangeCount, ranges, zone);
5211 AddClassNegated(kSpaceRanges, kSpaceRangeCount, ranges, zone);
5214 AddClass(kWordRanges, kWordRangeCount, ranges, zone);
5217 AddClassNegated(kWordRanges, kWordRangeCount, ranges, zone);
5220 AddClass(kDigitRanges, kDigitRangeCount, ranges, zone);
5223 AddClassNegated(kDigitRanges, kDigitRangeCount, ranges, zone);
5226 AddClassNegated(kLineTerminatorRanges,
5227 kLineTerminatorRangeCount,
5231 // This is not a character range as defined by the spec but a
5232 // convenient shorthand for a character class that matches any
5235 ranges->Add(CharacterRange::Everything(), zone);
5237 // This is the set of characters matched by the $ and ^ symbols
5238 // in multiline mode.
5240 AddClass(kLineTerminatorRanges,
5241 kLineTerminatorRangeCount,
5251 Vector<const int> CharacterRange::GetWordBounds() {
5252 return Vector<const int>(kWordRanges, kWordRangeCount - 1);
5256 class CharacterRangeSplitter {
5258 CharacterRangeSplitter(ZoneList<CharacterRange>** included,
5259 ZoneList<CharacterRange>** excluded,
5261 : included_(included),
5262 excluded_(excluded),
5264 void Call(uc16 from, DispatchTable::Entry entry);
5266 static const int kInBase = 0;
5267 static const int kInOverlay = 1;
5270 ZoneList<CharacterRange>** included_;
5271 ZoneList<CharacterRange>** excluded_;
5276 void CharacterRangeSplitter::Call(uc16 from, DispatchTable::Entry entry) {
5277 if (!entry.out_set()->Get(kInBase)) return;
5278 ZoneList<CharacterRange>** target = entry.out_set()->Get(kInOverlay)
5281 if (*target == NULL) *target = new(zone_) ZoneList<CharacterRange>(2, zone_);
5282 (*target)->Add(CharacterRange(entry.from(), entry.to()), zone_);
5286 void CharacterRange::Split(ZoneList<CharacterRange>* base,
5287 Vector<const int> overlay,
5288 ZoneList<CharacterRange>** included,
5289 ZoneList<CharacterRange>** excluded,
5291 DCHECK_EQ(NULL, *included);
5292 DCHECK_EQ(NULL, *excluded);
5293 DispatchTable table(zone);
5294 for (int i = 0; i < base->length(); i++)
5295 table.AddRange(base->at(i), CharacterRangeSplitter::kInBase, zone);
5296 for (int i = 0; i < overlay.length(); i += 2) {
5297 table.AddRange(CharacterRange(overlay[i], overlay[i + 1] - 1),
5298 CharacterRangeSplitter::kInOverlay, zone);
5300 CharacterRangeSplitter callback(included, excluded, zone);
5301 table.ForEach(&callback);
5305 void CharacterRange::AddCaseEquivalents(ZoneList<CharacterRange>* ranges,
5306 bool is_one_byte, Zone* zone) {
5307 Isolate* isolate = zone->isolate();
5308 uc16 bottom = from();
5310 if (is_one_byte && !RangeContainsLatin1Equivalents(*this)) {
5311 if (bottom > String::kMaxOneByteCharCode) return;
5312 if (top > String::kMaxOneByteCharCode) top = String::kMaxOneByteCharCode;
5314 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
5315 if (top == bottom) {
5316 // If this is a singleton we just expand the one character.
5317 int length = isolate->jsregexp_uncanonicalize()->get(bottom, '\0', chars);
5318 for (int i = 0; i < length; i++) {
5319 uc32 chr = chars[i];
5320 if (chr != bottom) {
5321 ranges->Add(CharacterRange::Singleton(chars[i]), zone);
5325 // If this is a range we expand the characters block by block,
5326 // expanding contiguous subranges (blocks) one at a time.
5327 // The approach is as follows. For a given start character we
5328 // look up the remainder of the block that contains it (represented
5329 // by the end point), for instance we find 'z' if the character
5330 // is 'c'. A block is characterized by the property
5331 // that all characters uncanonicalize in the same way, except that
5332 // each entry in the result is incremented by the distance from the first
5333 // element. So a-z is a block because 'a' uncanonicalizes to ['a', 'A'] and
5334 // the k'th letter uncanonicalizes to ['a' + k, 'A' + k].
5335 // Once we've found the end point we look up its uncanonicalization
5336 // and produce a range for each element. For instance for [c-f]
5337 // we look up ['z', 'Z'] and produce [c-f] and [C-F]. We then only
5338 // add a range if it is not already contained in the input, so [c-f]
5339 // will be skipped but [C-F] will be added. If this range is not
5340 // completely contained in a block we do this for all the blocks
5341 // covered by the range (handling characters that is not in a block
5342 // as a "singleton block").
5343 unibrow::uchar range[unibrow::Ecma262UnCanonicalize::kMaxWidth];
5345 while (pos <= top) {
5346 int length = isolate->jsregexp_canonrange()->get(pos, '\0', range);
5351 DCHECK_EQ(1, length);
5352 block_end = range[0];
5354 int end = (block_end > top) ? top : block_end;
5355 length = isolate->jsregexp_uncanonicalize()->get(block_end, '\0', range);
5356 for (int i = 0; i < length; i++) {
5358 uc16 range_from = c - (block_end - pos);
5359 uc16 range_to = c - (block_end - end);
5360 if (!(bottom <= range_from && range_to <= top)) {
5361 ranges->Add(CharacterRange(range_from, range_to), zone);
5370 bool CharacterRange::IsCanonical(ZoneList<CharacterRange>* ranges) {
5371 DCHECK_NOT_NULL(ranges);
5372 int n = ranges->length();
5373 if (n <= 1) return true;
5374 int max = ranges->at(0).to();
5375 for (int i = 1; i < n; i++) {
5376 CharacterRange next_range = ranges->at(i);
5377 if (next_range.from() <= max + 1) return false;
5378 max = next_range.to();
5384 ZoneList<CharacterRange>* CharacterSet::ranges(Zone* zone) {
5385 if (ranges_ == NULL) {
5386 ranges_ = new(zone) ZoneList<CharacterRange>(2, zone);
5387 CharacterRange::AddClassEscape(standard_set_type_, ranges_, zone);
5393 // Move a number of elements in a zonelist to another position
5394 // in the same list. Handles overlapping source and target areas.
5395 static void MoveRanges(ZoneList<CharacterRange>* list,
5399 // Ranges are potentially overlapping.
5401 for (int i = count - 1; i >= 0; i--) {
5402 list->at(to + i) = list->at(from + i);
5405 for (int i = 0; i < count; i++) {
5406 list->at(to + i) = list->at(from + i);
5412 static int InsertRangeInCanonicalList(ZoneList<CharacterRange>* list,
5414 CharacterRange insert) {
5415 // Inserts a range into list[0..count[, which must be sorted
5416 // by from value and non-overlapping and non-adjacent, using at most
5417 // list[0..count] for the result. Returns the number of resulting
5418 // canonicalized ranges. Inserting a range may collapse existing ranges into
5419 // fewer ranges, so the return value can be anything in the range 1..count+1.
5420 uc16 from = insert.from();
5421 uc16 to = insert.to();
5423 int end_pos = count;
5424 for (int i = count - 1; i >= 0; i--) {
5425 CharacterRange current = list->at(i);
5426 if (current.from() > to + 1) {
5428 } else if (current.to() + 1 < from) {
5434 // Inserted range overlaps, or is adjacent to, ranges at positions
5435 // [start_pos..end_pos[. Ranges before start_pos or at or after end_pos are
5436 // not affected by the insertion.
5437 // If start_pos == end_pos, the range must be inserted before start_pos.
5438 // if start_pos < end_pos, the entire range from start_pos to end_pos
5439 // must be merged with the insert range.
5441 if (start_pos == end_pos) {
5442 // Insert between existing ranges at position start_pos.
5443 if (start_pos < count) {
5444 MoveRanges(list, start_pos, start_pos + 1, count - start_pos);
5446 list->at(start_pos) = insert;
5449 if (start_pos + 1 == end_pos) {
5450 // Replace single existing range at position start_pos.
5451 CharacterRange to_replace = list->at(start_pos);
5452 int new_from = Min(to_replace.from(), from);
5453 int new_to = Max(to_replace.to(), to);
5454 list->at(start_pos) = CharacterRange(new_from, new_to);
5457 // Replace a number of existing ranges from start_pos to end_pos - 1.
5458 // Move the remaining ranges down.
5460 int new_from = Min(list->at(start_pos).from(), from);
5461 int new_to = Max(list->at(end_pos - 1).to(), to);
5462 if (end_pos < count) {
5463 MoveRanges(list, end_pos, start_pos + 1, count - end_pos);
5465 list->at(start_pos) = CharacterRange(new_from, new_to);
5466 return count - (end_pos - start_pos) + 1;
5470 void CharacterSet::Canonicalize() {
5471 // Special/default classes are always considered canonical. The result
5472 // of calling ranges() will be sorted.
5473 if (ranges_ == NULL) return;
5474 CharacterRange::Canonicalize(ranges_);
5478 void CharacterRange::Canonicalize(ZoneList<CharacterRange>* character_ranges) {
5479 if (character_ranges->length() <= 1) return;
5480 // Check whether ranges are already canonical (increasing, non-overlapping,
5482 int n = character_ranges->length();
5483 int max = character_ranges->at(0).to();
5486 CharacterRange current = character_ranges->at(i);
5487 if (current.from() <= max + 1) {
5493 // Canonical until the i'th range. If that's all of them, we are done.
5496 // The ranges at index i and forward are not canonicalized. Make them so by
5497 // doing the equivalent of insertion sort (inserting each into the previous
5499 // Notice that inserting a range can reduce the number of ranges in the
5500 // result due to combining of adjacent and overlapping ranges.
5501 int read = i; // Range to insert.
5502 int num_canonical = i; // Length of canonicalized part of list.
5504 num_canonical = InsertRangeInCanonicalList(character_ranges,
5506 character_ranges->at(read));
5509 character_ranges->Rewind(num_canonical);
5511 DCHECK(CharacterRange::IsCanonical(character_ranges));
5515 void CharacterRange::Negate(ZoneList<CharacterRange>* ranges,
5516 ZoneList<CharacterRange>* negated_ranges,
5518 DCHECK(CharacterRange::IsCanonical(ranges));
5519 DCHECK_EQ(0, negated_ranges->length());
5520 int range_count = ranges->length();
5523 if (range_count > 0 && ranges->at(0).from() == 0) {
5524 from = ranges->at(0).to();
5527 while (i < range_count) {
5528 CharacterRange range = ranges->at(i);
5529 negated_ranges->Add(CharacterRange(from + 1, range.from() - 1), zone);
5533 if (from < String::kMaxUtf16CodeUnit) {
5534 negated_ranges->Add(CharacterRange(from + 1, String::kMaxUtf16CodeUnit),
5540 // -------------------------------------------------------------------
5544 OutSet* OutSet::Extend(unsigned value, Zone* zone) {
5547 if (successors(zone) != NULL) {
5548 for (int i = 0; i < successors(zone)->length(); i++) {
5549 OutSet* successor = successors(zone)->at(i);
5550 if (successor->Get(value))
5554 successors_ = new(zone) ZoneList<OutSet*>(2, zone);
5556 OutSet* result = new(zone) OutSet(first_, remaining_);
5557 result->Set(value, zone);
5558 successors(zone)->Add(result, zone);
5563 void OutSet::Set(unsigned value, Zone *zone) {
5564 if (value < kFirstLimit) {
5565 first_ |= (1 << value);
5567 if (remaining_ == NULL)
5568 remaining_ = new(zone) ZoneList<unsigned>(1, zone);
5569 if (remaining_->is_empty() || !remaining_->Contains(value))
5570 remaining_->Add(value, zone);
5575 bool OutSet::Get(unsigned value) const {
5576 if (value < kFirstLimit) {
5577 return (first_ & (1 << value)) != 0;
5578 } else if (remaining_ == NULL) {
5581 return remaining_->Contains(value);
5586 const uc16 DispatchTable::Config::kNoKey = unibrow::Utf8::kBadChar;
5589 void DispatchTable::AddRange(CharacterRange full_range, int value,
5591 CharacterRange current = full_range;
5592 if (tree()->is_empty()) {
5593 // If this is the first range we just insert into the table.
5594 ZoneSplayTree<Config>::Locator loc;
5595 DCHECK_RESULT(tree()->Insert(current.from(), &loc));
5596 loc.set_value(Entry(current.from(), current.to(),
5597 empty()->Extend(value, zone)));
5600 // First see if there is a range to the left of this one that
5602 ZoneSplayTree<Config>::Locator loc;
5603 if (tree()->FindGreatestLessThan(current.from(), &loc)) {
5604 Entry* entry = &loc.value();
5605 // If we've found a range that overlaps with this one, and it
5606 // starts strictly to the left of this one, we have to fix it
5607 // because the following code only handles ranges that start on
5608 // or after the start point of the range we're adding.
5609 if (entry->from() < current.from() && entry->to() >= current.from()) {
5610 // Snap the overlapping range in half around the start point of
5611 // the range we're adding.
5612 CharacterRange left(entry->from(), current.from() - 1);
5613 CharacterRange right(current.from(), entry->to());
5614 // The left part of the overlapping range doesn't overlap.
5615 // Truncate the whole entry to be just the left part.
5616 entry->set_to(left.to());
5617 // The right part is the one that overlaps. We add this part
5618 // to the map and let the next step deal with merging it with
5619 // the range we're adding.
5620 ZoneSplayTree<Config>::Locator loc;
5621 DCHECK_RESULT(tree()->Insert(right.from(), &loc));
5622 loc.set_value(Entry(right.from(),
5627 while (current.is_valid()) {
5628 if (tree()->FindLeastGreaterThan(current.from(), &loc) &&
5629 (loc.value().from() <= current.to()) &&
5630 (loc.value().to() >= current.from())) {
5631 Entry* entry = &loc.value();
5632 // We have overlap. If there is space between the start point of
5633 // the range we're adding and where the overlapping range starts
5634 // then we have to add a range covering just that space.
5635 if (current.from() < entry->from()) {
5636 ZoneSplayTree<Config>::Locator ins;
5637 DCHECK_RESULT(tree()->Insert(current.from(), &ins));
5638 ins.set_value(Entry(current.from(),
5640 empty()->Extend(value, zone)));
5641 current.set_from(entry->from());
5643 DCHECK_EQ(current.from(), entry->from());
5644 // If the overlapping range extends beyond the one we want to add
5645 // we have to snap the right part off and add it separately.
5646 if (entry->to() > current.to()) {
5647 ZoneSplayTree<Config>::Locator ins;
5648 DCHECK_RESULT(tree()->Insert(current.to() + 1, &ins));
5649 ins.set_value(Entry(current.to() + 1,
5652 entry->set_to(current.to());
5654 DCHECK(entry->to() <= current.to());
5655 // The overlapping range is now completely contained by the range
5656 // we're adding so we can just update it and move the start point
5657 // of the range we're adding just past it.
5658 entry->AddValue(value, zone);
5659 // Bail out if the last interval ended at 0xFFFF since otherwise
5660 // adding 1 will wrap around to 0.
5661 if (entry->to() == String::kMaxUtf16CodeUnit)
5663 DCHECK(entry->to() + 1 > current.from());
5664 current.set_from(entry->to() + 1);
5666 // There is no overlap so we can just add the range
5667 ZoneSplayTree<Config>::Locator ins;
5668 DCHECK_RESULT(tree()->Insert(current.from(), &ins));
5669 ins.set_value(Entry(current.from(),
5671 empty()->Extend(value, zone)));
5678 OutSet* DispatchTable::Get(uc16 value) {
5679 ZoneSplayTree<Config>::Locator loc;
5680 if (!tree()->FindGreatestLessThan(value, &loc))
5682 Entry* entry = &loc.value();
5683 if (value <= entry->to())
5684 return entry->out_set();
5690 // -------------------------------------------------------------------
5694 void Analysis::EnsureAnalyzed(RegExpNode* that) {
5695 StackLimitCheck check(that->zone()->isolate());
5696 if (check.HasOverflowed()) {
5697 fail("Stack overflow");
5700 if (that->info()->been_analyzed || that->info()->being_analyzed)
5702 that->info()->being_analyzed = true;
5704 that->info()->being_analyzed = false;
5705 that->info()->been_analyzed = true;
5709 void Analysis::VisitEnd(EndNode* that) {
5714 void TextNode::CalculateOffsets() {
5715 int element_count = elements()->length();
5716 // Set up the offsets of the elements relative to the start. This is a fixed
5717 // quantity since a TextNode can only contain fixed-width things.
5719 for (int i = 0; i < element_count; i++) {
5720 TextElement& elm = elements()->at(i);
5721 elm.set_cp_offset(cp_offset);
5722 cp_offset += elm.length();
5727 void Analysis::VisitText(TextNode* that) {
5729 that->MakeCaseIndependent(is_one_byte_);
5731 EnsureAnalyzed(that->on_success());
5732 if (!has_failed()) {
5733 that->CalculateOffsets();
5738 void Analysis::VisitAction(ActionNode* that) {
5739 RegExpNode* target = that->on_success();
5740 EnsureAnalyzed(target);
5741 if (!has_failed()) {
5742 // If the next node is interested in what it follows then this node
5743 // has to be interested too so it can pass the information on.
5744 that->info()->AddFromFollowing(target->info());
5749 void Analysis::VisitChoice(ChoiceNode* that) {
5750 NodeInfo* info = that->info();
5751 for (int i = 0; i < that->alternatives()->length(); i++) {
5752 RegExpNode* node = that->alternatives()->at(i).node();
5753 EnsureAnalyzed(node);
5754 if (has_failed()) return;
5755 // Anything the following nodes need to know has to be known by
5756 // this node also, so it can pass it on.
5757 info->AddFromFollowing(node->info());
5762 void Analysis::VisitLoopChoice(LoopChoiceNode* that) {
5763 NodeInfo* info = that->info();
5764 for (int i = 0; i < that->alternatives()->length(); i++) {
5765 RegExpNode* node = that->alternatives()->at(i).node();
5766 if (node != that->loop_node()) {
5767 EnsureAnalyzed(node);
5768 if (has_failed()) return;
5769 info->AddFromFollowing(node->info());
5772 // Check the loop last since it may need the value of this node
5773 // to get a correct result.
5774 EnsureAnalyzed(that->loop_node());
5775 if (!has_failed()) {
5776 info->AddFromFollowing(that->loop_node()->info());
5781 void Analysis::VisitBackReference(BackReferenceNode* that) {
5782 EnsureAnalyzed(that->on_success());
5786 void Analysis::VisitAssertion(AssertionNode* that) {
5787 EnsureAnalyzed(that->on_success());
5791 void BackReferenceNode::FillInBMInfo(int offset,
5793 BoyerMooreLookahead* bm,
5794 bool not_at_start) {
5795 // Working out the set of characters that a backreference can match is too
5796 // hard, so we just say that any character can match.
5797 bm->SetRest(offset);
5798 SaveBMInfo(bm, not_at_start, offset);
5802 STATIC_ASSERT(BoyerMoorePositionInfo::kMapSize ==
5803 RegExpMacroAssembler::kTableSize);
5806 void ChoiceNode::FillInBMInfo(int offset,
5808 BoyerMooreLookahead* bm,
5809 bool not_at_start) {
5810 ZoneList<GuardedAlternative>* alts = alternatives();
5811 budget = (budget - 1) / alts->length();
5812 for (int i = 0; i < alts->length(); i++) {
5813 GuardedAlternative& alt = alts->at(i);
5814 if (alt.guards() != NULL && alt.guards()->length() != 0) {
5815 bm->SetRest(offset); // Give up trying to fill in info.
5816 SaveBMInfo(bm, not_at_start, offset);
5819 alt.node()->FillInBMInfo(offset, budget, bm, not_at_start);
5821 SaveBMInfo(bm, not_at_start, offset);
5825 void TextNode::FillInBMInfo(int initial_offset,
5827 BoyerMooreLookahead* bm,
5828 bool not_at_start) {
5829 if (initial_offset >= bm->length()) return;
5830 int offset = initial_offset;
5831 int max_char = bm->max_char();
5832 for (int i = 0; i < elements()->length(); i++) {
5833 if (offset >= bm->length()) {
5834 if (initial_offset == 0) set_bm_info(not_at_start, bm);
5837 TextElement text = elements()->at(i);
5838 if (text.text_type() == TextElement::ATOM) {
5839 RegExpAtom* atom = text.atom();
5840 for (int j = 0; j < atom->length(); j++, offset++) {
5841 if (offset >= bm->length()) {
5842 if (initial_offset == 0) set_bm_info(not_at_start, bm);
5845 uc16 character = atom->data()[j];
5846 if (bm->compiler()->ignore_case()) {
5847 unibrow::uchar chars[unibrow::Ecma262UnCanonicalize::kMaxWidth];
5848 int length = GetCaseIndependentLetters(
5851 bm->max_char() == String::kMaxOneByteCharCode,
5853 for (int j = 0; j < length; j++) {
5854 bm->Set(offset, chars[j]);
5857 if (character <= max_char) bm->Set(offset, character);
5861 DCHECK_EQ(TextElement::CHAR_CLASS, text.text_type());
5862 RegExpCharacterClass* char_class = text.char_class();
5863 ZoneList<CharacterRange>* ranges = char_class->ranges(zone());
5864 if (char_class->is_negated()) {
5867 for (int k = 0; k < ranges->length(); k++) {
5868 CharacterRange& range = ranges->at(k);
5869 if (range.from() > max_char) continue;
5870 int to = Min(max_char, static_cast<int>(range.to()));
5871 bm->SetInterval(offset, Interval(range.from(), to));
5877 if (offset >= bm->length()) {
5878 if (initial_offset == 0) set_bm_info(not_at_start, bm);
5881 on_success()->FillInBMInfo(offset,
5884 true); // Not at start after a text node.
5885 if (initial_offset == 0) set_bm_info(not_at_start, bm);
5889 // -------------------------------------------------------------------
5890 // Dispatch table construction
5893 void DispatchTableConstructor::VisitEnd(EndNode* that) {
5894 AddRange(CharacterRange::Everything());
5898 void DispatchTableConstructor::BuildTable(ChoiceNode* node) {
5899 node->set_being_calculated(true);
5900 ZoneList<GuardedAlternative>* alternatives = node->alternatives();
5901 for (int i = 0; i < alternatives->length(); i++) {
5902 set_choice_index(i);
5903 alternatives->at(i).node()->Accept(this);
5905 node->set_being_calculated(false);
5909 class AddDispatchRange {
5911 explicit AddDispatchRange(DispatchTableConstructor* constructor)
5912 : constructor_(constructor) { }
5913 void Call(uc32 from, DispatchTable::Entry entry);
5915 DispatchTableConstructor* constructor_;
5919 void AddDispatchRange::Call(uc32 from, DispatchTable::Entry entry) {
5920 CharacterRange range(from, entry.to());
5921 constructor_->AddRange(range);
5925 void DispatchTableConstructor::VisitChoice(ChoiceNode* node) {
5926 if (node->being_calculated())
5928 DispatchTable* table = node->GetTable(ignore_case_);
5929 AddDispatchRange adder(this);
5930 table->ForEach(&adder);
5934 void DispatchTableConstructor::VisitBackReference(BackReferenceNode* that) {
5935 // TODO(160): Find the node that we refer back to and propagate its start
5936 // set back to here. For now we just accept anything.
5937 AddRange(CharacterRange::Everything());
5941 void DispatchTableConstructor::VisitAssertion(AssertionNode* that) {
5942 RegExpNode* target = that->on_success();
5943 target->Accept(this);
5947 static int CompareRangeByFrom(const CharacterRange* a,
5948 const CharacterRange* b) {
5949 return Compare<uc16>(a->from(), b->from());
5953 void DispatchTableConstructor::AddInverse(ZoneList<CharacterRange>* ranges) {
5954 ranges->Sort(CompareRangeByFrom);
5956 for (int i = 0; i < ranges->length(); i++) {
5957 CharacterRange range = ranges->at(i);
5958 if (last < range.from())
5959 AddRange(CharacterRange(last, range.from() - 1));
5960 if (range.to() >= last) {
5961 if (range.to() == String::kMaxUtf16CodeUnit) {
5964 last = range.to() + 1;
5968 AddRange(CharacterRange(last, String::kMaxUtf16CodeUnit));
5972 void DispatchTableConstructor::VisitText(TextNode* that) {
5973 TextElement elm = that->elements()->at(0);
5974 switch (elm.text_type()) {
5975 case TextElement::ATOM: {
5976 uc16 c = elm.atom()->data()[0];
5977 AddRange(CharacterRange(c, c));
5980 case TextElement::CHAR_CLASS: {
5981 RegExpCharacterClass* tree = elm.char_class();
5982 ZoneList<CharacterRange>* ranges = tree->ranges(that->zone());
5983 if (tree->is_negated()) {
5986 for (int i = 0; i < ranges->length(); i++)
5987 AddRange(ranges->at(i));
5998 void DispatchTableConstructor::VisitAction(ActionNode* that) {
5999 RegExpNode* target = that->on_success();
6000 target->Accept(this);
6004 RegExpEngine::CompilationResult RegExpEngine::Compile(
6005 RegExpCompileData* data, bool ignore_case, bool is_global,
6006 bool is_multiline, bool is_sticky, Handle<String> pattern,
6007 Handle<String> sample_subject, bool is_one_byte, Zone* zone) {
6008 if ((data->capture_count + 1) * 2 - 1 > RegExpMacroAssembler::kMaxRegister) {
6009 return IrregexpRegExpTooBig(zone->isolate());
6011 RegExpCompiler compiler(data->capture_count, ignore_case, is_one_byte, zone);
6013 compiler.set_optimize(!TooMuchRegExpCode(pattern));
6015 // Sample some characters from the middle of the string.
6016 static const int kSampleSize = 128;
6018 sample_subject = String::Flatten(sample_subject);
6019 int chars_sampled = 0;
6020 int half_way = (sample_subject->length() - kSampleSize) / 2;
6021 for (int i = Max(0, half_way);
6022 i < sample_subject->length() && chars_sampled < kSampleSize;
6023 i++, chars_sampled++) {
6024 compiler.frequency_collator()->CountCharacter(sample_subject->Get(i));
6027 // Wrap the body of the regexp in capture #0.
6028 RegExpNode* captured_body = RegExpCapture::ToNode(data->tree,
6032 RegExpNode* node = captured_body;
6033 bool is_end_anchored = data->tree->IsAnchoredAtEnd();
6034 bool is_start_anchored = data->tree->IsAnchoredAtStart();
6035 int max_length = data->tree->max_match();
6036 if (!is_start_anchored && !is_sticky) {
6037 // Add a .*? at the beginning, outside the body capture, unless
6038 // this expression is anchored at the beginning or sticky.
6039 RegExpNode* loop_node =
6040 RegExpQuantifier::ToNode(0,
6041 RegExpTree::kInfinity,
6043 new(zone) RegExpCharacterClass('*'),
6046 data->contains_anchor);
6048 if (data->contains_anchor) {
6049 // Unroll loop once, to take care of the case that might start
6050 // at the start of input.
6051 ChoiceNode* first_step_node = new(zone) ChoiceNode(2, zone);
6052 first_step_node->AddAlternative(GuardedAlternative(captured_body));
6053 first_step_node->AddAlternative(GuardedAlternative(
6054 new(zone) TextNode(new(zone) RegExpCharacterClass('*'), loop_node)));
6055 node = first_step_node;
6061 node = node->FilterOneByte(RegExpCompiler::kMaxRecursion, ignore_case);
6062 // Do it again to propagate the new nodes to places where they were not
6063 // put because they had not been calculated yet.
6065 node = node->FilterOneByte(RegExpCompiler::kMaxRecursion, ignore_case);
6069 if (node == NULL) node = new(zone) EndNode(EndNode::BACKTRACK, zone);
6071 Analysis analysis(ignore_case, is_one_byte);
6072 analysis.EnsureAnalyzed(node);
6073 if (analysis.has_failed()) {
6074 const char* error_message = analysis.error_message();
6075 return CompilationResult(zone->isolate(), error_message);
6078 // Create the correct assembler for the architecture.
6079 #ifndef V8_INTERPRETED_REGEXP
6080 // Native regexp implementation.
6082 NativeRegExpMacroAssembler::Mode mode =
6083 is_one_byte ? NativeRegExpMacroAssembler::LATIN1
6084 : NativeRegExpMacroAssembler::UC16;
6086 #if V8_TARGET_ARCH_IA32
6087 RegExpMacroAssemblerIA32 macro_assembler(mode, (data->capture_count + 1) * 2,
6089 #elif V8_TARGET_ARCH_X64
6090 RegExpMacroAssemblerX64 macro_assembler(mode, (data->capture_count + 1) * 2,
6092 #elif V8_TARGET_ARCH_ARM
6093 RegExpMacroAssemblerARM macro_assembler(mode, (data->capture_count + 1) * 2,
6095 #elif V8_TARGET_ARCH_ARM64
6096 RegExpMacroAssemblerARM64 macro_assembler(mode, (data->capture_count + 1) * 2,
6098 #elif V8_TARGET_ARCH_MIPS
6099 RegExpMacroAssemblerMIPS macro_assembler(mode, (data->capture_count + 1) * 2,
6101 #elif V8_TARGET_ARCH_MIPS64
6102 RegExpMacroAssemblerMIPS macro_assembler(mode, (data->capture_count + 1) * 2,
6104 #elif V8_TARGET_ARCH_X87
6105 RegExpMacroAssemblerX87 macro_assembler(mode, (data->capture_count + 1) * 2,
6108 #error "Unsupported architecture"
6111 #else // V8_INTERPRETED_REGEXP
6112 // Interpreted regexp implementation.
6113 EmbeddedVector<byte, 1024> codes;
6114 RegExpMacroAssemblerIrregexp macro_assembler(codes, zone);
6115 #endif // V8_INTERPRETED_REGEXP
6117 macro_assembler.set_slow_safe(TooMuchRegExpCode(pattern));
6119 // Inserted here, instead of in Assembler, because it depends on information
6120 // in the AST that isn't replicated in the Node structure.
6121 static const int kMaxBacksearchLimit = 1024;
6122 if (is_end_anchored &&
6123 !is_start_anchored &&
6124 max_length < kMaxBacksearchLimit) {
6125 macro_assembler.SetCurrentPositionFromEnd(max_length);
6129 macro_assembler.set_global_mode(
6130 (data->tree->min_match() > 0)
6131 ? RegExpMacroAssembler::GLOBAL_NO_ZERO_LENGTH_CHECK
6132 : RegExpMacroAssembler::GLOBAL);
6135 return compiler.Assemble(¯o_assembler,
6137 data->capture_count,
6142 bool RegExpEngine::TooMuchRegExpCode(Handle<String> pattern) {
6143 Heap* heap = pattern->GetHeap();
6144 bool too_much = pattern->length() > RegExpImpl::kRegExpTooLargeToOptimize;
6145 if (heap->total_regexp_code_generated() > RegExpImpl::kRegExpCompiledLimit &&
6146 heap->isolate()->memory_allocator()->SizeExecutable() >
6147 RegExpImpl::kRegExpExecutableMemoryLimit) {
6152 }} // namespace v8::internal