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