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