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.
9 #include "src/cpu-profiler.h"
11 #include "src/macro-assembler.h"
12 #include "src/regexp-macro-assembler.h"
13 #include "src/regexp-stack.h"
14 #include "src/serialize.h"
15 #include "src/unicode.h"
16 #include "src/x64/regexp-macro-assembler-x64.h"
21 #ifndef V8_INTERPRETED_REGEXP
24 * This assembler uses the following register assignment convention
25 * - rdx : Currently loaded character(s) as Latin1 or UC16. Must be loaded
26 * using LoadCurrentCharacter before using any of the dispatch methods.
27 * Temporarily stores the index of capture start after a matching pass
28 * for a global regexp.
29 * - rdi : Current position in input, as negative offset from end of string.
30 * Please notice that this is the byte offset, not the character
31 * offset! Is always a 32-bit signed (negative) offset, but must be
32 * maintained sign-extended to 64 bits, since it is used as index.
33 * - rsi : End of input (points to byte after last character in input),
34 * so that rsi+rdi points to the current character.
35 * - rbp : Frame pointer. Used to access arguments, local variables and
37 * - rsp : Points to tip of C stack.
38 * - rcx : Points to tip of backtrack stack. The backtrack stack contains
39 * only 32-bit values. Most are offsets from some base (e.g., character
40 * positions from end of string or code location from Code* pointer).
41 * - r8 : Code object pointer. Used to convert between absolute and
42 * code-object-relative addresses.
44 * The registers rax, rbx, r9 and r11 are free to use for computations.
45 * If changed to use r12+, they should be saved as callee-save registers.
46 * The macro assembler special registers r12 and r13 (kSmiConstantRegister,
47 * kRootRegister) aren't special during execution of RegExp code (they don't
48 * hold the values assumed when creating JS code), so no Smi or Root related
49 * macro operations can be used.
51 * Each call to a C++ method should retain these registers.
53 * The stack will have the following content, in some order, indexable from the
54 * frame pointer (see, e.g., kStackHighEnd):
55 * - Isolate* isolate (address of the current isolate)
56 * - direct_call (if 1, direct call from JavaScript code, if 0 call
57 * through the runtime system)
58 * - stack_area_base (high end of the memory area to use as
60 * - capture array size (may fit multiple sets of matches)
61 * - int* capture_array (int[num_saved_registers_], for output).
62 * - end of input (address of end of string)
63 * - start of input (address of first character in string)
64 * - start index (character index of start)
65 * - String* input_string (input string)
67 * - backup of callee save registers (rbx, possibly rsi and rdi).
68 * - success counter (only useful for global regexp to count matches)
69 * - Offset of location before start of input (effectively character
70 * position -1). Used to initialize capture registers to a non-position.
71 * - At start of string (if 1, we are starting at the start of the
72 * string, otherwise 0)
73 * - register 0 rbp[-n] (Only positions must be stored in the first
74 * - register 1 rbp[-n-8] num_saved_registers_ registers)
77 * The first num_saved_registers_ registers are initialized to point to
78 * "character -1" in the string (i.e., char_size() bytes before the first
79 * character of the string). The remaining registers starts out uninitialized.
81 * The first seven values must be provided by the calling code by
82 * calling the code's entry address cast to a function pointer with the
83 * following signature:
84 * int (*match)(String* input_string,
88 * int* capture_output_array,
90 * byte* stack_area_base,
94 #define __ ACCESS_MASM((&masm_))
96 RegExpMacroAssemblerX64::RegExpMacroAssemblerX64(Isolate* isolate, Zone* zone,
98 int registers_to_save)
99 : NativeRegExpMacroAssembler(isolate, zone),
100 masm_(isolate, NULL, kRegExpCodeSize),
101 no_root_array_scope_(&masm_),
102 code_relative_fixup_positions_(4, zone),
104 num_registers_(registers_to_save),
105 num_saved_registers_(registers_to_save),
111 DCHECK_EQ(0, registers_to_save % 2);
112 __ jmp(&entry_label_); // We'll write the entry code when we know more.
113 __ bind(&start_label_); // And then continue from here.
117 RegExpMacroAssemblerX64::~RegExpMacroAssemblerX64() {
118 // Unuse labels in case we throw away the assembler without calling GetCode.
119 entry_label_.Unuse();
120 start_label_.Unuse();
121 success_label_.Unuse();
122 backtrack_label_.Unuse();
124 check_preempt_label_.Unuse();
125 stack_overflow_label_.Unuse();
129 int RegExpMacroAssemblerX64::stack_limit_slack() {
130 return RegExpStack::kStackLimitSlack;
134 void RegExpMacroAssemblerX64::AdvanceCurrentPosition(int by) {
136 __ addq(rdi, Immediate(by * char_size()));
141 void RegExpMacroAssemblerX64::AdvanceRegister(int reg, int by) {
143 DCHECK(reg < num_registers_);
145 __ addp(register_location(reg), Immediate(by));
150 void RegExpMacroAssemblerX64::Backtrack() {
152 // Pop Code* offset from backtrack stack, add Code* and jump to location.
154 __ addp(rbx, code_object_pointer());
159 void RegExpMacroAssemblerX64::Bind(Label* label) {
164 void RegExpMacroAssemblerX64::CheckCharacter(uint32_t c, Label* on_equal) {
165 __ cmpl(current_character(), Immediate(c));
166 BranchOrBacktrack(equal, on_equal);
170 void RegExpMacroAssemblerX64::CheckCharacterGT(uc16 limit, Label* on_greater) {
171 __ cmpl(current_character(), Immediate(limit));
172 BranchOrBacktrack(greater, on_greater);
176 void RegExpMacroAssemblerX64::CheckAtStart(Label* on_at_start) {
178 // Did we start the match at the start of the string at all?
179 __ cmpl(Operand(rbp, kStartIndex), Immediate(0));
180 BranchOrBacktrack(not_equal, ¬_at_start);
181 // If we did, are we still at the start of the input?
182 __ leap(rax, Operand(rsi, rdi, times_1, 0));
183 __ cmpp(rax, Operand(rbp, kInputStart));
184 BranchOrBacktrack(equal, on_at_start);
185 __ bind(¬_at_start);
189 void RegExpMacroAssemblerX64::CheckNotAtStart(Label* on_not_at_start) {
190 // Did we start the match at the start of the string at all?
191 __ cmpl(Operand(rbp, kStartIndex), Immediate(0));
192 BranchOrBacktrack(not_equal, on_not_at_start);
193 // If we did, are we still at the start of the input?
194 __ leap(rax, Operand(rsi, rdi, times_1, 0));
195 __ cmpp(rax, Operand(rbp, kInputStart));
196 BranchOrBacktrack(not_equal, on_not_at_start);
200 void RegExpMacroAssemblerX64::CheckCharacterLT(uc16 limit, Label* on_less) {
201 __ cmpl(current_character(), Immediate(limit));
202 BranchOrBacktrack(less, on_less);
206 void RegExpMacroAssemblerX64::CheckGreedyLoop(Label* on_equal) {
208 __ cmpl(rdi, Operand(backtrack_stackpointer(), 0));
209 __ j(not_equal, &fallthrough);
211 BranchOrBacktrack(no_condition, on_equal);
212 __ bind(&fallthrough);
216 void RegExpMacroAssemblerX64::CheckNotBackReferenceIgnoreCase(
218 Label* on_no_match) {
220 ReadPositionFromRegister(rdx, start_reg); // Offset of start of capture
221 ReadPositionFromRegister(rbx, start_reg + 1); // Offset of end of capture
222 __ subp(rbx, rdx); // Length of capture.
224 // -----------------------
225 // rdx = Start offset of capture.
226 // rbx = Length of capture
228 // If length is negative, this code will fail (it's a symptom of a partial or
229 // illegal capture where start of capture after end of capture).
230 // This must not happen (no back-reference can reference a capture that wasn't
231 // closed before in the reg-exp, and we must not generate code that can cause
234 // If length is zero, either the capture is empty or it is nonparticipating.
235 // In either case succeed immediately.
236 __ j(equal, &fallthrough);
238 // -----------------------
239 // rdx - Start of capture
240 // rbx - length of capture
241 // Check that there are sufficient characters left in the input.
244 BranchOrBacktrack(greater, on_no_match);
246 if (mode_ == LATIN1) {
247 Label loop_increment;
248 if (on_no_match == NULL) {
249 on_no_match = &backtrack_label_;
252 __ leap(r9, Operand(rsi, rdx, times_1, 0));
253 __ leap(r11, Operand(rsi, rdi, times_1, 0));
254 __ addp(rbx, r9); // End of capture
255 // ---------------------
256 // r11 - current input character address
257 // r9 - current capture character address
258 // rbx - end of capture
262 __ movzxbl(rdx, Operand(r9, 0));
263 __ movzxbl(rax, Operand(r11, 0));
264 // al - input character
265 // dl - capture character
267 __ j(equal, &loop_increment);
269 // Mismatch, try case-insensitive match (converting letters to lower-case).
270 // I.e., if or-ing with 0x20 makes values equal and in range 'a'-'z', it's
272 __ orp(rax, Immediate(0x20)); // Convert match character to lower-case.
273 __ orp(rdx, Immediate(0x20)); // Convert capture character to lower-case.
275 __ j(not_equal, on_no_match); // Definitely not equal.
276 __ subb(rax, Immediate('a'));
277 __ cmpb(rax, Immediate('z' - 'a'));
278 __ j(below_equal, &loop_increment); // In range 'a'-'z'.
279 // Latin-1: Check for values in range [224,254] but not 247.
280 __ subb(rax, Immediate(224 - 'a'));
281 __ cmpb(rax, Immediate(254 - 224));
282 __ j(above, on_no_match); // Weren't Latin-1 letters.
283 __ cmpb(rax, Immediate(247 - 224)); // Check for 247.
284 __ j(equal, on_no_match);
285 __ bind(&loop_increment);
286 // Increment pointers into match and capture strings.
287 __ addp(r11, Immediate(1));
288 __ addp(r9, Immediate(1));
289 // Compare to end of capture, and loop if not done.
293 // Compute new value of character position after the matched part.
297 DCHECK(mode_ == UC16);
298 // Save important/volatile registers before calling C function.
300 // Caller save on Linux and callee save in Windows.
304 __ pushq(backtrack_stackpointer());
306 static const int num_arguments = 4;
307 __ PrepareCallCFunction(num_arguments);
309 // Put arguments into parameter registers. Parameters are
310 // Address byte_offset1 - Address captured substring's start.
311 // Address byte_offset2 - Address of current character position.
312 // size_t byte_length - length of capture in bytes(!)
315 // Compute and set byte_offset1 (start of capture).
316 __ leap(rcx, Operand(rsi, rdx, times_1, 0));
318 __ leap(rdx, Operand(rsi, rdi, times_1, 0));
322 __ LoadAddress(r9, ExternalReference::isolate_address(isolate()));
323 #else // AMD64 calling convention
324 // Compute byte_offset2 (current position = rsi+rdi).
325 __ leap(rax, Operand(rsi, rdi, times_1, 0));
326 // Compute and set byte_offset1 (start of capture).
327 __ leap(rdi, Operand(rsi, rdx, times_1, 0));
333 __ LoadAddress(rcx, ExternalReference::isolate_address(isolate()));
336 { // NOLINT: Can't find a way to open this scope without confusing the
338 AllowExternalCallThatCantCauseGC scope(&masm_);
339 ExternalReference compare =
340 ExternalReference::re_case_insensitive_compare_uc16(isolate());
341 __ CallCFunction(compare, num_arguments);
344 // Restore original values before reacting on result value.
345 __ Move(code_object_pointer(), masm_.CodeObject());
346 __ popq(backtrack_stackpointer());
352 // Check if function returned non-zero for success or zero for failure.
354 BranchOrBacktrack(zero, on_no_match);
355 // On success, increment position by length of capture.
356 // Requires that rbx is callee save (true for both Win64 and AMD64 ABIs).
359 __ bind(&fallthrough);
363 void RegExpMacroAssemblerX64::CheckNotBackReference(
365 Label* on_no_match) {
368 // Find length of back-referenced capture.
369 ReadPositionFromRegister(rdx, start_reg); // Offset of start of capture
370 ReadPositionFromRegister(rax, start_reg + 1); // Offset of end of capture
371 __ subp(rax, rdx); // Length to check.
373 // Fail on partial or illegal capture (start of capture after end of capture).
374 // This must not happen (no back-reference can reference a capture that wasn't
375 // closed before in the reg-exp).
376 __ Check(greater_equal, kInvalidCaptureReferenced);
378 // Succeed on empty capture (including non-participating capture)
379 __ j(equal, &fallthrough);
381 // -----------------------
382 // rdx - Start of capture
383 // rax - length of capture
385 // Check that there are sufficient characters left in the input.
388 BranchOrBacktrack(greater, on_no_match);
390 // Compute pointers to match string and capture string
391 __ leap(rbx, Operand(rsi, rdi, times_1, 0)); // Start of match.
392 __ addp(rdx, rsi); // Start of capture.
393 __ leap(r9, Operand(rdx, rax, times_1, 0)); // End of capture
395 // -----------------------
396 // rbx - current capture character address.
397 // rbx - current input character address .
398 // r9 - end of input to match (capture length after rbx).
402 if (mode_ == LATIN1) {
403 __ movzxbl(rax, Operand(rdx, 0));
404 __ cmpb(rax, Operand(rbx, 0));
406 DCHECK(mode_ == UC16);
407 __ movzxwl(rax, Operand(rdx, 0));
408 __ cmpw(rax, Operand(rbx, 0));
410 BranchOrBacktrack(not_equal, on_no_match);
411 // Increment pointers into capture and match string.
412 __ addp(rbx, Immediate(char_size()));
413 __ addp(rdx, Immediate(char_size()));
414 // Check if we have reached end of match area.
419 // Set current character position to position after match.
423 __ bind(&fallthrough);
427 void RegExpMacroAssemblerX64::CheckNotCharacter(uint32_t c,
428 Label* on_not_equal) {
429 __ cmpl(current_character(), Immediate(c));
430 BranchOrBacktrack(not_equal, on_not_equal);
434 void RegExpMacroAssemblerX64::CheckCharacterAfterAnd(uint32_t c,
438 __ testl(current_character(), Immediate(mask));
440 __ movl(rax, Immediate(mask));
441 __ andp(rax, current_character());
442 __ cmpl(rax, Immediate(c));
444 BranchOrBacktrack(equal, on_equal);
448 void RegExpMacroAssemblerX64::CheckNotCharacterAfterAnd(uint32_t c,
450 Label* on_not_equal) {
452 __ testl(current_character(), Immediate(mask));
454 __ movl(rax, Immediate(mask));
455 __ andp(rax, current_character());
456 __ cmpl(rax, Immediate(c));
458 BranchOrBacktrack(not_equal, on_not_equal);
462 void RegExpMacroAssemblerX64::CheckNotCharacterAfterMinusAnd(
466 Label* on_not_equal) {
467 DCHECK(minus < String::kMaxUtf16CodeUnit);
468 __ leap(rax, Operand(current_character(), -minus));
469 __ andp(rax, Immediate(mask));
470 __ cmpl(rax, Immediate(c));
471 BranchOrBacktrack(not_equal, on_not_equal);
475 void RegExpMacroAssemblerX64::CheckCharacterInRange(
478 Label* on_in_range) {
479 __ leal(rax, Operand(current_character(), -from));
480 __ cmpl(rax, Immediate(to - from));
481 BranchOrBacktrack(below_equal, on_in_range);
485 void RegExpMacroAssemblerX64::CheckCharacterNotInRange(
488 Label* on_not_in_range) {
489 __ leal(rax, Operand(current_character(), -from));
490 __ cmpl(rax, Immediate(to - from));
491 BranchOrBacktrack(above, on_not_in_range);
495 void RegExpMacroAssemblerX64::CheckBitInTable(
496 Handle<ByteArray> table,
499 Register index = current_character();
500 if (mode_ != LATIN1 || kTableMask != String::kMaxOneByteCharCode) {
501 __ movp(rbx, current_character());
502 __ andp(rbx, Immediate(kTableMask));
505 __ cmpb(FieldOperand(rax, index, times_1, ByteArray::kHeaderSize),
507 BranchOrBacktrack(not_equal, on_bit_set);
511 bool RegExpMacroAssemblerX64::CheckSpecialCharacterClass(uc16 type,
512 Label* on_no_match) {
513 // Range checks (c in min..max) are generally implemented by an unsigned
514 // (c - min) <= (max - min) check, using the sequence:
515 // leap(rax, Operand(current_character(), -min)) or sub(rax, Immediate(min))
516 // cmp(rax, Immediate(max - min))
519 // Match space-characters
520 if (mode_ == LATIN1) {
521 // One byte space characters are '\t'..'\r', ' ' and \u00a0.
523 __ cmpl(current_character(), Immediate(' '));
524 __ j(equal, &success, Label::kNear);
525 // Check range 0x09..0x0d
526 __ leap(rax, Operand(current_character(), -'\t'));
527 __ cmpl(rax, Immediate('\r' - '\t'));
528 __ j(below_equal, &success, Label::kNear);
530 __ cmpl(rax, Immediate(0x00a0 - '\t'));
531 BranchOrBacktrack(not_equal, on_no_match);
537 // The emitted code for generic character classes is good enough.
540 // Match ASCII digits ('0'..'9')
541 __ leap(rax, Operand(current_character(), -'0'));
542 __ cmpl(rax, Immediate('9' - '0'));
543 BranchOrBacktrack(above, on_no_match);
546 // Match non ASCII-digits
547 __ leap(rax, Operand(current_character(), -'0'));
548 __ cmpl(rax, Immediate('9' - '0'));
549 BranchOrBacktrack(below_equal, on_no_match);
552 // Match non-newlines (not 0x0a('\n'), 0x0d('\r'), 0x2028 and 0x2029)
553 __ movl(rax, current_character());
554 __ xorp(rax, Immediate(0x01));
555 // See if current character is '\n'^1 or '\r'^1, i.e., 0x0b or 0x0c
556 __ subl(rax, Immediate(0x0b));
557 __ cmpl(rax, Immediate(0x0c - 0x0b));
558 BranchOrBacktrack(below_equal, on_no_match);
560 // Compare original value to 0x2028 and 0x2029, using the already
561 // computed (current_char ^ 0x01 - 0x0b). I.e., check for
562 // 0x201d (0x2028 - 0x0b) or 0x201e.
563 __ subl(rax, Immediate(0x2028 - 0x0b));
564 __ cmpl(rax, Immediate(0x2029 - 0x2028));
565 BranchOrBacktrack(below_equal, on_no_match);
570 // Match newlines (0x0a('\n'), 0x0d('\r'), 0x2028 and 0x2029)
571 __ movl(rax, current_character());
572 __ xorp(rax, Immediate(0x01));
573 // See if current character is '\n'^1 or '\r'^1, i.e., 0x0b or 0x0c
574 __ subl(rax, Immediate(0x0b));
575 __ cmpl(rax, Immediate(0x0c - 0x0b));
576 if (mode_ == LATIN1) {
577 BranchOrBacktrack(above, on_no_match);
580 BranchOrBacktrack(below_equal, &done);
581 // Compare original value to 0x2028 and 0x2029, using the already
582 // computed (current_char ^ 0x01 - 0x0b). I.e., check for
583 // 0x201d (0x2028 - 0x0b) or 0x201e.
584 __ subl(rax, Immediate(0x2028 - 0x0b));
585 __ cmpl(rax, Immediate(0x2029 - 0x2028));
586 BranchOrBacktrack(above, on_no_match);
592 if (mode_ != LATIN1) {
593 // Table is 256 entries, so all Latin1 characters can be tested.
594 __ cmpl(current_character(), Immediate('z'));
595 BranchOrBacktrack(above, on_no_match);
597 __ Move(rbx, ExternalReference::re_word_character_map());
598 DCHECK_EQ(0, word_character_map[0]); // Character '\0' is not a word char.
599 __ testb(Operand(rbx, current_character(), times_1, 0),
600 current_character());
601 BranchOrBacktrack(zero, on_no_match);
606 if (mode_ != LATIN1) {
607 // Table is 256 entries, so all Latin1 characters can be tested.
608 __ cmpl(current_character(), Immediate('z'));
611 __ Move(rbx, ExternalReference::re_word_character_map());
612 DCHECK_EQ(0, word_character_map[0]); // Character '\0' is not a word char.
613 __ testb(Operand(rbx, current_character(), times_1, 0),
614 current_character());
615 BranchOrBacktrack(not_zero, on_no_match);
616 if (mode_ != LATIN1) {
623 // Match any character.
625 // No custom implementation (yet): s(UC16), S(UC16).
632 void RegExpMacroAssemblerX64::Fail() {
633 STATIC_ASSERT(FAILURE == 0); // Return value for failure is zero.
635 __ Set(rax, FAILURE);
637 __ jmp(&exit_label_);
641 Handle<HeapObject> RegExpMacroAssemblerX64::GetCode(Handle<String> source) {
643 // Finalize code - write the entry point code now we know how many
644 // registers we need.
646 __ bind(&entry_label_);
648 // Tell the system that we have a stack frame. Because the type is MANUAL, no
650 FrameScope scope(&masm_, StackFrame::MANUAL);
652 // Actually emit code to start a new stack frame.
655 // Save parameters and callee-save registers. Order here should correspond
656 // to order of kBackup_ebx etc.
658 // MSVC passes arguments in rcx, rdx, r8, r9, with backing stack slots.
659 // Store register parameters in pre-allocated stack slots,
660 __ movq(Operand(rbp, kInputString), rcx);
661 __ movq(Operand(rbp, kStartIndex), rdx); // Passed as int32 in edx.
662 __ movq(Operand(rbp, kInputStart), r8);
663 __ movq(Operand(rbp, kInputEnd), r9);
664 // Callee-save on Win64.
669 // GCC passes arguments in rdi, rsi, rdx, rcx, r8, r9 (and then on stack).
670 // Push register parameters on stack for reference.
671 DCHECK_EQ(kInputString, -1 * kRegisterSize);
672 DCHECK_EQ(kStartIndex, -2 * kRegisterSize);
673 DCHECK_EQ(kInputStart, -3 * kRegisterSize);
674 DCHECK_EQ(kInputEnd, -4 * kRegisterSize);
675 DCHECK_EQ(kRegisterOutput, -5 * kRegisterSize);
676 DCHECK_EQ(kNumOutputRegisters, -6 * kRegisterSize);
684 __ pushq(rbx); // Callee-save
687 __ Push(Immediate(0)); // Number of successful matches in a global regexp.
688 __ Push(Immediate(0)); // Make room for "input start - 1" constant.
690 // Check if we have space on the stack for registers.
691 Label stack_limit_hit;
694 ExternalReference stack_limit =
695 ExternalReference::address_of_stack_limit(isolate());
697 __ Move(kScratchRegister, stack_limit);
698 __ subp(rcx, Operand(kScratchRegister, 0));
699 // Handle it if the stack pointer is already below the stack limit.
700 __ j(below_equal, &stack_limit_hit);
701 // Check if there is room for the variable number of registers above
703 __ cmpp(rcx, Immediate(num_registers_ * kPointerSize));
704 __ j(above_equal, &stack_ok);
705 // Exit with OutOfMemory exception. There is not enough space on the stack
706 // for our working registers.
707 __ Set(rax, EXCEPTION);
710 __ bind(&stack_limit_hit);
711 __ Move(code_object_pointer(), masm_.CodeObject());
712 CallCheckStackGuardState(); // Preserves no registers beside rbp and rsp.
714 // If returned value is non-zero, we exit with the returned value as result.
715 __ j(not_zero, &return_rax);
719 // Allocate space on stack for registers.
720 __ subp(rsp, Immediate(num_registers_ * kPointerSize));
721 // Load string length.
722 __ movp(rsi, Operand(rbp, kInputEnd));
723 // Load input position.
724 __ movp(rdi, Operand(rbp, kInputStart));
725 // Set up rdi to be negative offset from string end.
727 // Set rax to address of char before start of the string
728 // (effectively string position -1).
729 __ movp(rbx, Operand(rbp, kStartIndex));
732 __ leap(rax, Operand(rdi, rbx, times_2, -char_size()));
734 __ leap(rax, Operand(rdi, rbx, times_1, -char_size()));
736 // Store this value in a local variable, for use when clearing
737 // position registers.
738 __ movp(Operand(rbp, kInputStartMinusOne), rax);
741 // Ensure that we have written to each stack page, in order. Skipping a page
742 // on Windows can cause segmentation faults. Assuming page size is 4k.
743 const int kPageSize = 4096;
744 const int kRegistersPerPage = kPageSize / kPointerSize;
745 for (int i = num_saved_registers_ + kRegistersPerPage - 1;
747 i += kRegistersPerPage) {
748 __ movp(register_location(i), rax); // One write every page.
752 // Initialize code object pointer.
753 __ Move(code_object_pointer(), masm_.CodeObject());
755 Label load_char_start_regexp, start_regexp;
756 // Load newline if index is at start, previous character otherwise.
757 __ cmpl(Operand(rbp, kStartIndex), Immediate(0));
758 __ j(not_equal, &load_char_start_regexp, Label::kNear);
759 __ Set(current_character(), '\n');
760 __ jmp(&start_regexp, Label::kNear);
762 // Global regexp restarts matching here.
763 __ bind(&load_char_start_regexp);
764 // Load previous char as initial value of current character register.
765 LoadCurrentCharacterUnchecked(-1, 1);
766 __ bind(&start_regexp);
768 // Initialize on-stack registers.
769 if (num_saved_registers_ > 0) {
770 // Fill saved registers with initial value = start offset - 1
771 // Fill in stack push order, to avoid accessing across an unwritten
772 // page (a problem on Windows).
773 if (num_saved_registers_ > 8) {
774 __ Set(rcx, kRegisterZero);
777 __ movp(Operand(rbp, rcx, times_1, 0), rax);
778 __ subq(rcx, Immediate(kPointerSize));
780 Immediate(kRegisterZero - num_saved_registers_ * kPointerSize));
781 __ j(greater, &init_loop);
782 } else { // Unroll the loop.
783 for (int i = 0; i < num_saved_registers_; i++) {
784 __ movp(register_location(i), rax);
789 // Initialize backtrack stack pointer.
790 __ movp(backtrack_stackpointer(), Operand(rbp, kStackHighEnd));
792 __ jmp(&start_label_);
795 if (success_label_.is_linked()) {
796 // Save captures when successful.
797 __ bind(&success_label_);
798 if (num_saved_registers_ > 0) {
799 // copy captures to output
800 __ movp(rdx, Operand(rbp, kStartIndex));
801 __ movp(rbx, Operand(rbp, kRegisterOutput));
802 __ movp(rcx, Operand(rbp, kInputEnd));
803 __ subp(rcx, Operand(rbp, kInputStart));
805 __ leap(rcx, Operand(rcx, rdx, times_2, 0));
809 for (int i = 0; i < num_saved_registers_; i++) {
810 __ movp(rax, register_location(i));
811 if (i == 0 && global_with_zero_length_check()) {
812 // Keep capture start in rdx for the zero-length check later.
815 __ addp(rax, rcx); // Convert to index from start, not end.
817 __ sarp(rax, Immediate(1)); // Convert byte index to character index.
819 __ movl(Operand(rbx, i * kIntSize), rax);
824 // Restart matching if the regular expression is flagged as global.
825 // Increment success counter.
826 __ incp(Operand(rbp, kSuccessfulCaptures));
827 // Capture results have been stored, so the number of remaining global
828 // output registers is reduced by the number of stored captures.
829 __ movsxlq(rcx, Operand(rbp, kNumOutputRegisters));
830 __ subp(rcx, Immediate(num_saved_registers_));
831 // Check whether we have enough room for another set of capture results.
832 __ cmpp(rcx, Immediate(num_saved_registers_));
833 __ j(less, &exit_label_);
835 __ movp(Operand(rbp, kNumOutputRegisters), rcx);
836 // Advance the location for output.
837 __ addp(Operand(rbp, kRegisterOutput),
838 Immediate(num_saved_registers_ * kIntSize));
840 // Prepare rax to initialize registers with its value in the next run.
841 __ movp(rax, Operand(rbp, kInputStartMinusOne));
843 if (global_with_zero_length_check()) {
844 // Special case for zero-length matches.
845 // rdx: capture start index
847 // Not a zero-length match, restart.
848 __ j(not_equal, &load_char_start_regexp);
849 // rdi (offset from the end) is zero if we already reached the end.
851 __ j(zero, &exit_label_, Label::kNear);
852 // Advance current position after a zero-length match.
854 __ addq(rdi, Immediate(2));
860 __ jmp(&load_char_start_regexp);
862 __ movp(rax, Immediate(SUCCESS));
866 __ bind(&exit_label_);
868 // Return the number of successful captures.
869 __ movp(rax, Operand(rbp, kSuccessfulCaptures));
872 __ bind(&return_rax);
874 // Restore callee save registers.
875 __ leap(rsp, Operand(rbp, kLastCalleeSaveRegister));
881 // Restore callee save register.
882 __ movp(rbx, Operand(rbp, kBackup_rbx));
886 // Exit function frame, restore previous one.
890 // Backtrack code (branch target for conditional backtracks).
891 if (backtrack_label_.is_linked()) {
892 __ bind(&backtrack_label_);
896 Label exit_with_exception;
899 if (check_preempt_label_.is_linked()) {
900 SafeCallTarget(&check_preempt_label_);
902 __ pushq(backtrack_stackpointer());
905 CallCheckStackGuardState();
907 // If returning non-zero, we should end execution with the given
908 // result as return value.
909 __ j(not_zero, &return_rax);
911 // Restore registers.
912 __ Move(code_object_pointer(), masm_.CodeObject());
914 __ popq(backtrack_stackpointer());
915 // String might have moved: Reload esi from frame.
916 __ movp(rsi, Operand(rbp, kInputEnd));
920 // Backtrack stack overflow code.
921 if (stack_overflow_label_.is_linked()) {
922 SafeCallTarget(&stack_overflow_label_);
923 // Reached if the backtrack-stack limit has been hit.
926 // Save registers before calling C function
928 // Callee-save in Microsoft 64-bit ABI, but not in AMD64 ABI.
933 // Call GrowStack(backtrack_stackpointer())
934 static const int num_arguments = 3;
935 __ PrepareCallCFunction(num_arguments);
937 // Microsoft passes parameters in rcx, rdx, r8.
938 // First argument, backtrack stackpointer, is already in rcx.
939 __ leap(rdx, Operand(rbp, kStackHighEnd)); // Second argument
940 __ LoadAddress(r8, ExternalReference::isolate_address(isolate()));
942 // AMD64 ABI passes parameters in rdi, rsi, rdx.
943 __ movp(rdi, backtrack_stackpointer()); // First argument.
944 __ leap(rsi, Operand(rbp, kStackHighEnd)); // Second argument.
945 __ LoadAddress(rdx, ExternalReference::isolate_address(isolate()));
947 ExternalReference grow_stack =
948 ExternalReference::re_grow_stack(isolate());
949 __ CallCFunction(grow_stack, num_arguments);
950 // If return NULL, we have failed to grow the stack, and
951 // must exit with a stack-overflow exception.
953 __ j(equal, &exit_with_exception);
954 // Otherwise use return value as new stack pointer.
955 __ movp(backtrack_stackpointer(), rax);
956 // Restore saved registers and continue.
957 __ Move(code_object_pointer(), masm_.CodeObject());
965 if (exit_with_exception.is_linked()) {
966 // If any of the code above needed to exit with an exception.
967 __ bind(&exit_with_exception);
968 // Exit with Result EXCEPTION(-1) to signal thrown exception.
969 __ Set(rax, EXCEPTION);
973 FixupCodeRelativePositions();
976 masm_.GetCode(&code_desc);
977 Isolate* isolate = this->isolate();
978 Handle<Code> code = isolate->factory()->NewCode(
979 code_desc, Code::ComputeFlags(Code::REGEXP),
981 PROFILE(isolate, RegExpCodeCreateEvent(*code, *source));
982 return Handle<HeapObject>::cast(code);
986 void RegExpMacroAssemblerX64::GoTo(Label* to) {
987 BranchOrBacktrack(no_condition, to);
991 void RegExpMacroAssemblerX64::IfRegisterGE(int reg,
994 __ cmpp(register_location(reg), Immediate(comparand));
995 BranchOrBacktrack(greater_equal, if_ge);
999 void RegExpMacroAssemblerX64::IfRegisterLT(int reg,
1002 __ cmpp(register_location(reg), Immediate(comparand));
1003 BranchOrBacktrack(less, if_lt);
1007 void RegExpMacroAssemblerX64::IfRegisterEqPos(int reg,
1009 __ cmpp(rdi, register_location(reg));
1010 BranchOrBacktrack(equal, if_eq);
1014 RegExpMacroAssembler::IrregexpImplementation
1015 RegExpMacroAssemblerX64::Implementation() {
1016 return kX64Implementation;
1020 void RegExpMacroAssemblerX64::LoadCurrentCharacter(int cp_offset,
1021 Label* on_end_of_input,
1024 DCHECK(cp_offset >= -1); // ^ and \b can look behind one character.
1025 DCHECK(cp_offset < (1<<30)); // Be sane! (And ensure negation works)
1027 CheckPosition(cp_offset + characters - 1, on_end_of_input);
1029 LoadCurrentCharacterUnchecked(cp_offset, characters);
1033 void RegExpMacroAssemblerX64::PopCurrentPosition() {
1038 void RegExpMacroAssemblerX64::PopRegister(int register_index) {
1040 __ movp(register_location(register_index), rax);
1044 void RegExpMacroAssemblerX64::PushBacktrack(Label* label) {
1050 void RegExpMacroAssemblerX64::PushCurrentPosition() {
1055 void RegExpMacroAssemblerX64::PushRegister(int register_index,
1056 StackCheckFlag check_stack_limit) {
1057 __ movp(rax, register_location(register_index));
1059 if (check_stack_limit) CheckStackLimit();
1063 STATIC_ASSERT(kPointerSize == kInt64Size || kPointerSize == kInt32Size);
1066 void RegExpMacroAssemblerX64::ReadCurrentPositionFromRegister(int reg) {
1067 if (kPointerSize == kInt64Size) {
1068 __ movq(rdi, register_location(reg));
1070 // Need sign extension for x32 as rdi might be used as an index register.
1071 __ movsxlq(rdi, register_location(reg));
1076 void RegExpMacroAssemblerX64::ReadPositionFromRegister(Register dst, int reg) {
1077 if (kPointerSize == kInt64Size) {
1078 __ movq(dst, register_location(reg));
1080 // Need sign extension for x32 as dst might be used as an index register.
1081 __ movsxlq(dst, register_location(reg));
1086 void RegExpMacroAssemblerX64::ReadStackPointerFromRegister(int reg) {
1087 __ movp(backtrack_stackpointer(), register_location(reg));
1088 __ addp(backtrack_stackpointer(), Operand(rbp, kStackHighEnd));
1092 void RegExpMacroAssemblerX64::SetCurrentPositionFromEnd(int by) {
1093 Label after_position;
1094 __ cmpp(rdi, Immediate(-by * char_size()));
1095 __ j(greater_equal, &after_position, Label::kNear);
1096 __ movq(rdi, Immediate(-by * char_size()));
1097 // On RegExp code entry (where this operation is used), the character before
1098 // the current position is expected to be already loaded.
1099 // We have advanced the position, so it's safe to read backwards.
1100 LoadCurrentCharacterUnchecked(-1, 1);
1101 __ bind(&after_position);
1105 void RegExpMacroAssemblerX64::SetRegister(int register_index, int to) {
1106 DCHECK(register_index >= num_saved_registers_); // Reserved for positions!
1107 __ movp(register_location(register_index), Immediate(to));
1111 bool RegExpMacroAssemblerX64::Succeed() {
1112 __ jmp(&success_label_);
1117 void RegExpMacroAssemblerX64::WriteCurrentPositionToRegister(int reg,
1119 if (cp_offset == 0) {
1120 __ movp(register_location(reg), rdi);
1122 __ leap(rax, Operand(rdi, cp_offset * char_size()));
1123 __ movp(register_location(reg), rax);
1128 void RegExpMacroAssemblerX64::ClearRegisters(int reg_from, int reg_to) {
1129 DCHECK(reg_from <= reg_to);
1130 __ movp(rax, Operand(rbp, kInputStartMinusOne));
1131 for (int reg = reg_from; reg <= reg_to; reg++) {
1132 __ movp(register_location(reg), rax);
1137 void RegExpMacroAssemblerX64::WriteStackPointerToRegister(int reg) {
1138 __ movp(rax, backtrack_stackpointer());
1139 __ subp(rax, Operand(rbp, kStackHighEnd));
1140 __ movp(register_location(reg), rax);
1146 void RegExpMacroAssemblerX64::CallCheckStackGuardState() {
1147 // This function call preserves no register values. Caller should
1148 // store anything volatile in a C call or overwritten by this function.
1149 static const int num_arguments = 3;
1150 __ PrepareCallCFunction(num_arguments);
1152 // Second argument: Code* of self. (Do this before overwriting r8).
1153 __ movp(rdx, code_object_pointer());
1154 // Third argument: RegExp code frame pointer.
1156 // First argument: Next address on the stack (will be address of
1158 __ leap(rcx, Operand(rsp, -kPointerSize));
1160 // Third argument: RegExp code frame pointer.
1162 // Second argument: Code* of self.
1163 __ movp(rsi, code_object_pointer());
1164 // First argument: Next address on the stack (will be address of
1166 __ leap(rdi, Operand(rsp, -kRegisterSize));
1168 ExternalReference stack_check =
1169 ExternalReference::re_check_stack_guard_state(isolate());
1170 __ CallCFunction(stack_check, num_arguments);
1174 // Helper function for reading a value out of a stack frame.
1175 template <typename T>
1176 static T& frame_entry(Address re_frame, int frame_offset) {
1177 return reinterpret_cast<T&>(Memory::int32_at(re_frame + frame_offset));
1181 int RegExpMacroAssemblerX64::CheckStackGuardState(Address* return_address,
1184 Isolate* isolate = frame_entry<Isolate*>(re_frame, kIsolate);
1185 StackLimitCheck check(isolate);
1186 if (check.JsHasOverflowed()) {
1187 isolate->StackOverflow();
1191 // If not real stack overflow the stack guard was used to interrupt
1192 // execution for another purpose.
1194 // If this is a direct call from JavaScript retry the RegExp forcing the call
1195 // through the runtime system. Currently the direct call cannot handle a GC.
1196 if (frame_entry<int>(re_frame, kDirectCall) == 1) {
1200 // Prepare for possible GC.
1201 HandleScope handles(isolate);
1202 Handle<Code> code_handle(re_code);
1204 Handle<String> subject(frame_entry<String*>(re_frame, kInputString));
1207 bool is_one_byte = subject->IsOneByteRepresentationUnderneath();
1209 DCHECK(re_code->instruction_start() <= *return_address);
1210 DCHECK(*return_address <=
1211 re_code->instruction_start() + re_code->instruction_size());
1213 Object* result = isolate->stack_guard()->HandleInterrupts();
1215 if (*code_handle != re_code) { // Return address no longer valid
1216 intptr_t delta = code_handle->address() - re_code->address();
1217 // Overwrite the return address on the stack.
1218 *return_address += delta;
1221 if (result->IsException()) {
1225 Handle<String> subject_tmp = subject;
1226 int slice_offset = 0;
1228 // Extract the underlying string and the slice offset.
1229 if (StringShape(*subject_tmp).IsCons()) {
1230 subject_tmp = Handle<String>(ConsString::cast(*subject_tmp)->first());
1231 } else if (StringShape(*subject_tmp).IsSliced()) {
1232 SlicedString* slice = SlicedString::cast(*subject_tmp);
1233 subject_tmp = Handle<String>(slice->parent());
1234 slice_offset = slice->offset();
1237 // String might have changed.
1238 if (subject_tmp->IsOneByteRepresentation() != is_one_byte) {
1239 // If we changed between an Latin1 and an UC16 string, the specialized
1240 // code cannot be used, and we need to restart regexp matching from
1241 // scratch (including, potentially, compiling a new version of the code).
1245 // Otherwise, the content of the string might have moved. It must still
1246 // be a sequential or external string with the same content.
1247 // Update the start and end pointers in the stack frame to the current
1248 // location (whether it has actually moved or not).
1249 DCHECK(StringShape(*subject_tmp).IsSequential() ||
1250 StringShape(*subject_tmp).IsExternal());
1252 // The original start address of the characters to match.
1253 const byte* start_address = frame_entry<const byte*>(re_frame, kInputStart);
1255 // Find the current start address of the same character at the current string
1257 int start_index = frame_entry<int>(re_frame, kStartIndex);
1258 const byte* new_address = StringCharacterPosition(*subject_tmp,
1259 start_index + slice_offset);
1261 if (start_address != new_address) {
1262 // If there is a difference, update the object pointer and start and end
1263 // addresses in the RegExp stack frame to match the new value.
1264 const byte* end_address = frame_entry<const byte* >(re_frame, kInputEnd);
1265 int byte_length = static_cast<int>(end_address - start_address);
1266 frame_entry<const String*>(re_frame, kInputString) = *subject;
1267 frame_entry<const byte*>(re_frame, kInputStart) = new_address;
1268 frame_entry<const byte*>(re_frame, kInputEnd) = new_address + byte_length;
1269 } else if (frame_entry<const String*>(re_frame, kInputString) != *subject) {
1270 // Subject string might have been a ConsString that underwent
1271 // short-circuiting during GC. That will not change start_address but
1272 // will change pointer inside the subject handle.
1273 frame_entry<const String*>(re_frame, kInputString) = *subject;
1280 Operand RegExpMacroAssemblerX64::register_location(int register_index) {
1281 DCHECK(register_index < (1<<30));
1282 if (num_registers_ <= register_index) {
1283 num_registers_ = register_index + 1;
1285 return Operand(rbp, kRegisterZero - register_index * kPointerSize);
1289 void RegExpMacroAssemblerX64::CheckPosition(int cp_offset,
1290 Label* on_outside_input) {
1291 __ cmpl(rdi, Immediate(-cp_offset * char_size()));
1292 BranchOrBacktrack(greater_equal, on_outside_input);
1296 void RegExpMacroAssemblerX64::BranchOrBacktrack(Condition condition,
1298 if (condition < 0) { // No condition
1307 __ j(condition, &backtrack_label_);
1310 __ j(condition, to);
1314 void RegExpMacroAssemblerX64::SafeCall(Label* to) {
1319 void RegExpMacroAssemblerX64::SafeCallTarget(Label* label) {
1321 __ subp(Operand(rsp, 0), code_object_pointer());
1325 void RegExpMacroAssemblerX64::SafeReturn() {
1326 __ addp(Operand(rsp, 0), code_object_pointer());
1331 void RegExpMacroAssemblerX64::Push(Register source) {
1332 DCHECK(!source.is(backtrack_stackpointer()));
1333 // Notice: This updates flags, unlike normal Push.
1334 __ subp(backtrack_stackpointer(), Immediate(kIntSize));
1335 __ movl(Operand(backtrack_stackpointer(), 0), source);
1339 void RegExpMacroAssemblerX64::Push(Immediate value) {
1340 // Notice: This updates flags, unlike normal Push.
1341 __ subp(backtrack_stackpointer(), Immediate(kIntSize));
1342 __ movl(Operand(backtrack_stackpointer(), 0), value);
1346 void RegExpMacroAssemblerX64::FixupCodeRelativePositions() {
1347 for (int i = 0, n = code_relative_fixup_positions_.length(); i < n; i++) {
1348 int position = code_relative_fixup_positions_[i];
1349 // The position succeeds a relative label offset from position.
1350 // Patch the relative offset to be relative to the Code object pointer
1352 int patch_position = position - kIntSize;
1353 int offset = masm_.long_at(patch_position);
1354 masm_.long_at_put(patch_position,
1360 code_relative_fixup_positions_.Clear();
1364 void RegExpMacroAssemblerX64::Push(Label* backtrack_target) {
1365 __ subp(backtrack_stackpointer(), Immediate(kIntSize));
1366 __ movl(Operand(backtrack_stackpointer(), 0), backtrack_target);
1367 MarkPositionForCodeRelativeFixup();
1371 void RegExpMacroAssemblerX64::Pop(Register target) {
1372 DCHECK(!target.is(backtrack_stackpointer()));
1373 __ movsxlq(target, Operand(backtrack_stackpointer(), 0));
1374 // Notice: This updates flags, unlike normal Pop.
1375 __ addp(backtrack_stackpointer(), Immediate(kIntSize));
1379 void RegExpMacroAssemblerX64::Drop() {
1380 __ addp(backtrack_stackpointer(), Immediate(kIntSize));
1384 void RegExpMacroAssemblerX64::CheckPreemption() {
1385 // Check for preemption.
1387 ExternalReference stack_limit =
1388 ExternalReference::address_of_stack_limit(isolate());
1389 __ load_rax(stack_limit);
1391 __ j(above, &no_preempt);
1393 SafeCall(&check_preempt_label_);
1395 __ bind(&no_preempt);
1399 void RegExpMacroAssemblerX64::CheckStackLimit() {
1400 Label no_stack_overflow;
1401 ExternalReference stack_limit =
1402 ExternalReference::address_of_regexp_stack_limit(isolate());
1403 __ load_rax(stack_limit);
1404 __ cmpp(backtrack_stackpointer(), rax);
1405 __ j(above, &no_stack_overflow);
1407 SafeCall(&stack_overflow_label_);
1409 __ bind(&no_stack_overflow);
1413 void RegExpMacroAssemblerX64::LoadCurrentCharacterUnchecked(int cp_offset,
1415 if (mode_ == LATIN1) {
1416 if (characters == 4) {
1417 __ movl(current_character(), Operand(rsi, rdi, times_1, cp_offset));
1418 } else if (characters == 2) {
1419 __ movzxwl(current_character(), Operand(rsi, rdi, times_1, cp_offset));
1421 DCHECK(characters == 1);
1422 __ movzxbl(current_character(), Operand(rsi, rdi, times_1, cp_offset));
1425 DCHECK(mode_ == UC16);
1426 if (characters == 2) {
1427 __ movl(current_character(),
1428 Operand(rsi, rdi, times_1, cp_offset * sizeof(uc16)));
1430 DCHECK(characters == 1);
1431 __ movzxwl(current_character(),
1432 Operand(rsi, rdi, times_1, cp_offset * sizeof(uc16)));
1439 #endif // V8_INTERPRETED_REGEXP
1441 }} // namespace v8::internal
1443 #endif // V8_TARGET_ARCH_X64