Line data Source code
1 : // Copyright 2017 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/builtins/builtins-string-gen.h"
6 :
7 : #include "src/builtins/builtins-regexp-gen.h"
8 : #include "src/builtins/builtins-utils-gen.h"
9 : #include "src/builtins/builtins.h"
10 : #include "src/code-factory.h"
11 : #include "src/heap/factory-inl.h"
12 : #include "src/objects.h"
13 : #include "src/objects/property-cell.h"
14 :
15 : namespace v8 {
16 : namespace internal {
17 :
18 : typedef compiler::Node Node;
19 : template <class T>
20 : using TNode = compiler::TNode<T>;
21 :
22 1344 : Node* StringBuiltinsAssembler::DirectStringData(Node* string,
23 : Node* string_instance_type) {
24 : // Compute the effective offset of the first character.
25 1344 : VARIABLE(var_data, MachineType::PointerRepresentation());
26 1344 : Label if_sequential(this), if_external(this), if_join(this);
27 : Branch(Word32Equal(Word32And(string_instance_type,
28 2688 : Int32Constant(kStringRepresentationMask)),
29 5376 : Int32Constant(kSeqStringTag)),
30 2688 : &if_sequential, &if_external);
31 :
32 1344 : BIND(&if_sequential);
33 : {
34 : var_data.Bind(IntPtrAdd(
35 : IntPtrConstant(SeqOneByteString::kHeaderSize - kHeapObjectTag),
36 2688 : BitcastTaggedToWord(string)));
37 1344 : Goto(&if_join);
38 : }
39 :
40 1344 : BIND(&if_external);
41 : {
42 : // This is only valid for ExternalStrings where the resource data
43 : // pointer is cached (i.e. no uncached external strings).
44 : CSA_ASSERT(this, Word32NotEqual(
45 : Word32And(string_instance_type,
46 : Int32Constant(kUncachedExternalStringMask)),
47 : Int32Constant(kUncachedExternalStringTag)));
48 : var_data.Bind(LoadObjectField(string, ExternalString::kResourceDataOffset,
49 1344 : MachineType::Pointer()));
50 1344 : Goto(&if_join);
51 : }
52 :
53 1344 : BIND(&if_join);
54 2688 : return var_data.value();
55 : }
56 :
57 168 : void StringBuiltinsAssembler::DispatchOnStringEncodings(
58 : Node* const lhs_instance_type, Node* const rhs_instance_type,
59 : Label* if_one_one, Label* if_one_two, Label* if_two_one,
60 : Label* if_two_two) {
61 : STATIC_ASSERT(kStringEncodingMask == 0x8);
62 : STATIC_ASSERT(kTwoByteStringTag == 0x0);
63 : STATIC_ASSERT(kOneByteStringTag == 0x8);
64 :
65 : // First combine the encodings.
66 :
67 336 : Node* const encoding_mask = Int32Constant(kStringEncodingMask);
68 336 : Node* const lhs_encoding = Word32And(lhs_instance_type, encoding_mask);
69 336 : Node* const rhs_encoding = Word32And(rhs_instance_type, encoding_mask);
70 :
71 : Node* const combined_encodings =
72 504 : Word32Or(lhs_encoding, Word32Shr(rhs_encoding, 1));
73 :
74 : // Then dispatch on the combined encoding.
75 :
76 : Label unreachable(this, Label::kDeferred);
77 :
78 : int32_t values[] = {
79 : kOneByteStringTag | (kOneByteStringTag >> 1),
80 : kOneByteStringTag | (kTwoByteStringTag >> 1),
81 : kTwoByteStringTag | (kOneByteStringTag >> 1),
82 : kTwoByteStringTag | (kTwoByteStringTag >> 1),
83 168 : };
84 : Label* labels[] = {
85 : if_one_one, if_one_two, if_two_one, if_two_two,
86 168 : };
87 :
88 : STATIC_ASSERT(arraysize(values) == arraysize(labels));
89 168 : Switch(combined_encodings, &unreachable, values, labels, arraysize(values));
90 :
91 168 : BIND(&unreachable);
92 168 : Unreachable();
93 168 : }
94 :
95 : template <typename SubjectChar, typename PatternChar>
96 672 : Node* StringBuiltinsAssembler::CallSearchStringRaw(Node* const subject_ptr,
97 : Node* const subject_length,
98 : Node* const search_ptr,
99 : Node* const search_length,
100 : Node* const start_position) {
101 : Node* const function_addr = ExternalConstant(
102 1344 : ExternalReference::search_string_raw<SubjectChar, PatternChar>());
103 : Node* const isolate_ptr =
104 1344 : ExternalConstant(ExternalReference::isolate_address(isolate()));
105 :
106 672 : MachineType type_ptr = MachineType::Pointer();
107 672 : MachineType type_intptr = MachineType::IntPtr();
108 :
109 : Node* const result = CallCFunction6(
110 : type_intptr, type_ptr, type_ptr, type_intptr, type_ptr, type_intptr,
111 : type_intptr, function_addr, isolate_ptr, subject_ptr, subject_length,
112 672 : search_ptr, search_length, start_position);
113 :
114 672 : return result;
115 : }
116 :
117 1344 : Node* StringBuiltinsAssembler::PointerToStringDataAtIndex(
118 : Node* const string_data, Node* const index, String::Encoding encoding) {
119 : const ElementsKind kind = (encoding == String::ONE_BYTE_ENCODING)
120 : ? UINT8_ELEMENTS
121 1344 : : UINT16_ELEMENTS;
122 : Node* const offset_in_bytes =
123 2688 : ElementOffsetFromIndex(index, kind, INTPTR_PARAMETERS);
124 2688 : return IntPtrAdd(string_data, offset_in_bytes);
125 : }
126 :
127 56 : void StringBuiltinsAssembler::GenerateStringEqual(Node* context, Node* left,
128 : Node* right) {
129 56 : VARIABLE(var_left, MachineRepresentation::kTagged, left);
130 112 : VARIABLE(var_right, MachineRepresentation::kTagged, right);
131 56 : Label if_equal(this), if_notequal(this), if_indirect(this, Label::kDeferred),
132 168 : restart(this, {&var_left, &var_right});
133 :
134 56 : TNode<IntPtrT> lhs_length = LoadStringLengthAsWord(left);
135 56 : TNode<IntPtrT> rhs_length = LoadStringLengthAsWord(right);
136 :
137 : // Strings with different lengths cannot be equal.
138 112 : GotoIf(WordNotEqual(lhs_length, rhs_length), &if_notequal);
139 :
140 56 : Goto(&restart);
141 56 : BIND(&restart);
142 56 : Node* lhs = var_left.value();
143 56 : Node* rhs = var_right.value();
144 :
145 112 : Node* lhs_instance_type = LoadInstanceType(lhs);
146 112 : Node* rhs_instance_type = LoadInstanceType(rhs);
147 :
148 : StringEqual_Core(context, lhs, lhs_instance_type, rhs, rhs_instance_type,
149 56 : lhs_length, &if_equal, &if_notequal, &if_indirect);
150 :
151 56 : BIND(&if_indirect);
152 : {
153 : // Try to unwrap indirect strings, restart the above attempt on success.
154 : MaybeDerefIndirectStrings(&var_left, lhs_instance_type, &var_right,
155 56 : rhs_instance_type, &restart);
156 :
157 56 : TailCallRuntime(Runtime::kStringEqual, context, lhs, rhs);
158 : }
159 :
160 56 : BIND(&if_equal);
161 112 : Return(TrueConstant());
162 :
163 56 : BIND(&if_notequal);
164 168 : Return(FalseConstant());
165 56 : }
166 :
167 168 : void StringBuiltinsAssembler::StringEqual_Core(
168 : Node* context, Node* lhs, Node* lhs_instance_type, Node* rhs,
169 : Node* rhs_instance_type, TNode<IntPtrT> length, Label* if_equal,
170 : Label* if_not_equal, Label* if_indirect) {
171 : CSA_ASSERT(this, IsString(lhs));
172 : CSA_ASSERT(this, IsString(rhs));
173 : CSA_ASSERT(this, WordEqual(LoadStringLengthAsWord(lhs), length));
174 : CSA_ASSERT(this, WordEqual(LoadStringLengthAsWord(rhs), length));
175 : // Fast check to see if {lhs} and {rhs} refer to the same String object.
176 336 : GotoIf(WordEqual(lhs, rhs), if_equal);
177 :
178 : // Combine the instance types into a single 16-bit value, so we can check
179 : // both of them at once.
180 : Node* both_instance_types = Word32Or(
181 672 : lhs_instance_type, Word32Shl(rhs_instance_type, Int32Constant(8)));
182 :
183 : // Check if both {lhs} and {rhs} are internalized. Since we already know
184 : // that they're not the same object, they're not equal in that case.
185 : int const kBothInternalizedMask =
186 : kIsNotInternalizedMask | (kIsNotInternalizedMask << 8);
187 : int const kBothInternalizedTag = kInternalizedTag | (kInternalizedTag << 8);
188 : GotoIf(Word32Equal(Word32And(both_instance_types,
189 336 : Int32Constant(kBothInternalizedMask)),
190 672 : Int32Constant(kBothInternalizedTag)),
191 336 : if_not_equal);
192 :
193 : // Check if both {lhs} and {rhs} are direct strings, and that in case of
194 : // ExternalStrings the data pointer is cached.
195 : STATIC_ASSERT(kUncachedExternalStringTag != 0);
196 : STATIC_ASSERT(kIsIndirectStringTag != 0);
197 : int const kBothDirectStringMask =
198 : kIsIndirectStringMask | kUncachedExternalStringMask |
199 : ((kIsIndirectStringMask | kUncachedExternalStringMask) << 8);
200 : GotoIfNot(Word32Equal(Word32And(both_instance_types,
201 336 : Int32Constant(kBothDirectStringMask)),
202 672 : Int32Constant(0)),
203 336 : if_indirect);
204 :
205 : // Dispatch based on the {lhs} and {rhs} string encoding.
206 : int const kBothStringEncodingMask =
207 : kStringEncodingMask | (kStringEncodingMask << 8);
208 : int const kOneOneByteStringTag = kOneByteStringTag | (kOneByteStringTag << 8);
209 : int const kTwoTwoByteStringTag = kTwoByteStringTag | (kTwoByteStringTag << 8);
210 : int const kOneTwoByteStringTag = kOneByteStringTag | (kTwoByteStringTag << 8);
211 168 : Label if_oneonebytestring(this), if_twotwobytestring(this),
212 168 : if_onetwobytestring(this), if_twoonebytestring(this);
213 : Node* masked_instance_types =
214 504 : Word32And(both_instance_types, Int32Constant(kBothStringEncodingMask));
215 : GotoIf(
216 336 : Word32Equal(masked_instance_types, Int32Constant(kOneOneByteStringTag)),
217 336 : &if_oneonebytestring);
218 : GotoIf(
219 336 : Word32Equal(masked_instance_types, Int32Constant(kTwoTwoByteStringTag)),
220 336 : &if_twotwobytestring);
221 : Branch(
222 336 : Word32Equal(masked_instance_types, Int32Constant(kOneTwoByteStringTag)),
223 336 : &if_onetwobytestring, &if_twoonebytestring);
224 :
225 168 : BIND(&if_oneonebytestring);
226 : StringEqual_Loop(lhs, lhs_instance_type, MachineType::Uint8(), rhs,
227 : rhs_instance_type, MachineType::Uint8(), length, if_equal,
228 168 : if_not_equal);
229 :
230 168 : BIND(&if_twotwobytestring);
231 : StringEqual_Loop(lhs, lhs_instance_type, MachineType::Uint16(), rhs,
232 : rhs_instance_type, MachineType::Uint16(), length, if_equal,
233 168 : if_not_equal);
234 :
235 168 : BIND(&if_onetwobytestring);
236 : StringEqual_Loop(lhs, lhs_instance_type, MachineType::Uint8(), rhs,
237 : rhs_instance_type, MachineType::Uint16(), length, if_equal,
238 168 : if_not_equal);
239 :
240 168 : BIND(&if_twoonebytestring);
241 : StringEqual_Loop(lhs, lhs_instance_type, MachineType::Uint16(), rhs,
242 : rhs_instance_type, MachineType::Uint8(), length, if_equal,
243 336 : if_not_equal);
244 168 : }
245 :
246 672 : void StringBuiltinsAssembler::StringEqual_Loop(
247 : Node* lhs, Node* lhs_instance_type, MachineType lhs_type, Node* rhs,
248 : Node* rhs_instance_type, MachineType rhs_type, TNode<IntPtrT> length,
249 : Label* if_equal, Label* if_not_equal) {
250 : CSA_ASSERT(this, IsString(lhs));
251 : CSA_ASSERT(this, IsString(rhs));
252 : CSA_ASSERT(this, WordEqual(LoadStringLengthAsWord(lhs), length));
253 : CSA_ASSERT(this, WordEqual(LoadStringLengthAsWord(rhs), length));
254 :
255 : // Compute the effective offset of the first character.
256 672 : Node* lhs_data = DirectStringData(lhs, lhs_instance_type);
257 672 : Node* rhs_data = DirectStringData(rhs, rhs_instance_type);
258 :
259 : // Loop over the {lhs} and {rhs} strings to see if they are equal.
260 672 : TVARIABLE(IntPtrT, var_offset, IntPtrConstant(0));
261 672 : Label loop(this, &var_offset);
262 672 : Goto(&loop);
263 672 : BIND(&loop);
264 : {
265 : // If {offset} equals {end}, no difference was found, so the
266 : // strings are equal.
267 1344 : GotoIf(WordEqual(var_offset.value(), length), if_equal);
268 :
269 : // Load the next characters from {lhs} and {rhs}.
270 : Node* lhs_value =
271 : Load(lhs_type, lhs_data,
272 : WordShl(var_offset.value(),
273 2016 : ElementSizeLog2Of(lhs_type.representation())));
274 : Node* rhs_value =
275 : Load(rhs_type, rhs_data,
276 : WordShl(var_offset.value(),
277 2016 : ElementSizeLog2Of(rhs_type.representation())));
278 :
279 : // Check if the characters match.
280 1344 : GotoIf(Word32NotEqual(lhs_value, rhs_value), if_not_equal);
281 :
282 : // Advance to next character.
283 672 : var_offset = IntPtrAdd(var_offset.value(), IntPtrConstant(1));
284 672 : Goto(&loop);
285 : }
286 672 : }
287 :
288 336 : TF_BUILTIN(StringAdd_CheckNone, StringBuiltinsAssembler) {
289 56 : TNode<String> left = CAST(Parameter(Descriptor::kLeft));
290 56 : TNode<String> right = CAST(Parameter(Descriptor::kRight));
291 : Node* context = Parameter(Descriptor::kContext);
292 112 : Return(StringAdd(context, left, right));
293 56 : }
294 :
295 280 : TF_BUILTIN(StringAdd_ConvertLeft, StringBuiltinsAssembler) {
296 : TNode<Object> left = CAST(Parameter(Descriptor::kLeft));
297 56 : TNode<String> right = CAST(Parameter(Descriptor::kRight));
298 : Node* context = Parameter(Descriptor::kContext);
299 : // TODO(danno): The ToString and JSReceiverToPrimitive below could be
300 : // combined to avoid duplicate smi and instance type checks.
301 168 : left = ToString(context, JSReceiverToPrimitive(context, left));
302 56 : TailCallBuiltin(Builtins::kStringAdd_CheckNone, context, left, right);
303 56 : }
304 :
305 280 : TF_BUILTIN(StringAdd_ConvertRight, StringBuiltinsAssembler) {
306 56 : TNode<String> left = CAST(Parameter(Descriptor::kLeft));
307 : TNode<Object> right = CAST(Parameter(Descriptor::kRight));
308 : Node* context = Parameter(Descriptor::kContext);
309 : // TODO(danno): The ToString and JSReceiverToPrimitive below could be
310 : // combined to avoid duplicate smi and instance type checks.
311 168 : right = ToString(context, JSReceiverToPrimitive(context, right));
312 56 : TailCallBuiltin(Builtins::kStringAdd_CheckNone, context, left, right);
313 56 : }
314 :
315 280 : TF_BUILTIN(SubString, StringBuiltinsAssembler) {
316 56 : TNode<String> string = CAST(Parameter(Descriptor::kString));
317 : TNode<Smi> from = CAST(Parameter(Descriptor::kFrom));
318 : TNode<Smi> to = CAST(Parameter(Descriptor::kTo));
319 168 : Return(SubString(string, SmiUntag(from), SmiUntag(to)));
320 56 : }
321 :
322 168 : void StringBuiltinsAssembler::GenerateStringAt(
323 : char const* method_name, TNode<Context> context, Node* receiver,
324 : TNode<Object> maybe_position, TNode<Object> default_return,
325 : const StringAtAccessor& accessor) {
326 : // Check that {receiver} is coercible to Object and convert it to a String.
327 168 : TNode<String> string = ToThisString(context, receiver, method_name);
328 :
329 : // Convert the {position} to a Smi and check that it's in bounds of the
330 : // {string}.
331 168 : Label if_outofbounds(this, Label::kDeferred);
332 : TNode<Number> position = ToInteger_Inline(
333 168 : context, maybe_position, CodeStubAssembler::kTruncateMinusZero);
334 336 : GotoIfNot(TaggedIsSmi(position), &if_outofbounds);
335 168 : TNode<IntPtrT> index = SmiUntag(CAST(position));
336 168 : TNode<IntPtrT> length = LoadStringLengthAsWord(string);
337 336 : GotoIfNot(UintPtrLessThan(index, length), &if_outofbounds);
338 168 : TNode<Object> result = accessor(string, length, index);
339 168 : Return(result);
340 :
341 168 : BIND(&if_outofbounds);
342 168 : Return(default_return);
343 168 : }
344 :
345 224 : void StringBuiltinsAssembler::GenerateStringRelationalComparison(Node* context,
346 : Node* left,
347 : Node* right,
348 : Operation op) {
349 224 : VARIABLE(var_left, MachineRepresentation::kTagged, left);
350 448 : VARIABLE(var_right, MachineRepresentation::kTagged, right);
351 :
352 224 : Variable* input_vars[2] = {&var_left, &var_right};
353 224 : Label if_less(this), if_equal(this), if_greater(this);
354 448 : Label restart(this, 2, input_vars);
355 224 : Goto(&restart);
356 224 : BIND(&restart);
357 :
358 224 : Node* lhs = var_left.value();
359 224 : Node* rhs = var_right.value();
360 : // Fast check to see if {lhs} and {rhs} refer to the same String object.
361 448 : GotoIf(WordEqual(lhs, rhs), &if_equal);
362 :
363 : // Load instance types of {lhs} and {rhs}.
364 448 : Node* lhs_instance_type = LoadInstanceType(lhs);
365 448 : Node* rhs_instance_type = LoadInstanceType(rhs);
366 :
367 : // Combine the instance types into a single 16-bit value, so we can check
368 : // both of them at once.
369 : Node* both_instance_types = Word32Or(
370 896 : lhs_instance_type, Word32Shl(rhs_instance_type, Int32Constant(8)));
371 :
372 : // Check that both {lhs} and {rhs} are flat one-byte strings.
373 : int const kBothSeqOneByteStringMask =
374 : kStringEncodingMask | kStringRepresentationMask |
375 : ((kStringEncodingMask | kStringRepresentationMask) << 8);
376 : int const kBothSeqOneByteStringTag =
377 : kOneByteStringTag | kSeqStringTag |
378 : ((kOneByteStringTag | kSeqStringTag) << 8);
379 224 : Label if_bothonebyteseqstrings(this), if_notbothonebyteseqstrings(this);
380 : Branch(Word32Equal(Word32And(both_instance_types,
381 448 : Int32Constant(kBothSeqOneByteStringMask)),
382 896 : Int32Constant(kBothSeqOneByteStringTag)),
383 448 : &if_bothonebyteseqstrings, &if_notbothonebyteseqstrings);
384 :
385 224 : BIND(&if_bothonebyteseqstrings);
386 : {
387 : // Load the length of {lhs} and {rhs}.
388 224 : TNode<IntPtrT> lhs_length = LoadStringLengthAsWord(lhs);
389 224 : TNode<IntPtrT> rhs_length = LoadStringLengthAsWord(rhs);
390 :
391 : // Determine the minimum length.
392 224 : TNode<IntPtrT> length = IntPtrMin(lhs_length, rhs_length);
393 :
394 : // Compute the effective offset of the first character.
395 : TNode<IntPtrT> begin =
396 224 : IntPtrConstant(SeqOneByteString::kHeaderSize - kHeapObjectTag);
397 :
398 : // Compute the first offset after the string from the length.
399 : TNode<IntPtrT> end = IntPtrAdd(begin, length);
400 :
401 : // Loop over the {lhs} and {rhs} strings to see if they are equal.
402 : TVARIABLE(IntPtrT, var_offset, begin);
403 224 : Label loop(this, &var_offset);
404 224 : Goto(&loop);
405 224 : BIND(&loop);
406 : {
407 : // Check if {offset} equals {end}.
408 224 : Label if_done(this), if_notdone(this);
409 448 : Branch(WordEqual(var_offset.value(), end), &if_done, &if_notdone);
410 :
411 224 : BIND(&if_notdone);
412 : {
413 : // Load the next characters from {lhs} and {rhs}.
414 224 : Node* lhs_value = Load(MachineType::Uint8(), lhs, var_offset.value());
415 224 : Node* rhs_value = Load(MachineType::Uint8(), rhs, var_offset.value());
416 :
417 : // Check if the characters match.
418 224 : Label if_valueissame(this), if_valueisnotsame(this);
419 224 : Branch(Word32Equal(lhs_value, rhs_value), &if_valueissame,
420 448 : &if_valueisnotsame);
421 :
422 224 : BIND(&if_valueissame);
423 : {
424 : // Advance to next character.
425 224 : var_offset = IntPtrAdd(var_offset.value(), IntPtrConstant(1));
426 : }
427 224 : Goto(&loop);
428 :
429 224 : BIND(&if_valueisnotsame);
430 672 : Branch(Uint32LessThan(lhs_value, rhs_value), &if_less, &if_greater);
431 : }
432 :
433 224 : BIND(&if_done);
434 : {
435 : // All characters up to the min length are equal, decide based on
436 : // string length.
437 448 : GotoIf(IntPtrEqual(lhs_length, rhs_length), &if_equal);
438 448 : Branch(IntPtrLessThan(lhs_length, rhs_length), &if_less, &if_greater);
439 224 : }
440 : }
441 : }
442 :
443 224 : BIND(&if_notbothonebyteseqstrings);
444 : {
445 : // Try to unwrap indirect strings, restart the above attempt on success.
446 : MaybeDerefIndirectStrings(&var_left, lhs_instance_type, &var_right,
447 224 : rhs_instance_type, &restart);
448 : // TODO(bmeurer): Add support for two byte string relational comparisons.
449 224 : switch (op) {
450 : case Operation::kLessThan:
451 56 : TailCallRuntime(Runtime::kStringLessThan, context, lhs, rhs);
452 56 : break;
453 : case Operation::kLessThanOrEqual:
454 56 : TailCallRuntime(Runtime::kStringLessThanOrEqual, context, lhs, rhs);
455 56 : break;
456 : case Operation::kGreaterThan:
457 56 : TailCallRuntime(Runtime::kStringGreaterThan, context, lhs, rhs);
458 56 : break;
459 : case Operation::kGreaterThanOrEqual:
460 56 : TailCallRuntime(Runtime::kStringGreaterThanOrEqual, context, lhs, rhs);
461 56 : break;
462 : default:
463 0 : UNREACHABLE();
464 : }
465 : }
466 :
467 224 : BIND(&if_less);
468 224 : switch (op) {
469 : case Operation::kLessThan:
470 : case Operation::kLessThanOrEqual:
471 224 : Return(TrueConstant());
472 112 : break;
473 :
474 : case Operation::kGreaterThan:
475 : case Operation::kGreaterThanOrEqual:
476 224 : Return(FalseConstant());
477 112 : break;
478 : default:
479 0 : UNREACHABLE();
480 : }
481 :
482 224 : BIND(&if_equal);
483 224 : switch (op) {
484 : case Operation::kLessThan:
485 : case Operation::kGreaterThan:
486 224 : Return(FalseConstant());
487 112 : break;
488 :
489 : case Operation::kLessThanOrEqual:
490 : case Operation::kGreaterThanOrEqual:
491 224 : Return(TrueConstant());
492 112 : break;
493 : default:
494 0 : UNREACHABLE();
495 : }
496 :
497 224 : BIND(&if_greater);
498 224 : switch (op) {
499 : case Operation::kLessThan:
500 : case Operation::kLessThanOrEqual:
501 224 : Return(FalseConstant());
502 112 : break;
503 :
504 : case Operation::kGreaterThan:
505 : case Operation::kGreaterThanOrEqual:
506 224 : Return(TrueConstant());
507 112 : break;
508 : default:
509 0 : UNREACHABLE();
510 224 : }
511 224 : }
512 :
513 224 : TF_BUILTIN(StringEqual, StringBuiltinsAssembler) {
514 : Node* context = Parameter(Descriptor::kContext);
515 : Node* left = Parameter(Descriptor::kLeft);
516 : Node* right = Parameter(Descriptor::kRight);
517 56 : GenerateStringEqual(context, left, right);
518 56 : }
519 :
520 224 : TF_BUILTIN(StringLessThan, StringBuiltinsAssembler) {
521 : Node* context = Parameter(Descriptor::kContext);
522 : Node* left = Parameter(Descriptor::kLeft);
523 : Node* right = Parameter(Descriptor::kRight);
524 : GenerateStringRelationalComparison(context, left, right,
525 56 : Operation::kLessThan);
526 56 : }
527 :
528 224 : TF_BUILTIN(StringLessThanOrEqual, StringBuiltinsAssembler) {
529 : Node* context = Parameter(Descriptor::kContext);
530 : Node* left = Parameter(Descriptor::kLeft);
531 : Node* right = Parameter(Descriptor::kRight);
532 : GenerateStringRelationalComparison(context, left, right,
533 56 : Operation::kLessThanOrEqual);
534 56 : }
535 :
536 224 : TF_BUILTIN(StringGreaterThan, StringBuiltinsAssembler) {
537 : Node* context = Parameter(Descriptor::kContext);
538 : Node* left = Parameter(Descriptor::kLeft);
539 : Node* right = Parameter(Descriptor::kRight);
540 : GenerateStringRelationalComparison(context, left, right,
541 56 : Operation::kGreaterThan);
542 56 : }
543 :
544 224 : TF_BUILTIN(StringGreaterThanOrEqual, StringBuiltinsAssembler) {
545 : Node* context = Parameter(Descriptor::kContext);
546 : Node* left = Parameter(Descriptor::kLeft);
547 : Node* right = Parameter(Descriptor::kRight);
548 : GenerateStringRelationalComparison(context, left, right,
549 56 : Operation::kGreaterThanOrEqual);
550 56 : }
551 :
552 224 : TF_BUILTIN(StringCharAt, StringBuiltinsAssembler) {
553 : TNode<String> receiver = CAST(Parameter(Descriptor::kReceiver));
554 : TNode<IntPtrT> position =
555 : UncheckedCast<IntPtrT>(Parameter(Descriptor::kPosition));
556 :
557 : // Load the character code at the {position} from the {receiver}.
558 56 : TNode<Int32T> code = StringCharCodeAt(receiver, position);
559 :
560 : // And return the single character string with only that {code}
561 56 : TNode<String> result = StringFromSingleCharCode(code);
562 56 : Return(result);
563 56 : }
564 :
565 224 : TF_BUILTIN(StringCodePointAtUTF16, StringBuiltinsAssembler) {
566 : Node* receiver = Parameter(Descriptor::kReceiver);
567 : Node* position = Parameter(Descriptor::kPosition);
568 : // TODO(sigurds) Figure out if passing length as argument pays off.
569 56 : TNode<IntPtrT> length = LoadStringLengthAsWord(receiver);
570 : // Load the character code at the {position} from the {receiver}.
571 : TNode<Int32T> code =
572 56 : LoadSurrogatePairAt(receiver, length, position, UnicodeEncoding::UTF16);
573 : // And return it as TaggedSigned value.
574 : // TODO(turbofan): Allow builtins to return values untagged.
575 56 : TNode<Smi> result = SmiFromInt32(code);
576 56 : Return(result);
577 56 : }
578 :
579 224 : TF_BUILTIN(StringCodePointAtUTF32, StringBuiltinsAssembler) {
580 : Node* receiver = Parameter(Descriptor::kReceiver);
581 : Node* position = Parameter(Descriptor::kPosition);
582 :
583 : // TODO(sigurds) Figure out if passing length as argument pays off.
584 56 : TNode<IntPtrT> length = LoadStringLengthAsWord(receiver);
585 : // Load the character code at the {position} from the {receiver}.
586 : TNode<Int32T> code =
587 56 : LoadSurrogatePairAt(receiver, length, position, UnicodeEncoding::UTF32);
588 : // And return it as TaggedSigned value.
589 : // TODO(turbofan): Allow builtins to return values untagged.
590 56 : TNode<Smi> result = SmiFromInt32(code);
591 56 : Return(result);
592 56 : }
593 :
594 : // -----------------------------------------------------------------------------
595 : // ES6 section 21.1 String Objects
596 :
597 : // ES6 #sec-string.fromcharcode
598 168 : TF_BUILTIN(StringFromCharCode, CodeStubAssembler) {
599 : // TODO(ishell): use constants from Descriptor once the JSFunction linkage
600 : // arguments are reordered.
601 : TNode<Int32T> argc =
602 : UncheckedCast<Int32T>(Parameter(Descriptor::kJSActualArgumentsCount));
603 : Node* context = Parameter(Descriptor::kContext);
604 :
605 168 : CodeStubArguments arguments(this, ChangeInt32ToIntPtr(argc));
606 : // Check if we have exactly one argument (plus the implicit receiver), i.e.
607 : // if the parent frame is not an arguments adaptor frame.
608 56 : Label if_oneargument(this), if_notoneargument(this);
609 112 : Branch(Word32Equal(argc, Int32Constant(1)), &if_oneargument,
610 112 : &if_notoneargument);
611 :
612 56 : BIND(&if_oneargument);
613 : {
614 : // Single argument case, perform fast single character string cache lookup
615 : // for one-byte code units, or fall back to creating a single character
616 : // string on the fly otherwise.
617 112 : Node* code = arguments.AtIndex(0);
618 56 : Node* code32 = TruncateTaggedToWord32(context, code);
619 : TNode<Int32T> code16 =
620 112 : Signed(Word32And(code32, Int32Constant(String::kMaxUtf16CodeUnit)));
621 112 : Node* result = StringFromSingleCharCode(code16);
622 56 : arguments.PopAndReturn(result);
623 : }
624 :
625 56 : Node* code16 = nullptr;
626 56 : BIND(&if_notoneargument);
627 : {
628 : Label two_byte(this);
629 : // Assume that the resulting string contains only one-byte characters.
630 112 : Node* one_byte_result = AllocateSeqOneByteString(context, Unsigned(argc));
631 :
632 : TVARIABLE(IntPtrT, var_max_index);
633 56 : var_max_index = IntPtrConstant(0);
634 :
635 : // Iterate over the incoming arguments, converting them to 8-bit character
636 : // codes. Stop if any of the conversions generates a code that doesn't fit
637 : // in 8 bits.
638 112 : CodeStubAssembler::VariableList vars({&var_max_index}, zone());
639 : arguments.ForEach(vars, [this, context, &two_byte, &var_max_index, &code16,
640 56 : one_byte_result](Node* arg) {
641 56 : Node* code32 = TruncateTaggedToWord32(context, arg);
642 168 : code16 = Word32And(code32, Int32Constant(String::kMaxUtf16CodeUnit));
643 :
644 : GotoIf(
645 224 : Int32GreaterThan(code16, Int32Constant(String::kMaxOneByteCharCode)),
646 168 : &two_byte);
647 :
648 : // The {code16} fits into the SeqOneByteString {one_byte_result}.
649 : Node* offset = ElementOffsetFromIndex(
650 56 : var_max_index.value(), UINT8_ELEMENTS,
651 : CodeStubAssembler::INTPTR_PARAMETERS,
652 112 : SeqOneByteString::kHeaderSize - kHeapObjectTag);
653 : StoreNoWriteBarrier(MachineRepresentation::kWord8, one_byte_result,
654 56 : offset, code16);
655 168 : var_max_index = IntPtrAdd(var_max_index.value(), IntPtrConstant(1));
656 168 : });
657 56 : arguments.PopAndReturn(one_byte_result);
658 :
659 56 : BIND(&two_byte);
660 :
661 : // At least one of the characters in the string requires a 16-bit
662 : // representation. Allocate a SeqTwoByteString to hold the resulting
663 : // string.
664 112 : Node* two_byte_result = AllocateSeqTwoByteString(context, Unsigned(argc));
665 :
666 : // Copy the characters that have already been put in the 8-bit string into
667 : // their corresponding positions in the new 16-bit string.
668 56 : TNode<IntPtrT> zero = IntPtrConstant(0);
669 : CopyStringCharacters(one_byte_result, two_byte_result, zero, zero,
670 : var_max_index.value(), String::ONE_BYTE_ENCODING,
671 56 : String::TWO_BYTE_ENCODING);
672 :
673 : // Write the character that caused the 8-bit to 16-bit fault.
674 : Node* max_index_offset =
675 : ElementOffsetFromIndex(var_max_index.value(), UINT16_ELEMENTS,
676 : CodeStubAssembler::INTPTR_PARAMETERS,
677 112 : SeqTwoByteString::kHeaderSize - kHeapObjectTag);
678 : StoreNoWriteBarrier(MachineRepresentation::kWord16, two_byte_result,
679 56 : max_index_offset, code16);
680 56 : var_max_index = IntPtrAdd(var_max_index.value(), IntPtrConstant(1));
681 :
682 : // Resume copying the passed-in arguments from the same place where the
683 : // 8-bit copy stopped, but this time copying over all of the characters
684 : // using a 16-bit representation.
685 : arguments.ForEach(
686 : vars,
687 56 : [this, context, two_byte_result, &var_max_index](Node* arg) {
688 56 : Node* code32 = TruncateTaggedToWord32(context, arg);
689 : Node* code16 =
690 168 : Word32And(code32, Int32Constant(String::kMaxUtf16CodeUnit));
691 :
692 : Node* offset = ElementOffsetFromIndex(
693 56 : var_max_index.value(), UINT16_ELEMENTS,
694 : CodeStubAssembler::INTPTR_PARAMETERS,
695 112 : SeqTwoByteString::kHeaderSize - kHeapObjectTag);
696 : StoreNoWriteBarrier(MachineRepresentation::kWord16, two_byte_result,
697 56 : offset, code16);
698 168 : var_max_index = IntPtrAdd(var_max_index.value(), IntPtrConstant(1));
699 56 : },
700 112 : var_max_index.value());
701 :
702 112 : arguments.PopAndReturn(two_byte_result);
703 56 : }
704 56 : }
705 :
706 : // ES6 #sec-string.prototype.charat
707 280 : TF_BUILTIN(StringPrototypeCharAt, StringBuiltinsAssembler) {
708 56 : TNode<Context> context = CAST(Parameter(Descriptor::kContext));
709 : Node* receiver = Parameter(Descriptor::kReceiver);
710 56 : TNode<Object> maybe_position = CAST(Parameter(Descriptor::kPosition));
711 :
712 : GenerateStringAt("String.prototype.charAt", context, receiver, maybe_position,
713 56 : EmptyStringConstant(),
714 : [this](TNode<String> string, TNode<IntPtrT> length,
715 56 : TNode<IntPtrT> index) {
716 56 : TNode<Int32T> code = StringCharCodeAt(string, index);
717 56 : return StringFromSingleCharCode(code);
718 168 : });
719 56 : }
720 :
721 : // ES6 #sec-string.prototype.charcodeat
722 280 : TF_BUILTIN(StringPrototypeCharCodeAt, StringBuiltinsAssembler) {
723 56 : TNode<Context> context = CAST(Parameter(Descriptor::kContext));
724 : Node* receiver = Parameter(Descriptor::kReceiver);
725 56 : TNode<Object> maybe_position = CAST(Parameter(Descriptor::kPosition));
726 :
727 : GenerateStringAt("String.prototype.charCodeAt", context, receiver,
728 56 : maybe_position, NanConstant(),
729 : [this](TNode<String> receiver, TNode<IntPtrT> length,
730 56 : TNode<IntPtrT> index) {
731 112 : Node* value = StringCharCodeAt(receiver, index);
732 56 : return SmiFromInt32(value);
733 168 : });
734 56 : }
735 :
736 : // ES6 #sec-string.prototype.codepointat
737 280 : TF_BUILTIN(StringPrototypeCodePointAt, StringBuiltinsAssembler) {
738 56 : TNode<Context> context = CAST(Parameter(Descriptor::kContext));
739 : Node* receiver = Parameter(Descriptor::kReceiver);
740 56 : TNode<Object> maybe_position = CAST(Parameter(Descriptor::kPosition));
741 :
742 : GenerateStringAt("String.prototype.codePointAt", context, receiver,
743 56 : maybe_position, UndefinedConstant(),
744 : [this](TNode<String> receiver, TNode<IntPtrT> length,
745 56 : TNode<IntPtrT> index) {
746 : // This is always a call to a builtin from Javascript,
747 : // so we need to produce UTF32.
748 : Node* value = LoadSurrogatePairAt(receiver, length, index,
749 112 : UnicodeEncoding::UTF32);
750 56 : return SmiFromInt32(value);
751 168 : });
752 56 : }
753 :
754 : // ES6 String.prototype.concat(...args)
755 : // ES6 #sec-string.prototype.concat
756 224 : TF_BUILTIN(StringPrototypeConcat, CodeStubAssembler) {
757 : // TODO(ishell): use constants from Descriptor once the JSFunction linkage
758 : // arguments are reordered.
759 : CodeStubArguments arguments(
760 : this,
761 168 : ChangeInt32ToIntPtr(Parameter(Descriptor::kJSActualArgumentsCount)));
762 112 : Node* receiver = arguments.GetReceiver();
763 : Node* context = Parameter(Descriptor::kContext);
764 :
765 : // Check that {receiver} is coercible to Object and convert it to a String.
766 112 : receiver = ToThisString(context, receiver, "String.prototype.concat");
767 :
768 : // Concatenate all the arguments passed to this builtin.
769 56 : VARIABLE(var_result, MachineRepresentation::kTagged);
770 56 : var_result.Bind(receiver);
771 : arguments.ForEach(
772 : CodeStubAssembler::VariableList({&var_result}, zone()),
773 56 : [this, context, &var_result](Node* arg) {
774 168 : arg = ToString_Inline(context, arg);
775 : var_result.Bind(CallStub(CodeFactory::StringAdd(isolate()), context,
776 168 : var_result.value(), arg));
777 224 : });
778 56 : arguments.PopAndReturn(var_result.value());
779 56 : }
780 :
781 168 : void StringBuiltinsAssembler::StringIndexOf(
782 : Node* const subject_string, Node* const search_string, Node* const position,
783 : const std::function<void(Node*)>& f_return) {
784 : CSA_ASSERT(this, IsString(subject_string));
785 : CSA_ASSERT(this, IsString(search_string));
786 : CSA_ASSERT(this, TaggedIsSmi(position));
787 :
788 168 : TNode<IntPtrT> const int_zero = IntPtrConstant(0);
789 168 : TNode<IntPtrT> const search_length = LoadStringLengthAsWord(search_string);
790 168 : TNode<IntPtrT> const subject_length = LoadStringLengthAsWord(subject_string);
791 336 : TNode<IntPtrT> const start_position = IntPtrMax(SmiUntag(position), int_zero);
792 :
793 168 : Label zero_length_needle(this), return_minus_1(this);
794 : {
795 336 : GotoIf(IntPtrEqual(int_zero, search_length), &zero_length_needle);
796 :
797 : // Check that the needle fits in the start position.
798 : GotoIfNot(IntPtrLessThanOrEqual(search_length,
799 168 : IntPtrSub(subject_length, start_position)),
800 336 : &return_minus_1);
801 : }
802 :
803 : // If the string pointers are identical, we can just return 0. Note that this
804 : // implies {start_position} == 0 since we've passed the check above.
805 168 : Label return_zero(this);
806 336 : GotoIf(WordEqual(subject_string, search_string), &return_zero);
807 :
808 : // Try to unpack subject and search strings. Bail to runtime if either needs
809 : // to be flattened.
810 336 : ToDirectStringAssembler subject_to_direct(state(), subject_string);
811 336 : ToDirectStringAssembler search_to_direct(state(), search_string);
812 :
813 168 : Label call_runtime_unchecked(this, Label::kDeferred);
814 :
815 168 : subject_to_direct.TryToDirect(&call_runtime_unchecked);
816 168 : search_to_direct.TryToDirect(&call_runtime_unchecked);
817 :
818 : // Load pointers to string data.
819 : Node* const subject_ptr =
820 : subject_to_direct.PointerToData(&call_runtime_unchecked);
821 : Node* const search_ptr =
822 : search_to_direct.PointerToData(&call_runtime_unchecked);
823 :
824 : Node* const subject_offset = subject_to_direct.offset();
825 : Node* const search_offset = search_to_direct.offset();
826 :
827 : // Like String::IndexOf, the actual matching is done by the optimized
828 : // SearchString method in string-search.h. Dispatch based on string instance
829 : // types, then call straight into C++ for matching.
830 :
831 : CSA_ASSERT(this, IntPtrGreaterThan(search_length, int_zero));
832 : CSA_ASSERT(this, IntPtrGreaterThanOrEqual(start_position, int_zero));
833 : CSA_ASSERT(this, IntPtrGreaterThanOrEqual(subject_length, start_position));
834 : CSA_ASSERT(this,
835 : IntPtrLessThanOrEqual(search_length,
836 : IntPtrSub(subject_length, start_position)));
837 :
838 168 : Label one_one(this), one_two(this), two_one(this), two_two(this);
839 : DispatchOnStringEncodings(subject_to_direct.instance_type(),
840 : search_to_direct.instance_type(), &one_one,
841 168 : &one_two, &two_one, &two_two);
842 :
843 : typedef const uint8_t onebyte_t;
844 : typedef const uc16 twobyte_t;
845 :
846 168 : BIND(&one_one);
847 : {
848 : Node* const adjusted_subject_ptr = PointerToStringDataAtIndex(
849 168 : subject_ptr, subject_offset, String::ONE_BYTE_ENCODING);
850 : Node* const adjusted_search_ptr = PointerToStringDataAtIndex(
851 168 : search_ptr, search_offset, String::ONE_BYTE_ENCODING);
852 :
853 168 : Label direct_memchr_call(this), generic_fast_path(this);
854 336 : Branch(IntPtrEqual(search_length, IntPtrConstant(1)), &direct_memchr_call,
855 336 : &generic_fast_path);
856 :
857 : // An additional fast path that calls directly into memchr for 1-length
858 : // search strings.
859 168 : BIND(&direct_memchr_call);
860 : {
861 336 : Node* const string_addr = IntPtrAdd(adjusted_subject_ptr, start_position);
862 : Node* const search_length = IntPtrSub(subject_length, start_position);
863 : Node* const search_byte =
864 504 : ChangeInt32ToIntPtr(Load(MachineType::Uint8(), adjusted_search_ptr));
865 :
866 : Node* const memchr =
867 336 : ExternalConstant(ExternalReference::libc_memchr_function());
868 : Node* const result_address =
869 : CallCFunction3(MachineType::Pointer(), MachineType::Pointer(),
870 : MachineType::IntPtr(), MachineType::UintPtr(), memchr,
871 168 : string_addr, search_byte, search_length);
872 336 : GotoIf(WordEqual(result_address, int_zero), &return_minus_1);
873 : Node* const result_index =
874 504 : IntPtrAdd(IntPtrSub(result_address, string_addr), start_position);
875 336 : f_return(SmiTag(result_index));
876 : }
877 :
878 168 : BIND(&generic_fast_path);
879 : {
880 : Node* const result = CallSearchStringRaw<onebyte_t, onebyte_t>(
881 : adjusted_subject_ptr, subject_length, adjusted_search_ptr,
882 168 : search_length, start_position);
883 336 : f_return(SmiTag(result));
884 168 : }
885 : }
886 :
887 168 : BIND(&one_two);
888 : {
889 : Node* const adjusted_subject_ptr = PointerToStringDataAtIndex(
890 168 : subject_ptr, subject_offset, String::ONE_BYTE_ENCODING);
891 : Node* const adjusted_search_ptr = PointerToStringDataAtIndex(
892 168 : search_ptr, search_offset, String::TWO_BYTE_ENCODING);
893 :
894 : Node* const result = CallSearchStringRaw<onebyte_t, twobyte_t>(
895 : adjusted_subject_ptr, subject_length, adjusted_search_ptr,
896 168 : search_length, start_position);
897 336 : f_return(SmiTag(result));
898 : }
899 :
900 168 : BIND(&two_one);
901 : {
902 : Node* const adjusted_subject_ptr = PointerToStringDataAtIndex(
903 168 : subject_ptr, subject_offset, String::TWO_BYTE_ENCODING);
904 : Node* const adjusted_search_ptr = PointerToStringDataAtIndex(
905 168 : search_ptr, search_offset, String::ONE_BYTE_ENCODING);
906 :
907 : Node* const result = CallSearchStringRaw<twobyte_t, onebyte_t>(
908 : adjusted_subject_ptr, subject_length, adjusted_search_ptr,
909 168 : search_length, start_position);
910 336 : f_return(SmiTag(result));
911 : }
912 :
913 168 : BIND(&two_two);
914 : {
915 : Node* const adjusted_subject_ptr = PointerToStringDataAtIndex(
916 168 : subject_ptr, subject_offset, String::TWO_BYTE_ENCODING);
917 : Node* const adjusted_search_ptr = PointerToStringDataAtIndex(
918 168 : search_ptr, search_offset, String::TWO_BYTE_ENCODING);
919 :
920 : Node* const result = CallSearchStringRaw<twobyte_t, twobyte_t>(
921 : adjusted_subject_ptr, subject_length, adjusted_search_ptr,
922 168 : search_length, start_position);
923 336 : f_return(SmiTag(result));
924 : }
925 :
926 168 : BIND(&return_minus_1);
927 336 : f_return(SmiConstant(-1));
928 :
929 168 : BIND(&return_zero);
930 336 : f_return(SmiConstant(0));
931 :
932 168 : BIND(&zero_length_needle);
933 : {
934 168 : Comment("0-length search_string");
935 504 : f_return(SmiTag(IntPtrMin(subject_length, start_position)));
936 : }
937 :
938 168 : BIND(&call_runtime_unchecked);
939 : {
940 : // Simplified version of the runtime call where the types of the arguments
941 : // are already known due to type checks in this stub.
942 168 : Comment("Call Runtime Unchecked");
943 : Node* result =
944 : CallRuntime(Runtime::kStringIndexOfUnchecked, NoContextConstant(),
945 336 : subject_string, search_string, position);
946 168 : f_return(result);
947 168 : }
948 168 : }
949 :
950 : // ES6 String.prototype.indexOf(searchString [, position])
951 : // #sec-string.prototype.indexof
952 : // Unchecked helper for builtins lowering.
953 224 : TF_BUILTIN(StringIndexOf, StringBuiltinsAssembler) {
954 : Node* receiver = Parameter(Descriptor::kReceiver);
955 : Node* search_string = Parameter(Descriptor::kSearchString);
956 : Node* position = Parameter(Descriptor::kPosition);
957 : StringIndexOf(receiver, search_string, position,
958 616 : [this](Node* result) { this->Return(result); });
959 56 : }
960 :
961 : // ES6 String.prototype.includes(searchString [, position])
962 : // #sec-string.prototype.includes
963 280 : TF_BUILTIN(StringPrototypeIncludes, StringIncludesIndexOfAssembler) {
964 : TNode<IntPtrT> argc =
965 56 : ChangeInt32ToIntPtr(Parameter(Descriptor::kJSActualArgumentsCount));
966 56 : TNode<Context> context = CAST(Parameter(Descriptor::kContext));
967 56 : Generate(kIncludes, argc, context);
968 56 : }
969 :
970 : // ES6 String.prototype.indexOf(searchString [, position])
971 : // #sec-string.prototype.indexof
972 280 : TF_BUILTIN(StringPrototypeIndexOf, StringIncludesIndexOfAssembler) {
973 : TNode<IntPtrT> argc =
974 56 : ChangeInt32ToIntPtr(Parameter(Descriptor::kJSActualArgumentsCount));
975 56 : TNode<Context> context = CAST(Parameter(Descriptor::kContext));
976 56 : Generate(kIndexOf, argc, context);
977 56 : }
978 :
979 112 : void StringIncludesIndexOfAssembler::Generate(SearchVariant variant,
980 : TNode<IntPtrT> argc,
981 : TNode<Context> context) {
982 112 : CodeStubArguments arguments(this, argc);
983 224 : Node* const receiver = arguments.GetReceiver();
984 :
985 112 : VARIABLE(var_search_string, MachineRepresentation::kTagged);
986 224 : VARIABLE(var_position, MachineRepresentation::kTagged);
987 112 : Label argc_1(this), argc_2(this), call_runtime(this, Label::kDeferred),
988 112 : fast_path(this);
989 :
990 336 : GotoIf(IntPtrEqual(argc, IntPtrConstant(1)), &argc_1);
991 336 : GotoIf(IntPtrGreaterThan(argc, IntPtrConstant(1)), &argc_2);
992 : {
993 112 : Comment("0 Argument case");
994 : CSA_ASSERT(this, IntPtrEqual(argc, IntPtrConstant(0)));
995 224 : Node* const undefined = UndefinedConstant();
996 112 : var_search_string.Bind(undefined);
997 112 : var_position.Bind(undefined);
998 112 : Goto(&call_runtime);
999 : }
1000 112 : BIND(&argc_1);
1001 : {
1002 112 : Comment("1 Argument case");
1003 224 : var_search_string.Bind(arguments.AtIndex(0));
1004 224 : var_position.Bind(SmiConstant(0));
1005 112 : Goto(&fast_path);
1006 : }
1007 112 : BIND(&argc_2);
1008 : {
1009 112 : Comment("2 Argument case");
1010 224 : var_search_string.Bind(arguments.AtIndex(0));
1011 224 : var_position.Bind(arguments.AtIndex(1));
1012 336 : GotoIfNot(TaggedIsSmi(var_position.value()), &call_runtime);
1013 112 : Goto(&fast_path);
1014 : }
1015 112 : BIND(&fast_path);
1016 : {
1017 112 : Comment("Fast Path");
1018 112 : Node* const search = var_search_string.value();
1019 112 : Node* const position = var_position.value();
1020 224 : GotoIf(TaggedIsSmi(receiver), &call_runtime);
1021 224 : GotoIf(TaggedIsSmi(search), &call_runtime);
1022 224 : GotoIfNot(IsString(receiver), &call_runtime);
1023 224 : GotoIfNot(IsString(search), &call_runtime);
1024 :
1025 1008 : StringIndexOf(receiver, search, position, [&](Node* result) {
1026 : CSA_ASSERT(this, TaggedIsSmi(result));
1027 1008 : arguments.PopAndReturn((variant == kIndexOf)
1028 : ? result
1029 : : SelectBooleanConstant(SmiGreaterThanOrEqual(
1030 2520 : CAST(result), SmiConstant(0))));
1031 1232 : });
1032 : }
1033 112 : BIND(&call_runtime);
1034 : {
1035 112 : Comment("Call Runtime");
1036 112 : Runtime::FunctionId runtime = variant == kIndexOf
1037 : ? Runtime::kStringIndexOf
1038 112 : : Runtime::kStringIncludes;
1039 : Node* const result =
1040 : CallRuntime(runtime, context, receiver, var_search_string.value(),
1041 112 : var_position.value());
1042 112 : arguments.PopAndReturn(result);
1043 112 : }
1044 112 : }
1045 :
1046 336 : void StringBuiltinsAssembler::RequireObjectCoercible(Node* const context,
1047 : Node* const value,
1048 : const char* method_name) {
1049 672 : Label out(this), throw_exception(this, Label::kDeferred);
1050 672 : Branch(IsNullOrUndefined(value), &throw_exception, &out);
1051 :
1052 336 : BIND(&throw_exception);
1053 : ThrowTypeError(context, MessageTemplate::kCalledOnNullOrUndefined,
1054 336 : method_name);
1055 :
1056 672 : BIND(&out);
1057 336 : }
1058 :
1059 280 : void StringBuiltinsAssembler::MaybeCallFunctionAtSymbol(
1060 : Node* const context, Node* const object, Node* const maybe_string,
1061 : Handle<Symbol> symbol, DescriptorIndexAndName symbol_index,
1062 : const NodeFunction0& regexp_call, const NodeFunction1& generic_call) {
1063 280 : Label out(this);
1064 :
1065 : // Smis definitely don't have an attached symbol.
1066 560 : GotoIf(TaggedIsSmi(object), &out);
1067 :
1068 : // Take the fast path for RegExps.
1069 : // There's two conditions: {object} needs to be a fast regexp, and
1070 : // {maybe_string} must be a string (we can't call ToString on the fast path
1071 : // since it may mutate {object}).
1072 : {
1073 280 : Label stub_call(this), slow_lookup(this);
1074 :
1075 560 : GotoIf(TaggedIsSmi(maybe_string), &slow_lookup);
1076 560 : GotoIfNot(IsString(maybe_string), &slow_lookup);
1077 :
1078 : RegExpBuiltinsAssembler regexp_asm(state());
1079 280 : regexp_asm.BranchIfFastRegExp(context, object, LoadMap(object),
1080 840 : symbol_index, &stub_call, &slow_lookup);
1081 :
1082 280 : BIND(&stub_call);
1083 : // TODO(jgruber): Add a no-JS scope once it exists.
1084 280 : regexp_call();
1085 :
1086 560 : BIND(&slow_lookup);
1087 : }
1088 :
1089 560 : GotoIf(IsNullOrUndefined(object), &out);
1090 :
1091 : // Fall back to a slow lookup of {object[symbol]}.
1092 : //
1093 : // The spec uses GetMethod({object}, {symbol}), which has a few quirks:
1094 : // * null values are turned into undefined, and
1095 : // * an exception is thrown if the value is not undefined, null, or callable.
1096 : // We handle the former by jumping to {out} for null values as well, while
1097 : // the latter is already handled by the Call({maybe_func}) operation.
1098 :
1099 560 : Node* const maybe_func = GetProperty(context, object, symbol);
1100 560 : GotoIf(IsUndefined(maybe_func), &out);
1101 560 : GotoIf(IsNull(maybe_func), &out);
1102 :
1103 : // Attempt to call the function.
1104 280 : generic_call(maybe_func);
1105 :
1106 280 : BIND(&out);
1107 280 : }
1108 :
1109 112 : TNode<Smi> StringBuiltinsAssembler::IndexOfDollarChar(Node* const context,
1110 : Node* const string) {
1111 : CSA_ASSERT(this, IsString(string));
1112 :
1113 : TNode<String> const dollar_string = HeapConstant(
1114 224 : isolate()->factory()->LookupSingleCharacterStringFromCode('$'));
1115 : TNode<Smi> const dollar_ix =
1116 224 : CAST(CallBuiltin(Builtins::kStringIndexOf, context, string, dollar_string,
1117 : SmiConstant(0)));
1118 112 : return dollar_ix;
1119 : }
1120 :
1121 56 : compiler::Node* StringBuiltinsAssembler::GetSubstitution(
1122 : Node* context, Node* subject_string, Node* match_start_index,
1123 : Node* match_end_index, Node* replace_string) {
1124 : CSA_ASSERT(this, IsString(subject_string));
1125 : CSA_ASSERT(this, IsString(replace_string));
1126 : CSA_ASSERT(this, TaggedIsPositiveSmi(match_start_index));
1127 : CSA_ASSERT(this, TaggedIsPositiveSmi(match_end_index));
1128 :
1129 56 : VARIABLE(var_result, MachineRepresentation::kTagged, replace_string);
1130 56 : Label runtime(this), out(this);
1131 :
1132 : // In this primitive implementation we simply look for the next '$' char in
1133 : // {replace_string}. If it doesn't exist, we can simply return
1134 : // {replace_string} itself. If it does, then we delegate to
1135 : // String::GetSubstitution, passing in the index of the first '$' to avoid
1136 : // repeated scanning work.
1137 : // TODO(jgruber): Possibly extend this in the future to handle more complex
1138 : // cases without runtime calls.
1139 :
1140 56 : TNode<Smi> const dollar_index = IndexOfDollarChar(context, replace_string);
1141 112 : Branch(SmiIsNegative(dollar_index), &out, &runtime);
1142 :
1143 56 : BIND(&runtime);
1144 : {
1145 : CSA_ASSERT(this, TaggedIsPositiveSmi(dollar_index));
1146 :
1147 : Node* const matched =
1148 : CallBuiltin(Builtins::kStringSubstring, context, subject_string,
1149 224 : SmiUntag(match_start_index), SmiUntag(match_end_index));
1150 : Node* const replacement_string =
1151 : CallRuntime(Runtime::kGetSubstitution, context, matched, subject_string,
1152 : match_start_index, replace_string, dollar_index);
1153 56 : var_result.Bind(replacement_string);
1154 :
1155 56 : Goto(&out);
1156 : }
1157 :
1158 56 : BIND(&out);
1159 112 : return var_result.value();
1160 : }
1161 :
1162 : // ES6 #sec-string.prototype.repeat
1163 280 : TF_BUILTIN(StringPrototypeRepeat, StringBuiltinsAssembler) {
1164 112 : Label invalid_count(this), invalid_string_length(this),
1165 56 : return_emptystring(this);
1166 :
1167 : TNode<Context> context = CAST(Parameter(Descriptor::kContext));
1168 : Node* const receiver = Parameter(Descriptor::kReceiver);
1169 : TNode<Object> count = CAST(Parameter(Descriptor::kCount));
1170 : Node* const string =
1171 112 : ToThisString(context, receiver, "String.prototype.repeat");
1172 :
1173 168 : VARIABLE(
1174 : var_count, MachineRepresentation::kTagged,
1175 : ToInteger_Inline(context, count, CodeStubAssembler::kTruncateMinusZero));
1176 :
1177 : // Verifies a valid count and takes a fast path when the result will be an
1178 : // empty string.
1179 : {
1180 : Label if_count_isheapnumber(this, Label::kDeferred);
1181 :
1182 168 : GotoIfNot(TaggedIsSmi(var_count.value()), &if_count_isheapnumber);
1183 : {
1184 : // If count is a SMI, throw a RangeError if less than 0 or greater than
1185 : // the maximum string length.
1186 56 : TNode<Smi> smi_count = CAST(var_count.value());
1187 112 : GotoIf(SmiLessThan(smi_count, SmiConstant(0)), &invalid_count);
1188 112 : GotoIf(SmiEqual(smi_count, SmiConstant(0)), &return_emptystring);
1189 168 : GotoIf(Word32Equal(LoadStringLengthAsWord32(string), Int32Constant(0)),
1190 112 : &return_emptystring);
1191 56 : GotoIf(SmiGreaterThan(smi_count, SmiConstant(String::kMaxLength)),
1192 112 : &invalid_string_length);
1193 112 : Return(CallBuiltin(Builtins::kStringRepeat, context, string, smi_count));
1194 : }
1195 :
1196 : // If count is a Heap Number...
1197 : // 1) If count is Infinity, throw a RangeError exception
1198 : // 2) If receiver is an empty string, return an empty string
1199 : // 3) Otherwise, throw RangeError exception
1200 56 : BIND(&if_count_isheapnumber);
1201 : {
1202 : CSA_ASSERT(this, IsNumberNormalized(var_count.value()));
1203 168 : Node* const number_value = LoadHeapNumberValue(var_count.value());
1204 112 : GotoIf(Float64Equal(number_value, Float64Constant(V8_INFINITY)),
1205 112 : &invalid_count);
1206 112 : GotoIf(Float64LessThan(number_value, Float64Constant(0.0)),
1207 112 : &invalid_count);
1208 168 : Branch(Word32Equal(LoadStringLengthAsWord32(string), Int32Constant(0)),
1209 112 : &return_emptystring, &invalid_string_length);
1210 56 : }
1211 : }
1212 :
1213 56 : BIND(&return_emptystring);
1214 112 : Return(EmptyStringConstant());
1215 :
1216 56 : BIND(&invalid_count);
1217 : {
1218 : ThrowRangeError(context, MessageTemplate::kInvalidCountValue,
1219 56 : var_count.value());
1220 : }
1221 :
1222 56 : BIND(&invalid_string_length);
1223 : {
1224 : CallRuntime(Runtime::kThrowInvalidStringLength, context);
1225 56 : Unreachable();
1226 56 : }
1227 56 : }
1228 :
1229 : // Helper with less checks
1230 224 : TF_BUILTIN(StringRepeat, StringBuiltinsAssembler) {
1231 : Node* const context = Parameter(Descriptor::kContext);
1232 : Node* const string = Parameter(Descriptor::kString);
1233 : TNode<Smi> const count = CAST(Parameter(Descriptor::kCount));
1234 :
1235 : CSA_ASSERT(this, IsString(string));
1236 : CSA_ASSERT(this, Word32BinaryNot(IsEmptyString(string)));
1237 : CSA_ASSERT(this, TaggedIsPositiveSmi(count));
1238 :
1239 : // The string is repeated with the following algorithm:
1240 : // let n = count;
1241 : // let power_of_two_repeats = string;
1242 : // let result = "";
1243 : // while (true) {
1244 : // if (n & 1) result += s;
1245 : // n >>= 1;
1246 : // if (n === 0) return result;
1247 : // power_of_two_repeats += power_of_two_repeats;
1248 : // }
1249 112 : VARIABLE(var_result, MachineRepresentation::kTagged, EmptyStringConstant());
1250 112 : VARIABLE(var_temp, MachineRepresentation::kTagged, string);
1251 : TVARIABLE(Smi, var_count, count);
1252 :
1253 168 : Label loop(this, {&var_count, &var_result, &var_temp}), return_result(this);
1254 56 : Goto(&loop);
1255 56 : BIND(&loop);
1256 : {
1257 : {
1258 : Label next(this);
1259 224 : GotoIfNot(SmiToInt32(SmiAnd(var_count.value(), SmiConstant(1))), &next);
1260 : var_result.Bind(CallBuiltin(Builtins::kStringAdd_CheckNone, context,
1261 168 : var_result.value(), var_temp.value()));
1262 56 : Goto(&next);
1263 56 : BIND(&next);
1264 : }
1265 :
1266 56 : var_count = SmiShr(var_count.value(), 1);
1267 168 : GotoIf(SmiEqual(var_count.value(), SmiConstant(0)), &return_result);
1268 : var_temp.Bind(CallBuiltin(Builtins::kStringAdd_CheckNone, context,
1269 168 : var_temp.value(), var_temp.value()));
1270 56 : Goto(&loop);
1271 : }
1272 :
1273 56 : BIND(&return_result);
1274 168 : Return(var_result.value());
1275 56 : }
1276 :
1277 : // ES6 #sec-string.prototype.replace
1278 280 : TF_BUILTIN(StringPrototypeReplace, StringBuiltinsAssembler) {
1279 56 : Label out(this);
1280 :
1281 : Node* const receiver = Parameter(Descriptor::kReceiver);
1282 : Node* const search = Parameter(Descriptor::kSearch);
1283 : Node* const replace = Parameter(Descriptor::kReplace);
1284 : Node* const context = Parameter(Descriptor::kContext);
1285 :
1286 56 : TNode<Smi> const smi_zero = SmiConstant(0);
1287 :
1288 56 : RequireObjectCoercible(context, receiver, "String.prototype.replace");
1289 :
1290 : // Redirect to replacer method if {search[@@replace]} is not undefined.
1291 :
1292 : MaybeCallFunctionAtSymbol(
1293 : context, search, receiver, isolate()->factory()->replace_symbol(),
1294 : DescriptorIndexAndName{JSRegExp::kSymbolReplaceFunctionDescriptorIndex,
1295 : RootIndex::kreplace_symbol},
1296 56 : [=]() {
1297 : Return(CallBuiltin(Builtins::kRegExpReplace, context, search, receiver,
1298 168 : replace));
1299 56 : },
1300 56 : [=](Node* fn) {
1301 56 : Callable call_callable = CodeFactory::Call(isolate());
1302 112 : Return(CallJS(call_callable, context, fn, search, receiver, replace));
1303 280 : });
1304 :
1305 : // Convert {receiver} and {search} to strings.
1306 :
1307 56 : TNode<String> const subject_string = ToString_Inline(context, receiver);
1308 56 : TNode<String> const search_string = ToString_Inline(context, search);
1309 :
1310 56 : TNode<IntPtrT> const subject_length = LoadStringLengthAsWord(subject_string);
1311 56 : TNode<IntPtrT> const search_length = LoadStringLengthAsWord(search_string);
1312 :
1313 : // Fast-path single-char {search}, long cons {receiver}, and simple string
1314 : // {replace}.
1315 : {
1316 : Label next(this);
1317 :
1318 168 : GotoIfNot(WordEqual(search_length, IntPtrConstant(1)), &next);
1319 168 : GotoIfNot(IntPtrGreaterThan(subject_length, IntPtrConstant(0xFF)), &next);
1320 112 : GotoIf(TaggedIsSmi(replace), &next);
1321 112 : GotoIfNot(IsString(replace), &next);
1322 :
1323 112 : Node* const subject_instance_type = LoadInstanceType(subject_string);
1324 112 : GotoIfNot(IsConsStringInstanceType(subject_instance_type), &next);
1325 :
1326 168 : GotoIf(TaggedIsPositiveSmi(IndexOfDollarChar(context, replace)), &next);
1327 :
1328 : // Searching by traversing a cons string tree and replace with cons of
1329 : // slices works only when the replaced string is a single character, being
1330 : // replaced by a simple string and only pays off for long strings.
1331 : // TODO(jgruber): Reevaluate if this is still beneficial.
1332 : // TODO(jgruber): TailCallRuntime when it correctly handles adapter frames.
1333 : Return(CallRuntime(Runtime::kStringReplaceOneCharWithString, context,
1334 56 : subject_string, search_string, replace));
1335 :
1336 56 : BIND(&next);
1337 : }
1338 :
1339 : // TODO(jgruber): Extend StringIndexOf to handle two-byte strings and
1340 : // longer substrings - we can handle up to 8 chars (one-byte) / 4 chars
1341 : // (2-byte).
1342 :
1343 : TNode<Smi> const match_start_index =
1344 56 : CAST(CallBuiltin(Builtins::kStringIndexOf, context, subject_string,
1345 : search_string, smi_zero));
1346 :
1347 : // Early exit if no match found.
1348 : {
1349 56 : Label next(this), return_subject(this);
1350 :
1351 112 : GotoIfNot(SmiIsNegative(match_start_index), &next);
1352 :
1353 : // The spec requires to perform ToString(replace) if the {replace} is not
1354 : // callable even if we are going to exit here.
1355 : // Since ToString() being applied to Smi does not have side effects for
1356 : // numbers we can skip it.
1357 112 : GotoIf(TaggedIsSmi(replace), &return_subject);
1358 168 : GotoIf(IsCallableMap(LoadMap(replace)), &return_subject);
1359 :
1360 : // TODO(jgruber): Could introduce ToStringSideeffectsStub which only
1361 : // performs observable parts of ToString.
1362 56 : ToString_Inline(context, replace);
1363 56 : Goto(&return_subject);
1364 :
1365 56 : BIND(&return_subject);
1366 56 : Return(subject_string);
1367 :
1368 112 : BIND(&next);
1369 : }
1370 :
1371 : TNode<Smi> const match_end_index =
1372 56 : SmiAdd(match_start_index, SmiFromIntPtr(search_length));
1373 :
1374 168 : VARIABLE(var_result, MachineRepresentation::kTagged, EmptyStringConstant());
1375 :
1376 : // Compute the prefix.
1377 : {
1378 : Label next(this);
1379 :
1380 112 : GotoIf(SmiEqual(match_start_index, smi_zero), &next);
1381 : Node* const prefix =
1382 : CallBuiltin(Builtins::kStringSubstring, context, subject_string,
1383 168 : IntPtrConstant(0), SmiUntag(match_start_index));
1384 56 : var_result.Bind(prefix);
1385 :
1386 56 : Goto(&next);
1387 56 : BIND(&next);
1388 : }
1389 :
1390 : // Compute the string to replace with.
1391 :
1392 56 : Label if_iscallablereplace(this), if_notcallablereplace(this);
1393 112 : GotoIf(TaggedIsSmi(replace), &if_notcallablereplace);
1394 112 : Branch(IsCallableMap(LoadMap(replace)), &if_iscallablereplace,
1395 112 : &if_notcallablereplace);
1396 :
1397 56 : BIND(&if_iscallablereplace);
1398 : {
1399 56 : Callable call_callable = CodeFactory::Call(isolate());
1400 : Node* const replacement =
1401 : CallJS(call_callable, context, replace, UndefinedConstant(),
1402 112 : search_string, match_start_index, subject_string);
1403 112 : Node* const replacement_string = ToString_Inline(context, replacement);
1404 : var_result.Bind(CallBuiltin(Builtins::kStringAdd_CheckNone, context,
1405 168 : var_result.value(), replacement_string));
1406 56 : Goto(&out);
1407 : }
1408 :
1409 56 : BIND(&if_notcallablereplace);
1410 : {
1411 112 : Node* const replace_string = ToString_Inline(context, replace);
1412 : Node* const replacement =
1413 : GetSubstitution(context, subject_string, match_start_index,
1414 56 : match_end_index, replace_string);
1415 : var_result.Bind(CallBuiltin(Builtins::kStringAdd_CheckNone, context,
1416 168 : var_result.value(), replacement));
1417 56 : Goto(&out);
1418 : }
1419 :
1420 56 : BIND(&out);
1421 : {
1422 : Node* const suffix =
1423 : CallBuiltin(Builtins::kStringSubstring, context, subject_string,
1424 168 : SmiUntag(match_end_index), subject_length);
1425 : Node* const result = CallBuiltin(Builtins::kStringAdd_CheckNone, context,
1426 168 : var_result.value(), suffix);
1427 56 : Return(result);
1428 56 : }
1429 56 : }
1430 :
1431 : class StringMatchSearchAssembler : public StringBuiltinsAssembler {
1432 : public:
1433 : explicit StringMatchSearchAssembler(compiler::CodeAssemblerState* state)
1434 : : StringBuiltinsAssembler(state) {}
1435 :
1436 : protected:
1437 : enum Variant { kMatch, kSearch };
1438 :
1439 112 : void Generate(Variant variant, const char* method_name,
1440 : TNode<Object> receiver, TNode<Object> maybe_regexp,
1441 : TNode<Context> context) {
1442 112 : Label call_regexp_match_search(this);
1443 :
1444 : Builtins::Name builtin;
1445 : Handle<Symbol> symbol;
1446 : DescriptorIndexAndName property_to_check;
1447 112 : if (variant == kMatch) {
1448 : builtin = Builtins::kRegExpMatchFast;
1449 56 : symbol = isolate()->factory()->match_symbol();
1450 : property_to_check =
1451 : DescriptorIndexAndName{JSRegExp::kSymbolMatchFunctionDescriptorIndex,
1452 : RootIndex::kmatch_symbol};
1453 : } else {
1454 : builtin = Builtins::kRegExpSearchFast;
1455 56 : symbol = isolate()->factory()->search_symbol();
1456 : property_to_check =
1457 : DescriptorIndexAndName{JSRegExp::kSymbolSearchFunctionDescriptorIndex,
1458 : RootIndex::ksearch_symbol};
1459 : }
1460 :
1461 112 : RequireObjectCoercible(context, receiver, method_name);
1462 :
1463 : MaybeCallFunctionAtSymbol(
1464 : context, maybe_regexp, receiver, symbol, property_to_check,
1465 336 : [=] { Return(CallBuiltin(builtin, context, maybe_regexp, receiver)); },
1466 112 : [=](Node* fn) {
1467 112 : Callable call_callable = CodeFactory::Call(isolate());
1468 224 : Return(CallJS(call_callable, context, fn, maybe_regexp, receiver));
1469 560 : });
1470 :
1471 : // maybe_regexp is not a RegExp nor has [@@match / @@search] property.
1472 : {
1473 : RegExpBuiltinsAssembler regexp_asm(state());
1474 :
1475 112 : TNode<String> receiver_string = ToString_Inline(context, receiver);
1476 112 : TNode<Context> native_context = LoadNativeContext(context);
1477 112 : TNode<HeapObject> regexp_function = CAST(
1478 : LoadContextElement(native_context, Context::REGEXP_FUNCTION_INDEX));
1479 : TNode<Map> initial_map = CAST(LoadObjectField(
1480 : regexp_function, JSFunction::kPrototypeOrInitialMapOffset));
1481 : TNode<Object> regexp = regexp_asm.RegExpCreate(
1482 112 : context, initial_map, maybe_regexp, EmptyStringConstant());
1483 :
1484 112 : Label fast_path(this), slow_path(this);
1485 : regexp_asm.BranchIfFastRegExp(context, regexp, initial_map,
1486 112 : property_to_check, &fast_path, &slow_path);
1487 :
1488 112 : BIND(&fast_path);
1489 224 : Return(CallBuiltin(builtin, context, regexp, receiver_string));
1490 :
1491 112 : BIND(&slow_path);
1492 : {
1493 112 : TNode<Object> maybe_func = GetProperty(context, regexp, symbol);
1494 112 : Callable call_callable = CodeFactory::Call(isolate());
1495 : Return(CallJS(call_callable, context, maybe_func, regexp,
1496 224 : receiver_string));
1497 : }
1498 112 : }
1499 112 : }
1500 : };
1501 :
1502 : // ES6 #sec-string.prototype.match
1503 336 : TF_BUILTIN(StringPrototypeMatch, StringMatchSearchAssembler) {
1504 56 : TNode<Object> receiver = CAST(Parameter(Descriptor::kReceiver));
1505 56 : TNode<Object> maybe_regexp = CAST(Parameter(Descriptor::kRegexp));
1506 56 : TNode<Context> context = CAST(Parameter(Descriptor::kContext));
1507 :
1508 56 : Generate(kMatch, "String.prototype.match", receiver, maybe_regexp, context);
1509 56 : }
1510 :
1511 : // ES #sec-string.prototype.matchAll
1512 336 : TF_BUILTIN(StringPrototypeMatchAll, StringBuiltinsAssembler) {
1513 : char const* method_name = "String.prototype.matchAll";
1514 :
1515 56 : TNode<Context> context = CAST(Parameter(Descriptor::kContext));
1516 56 : TNode<Object> maybe_regexp = CAST(Parameter(Descriptor::kRegexp));
1517 56 : TNode<Object> receiver = CAST(Parameter(Descriptor::kReceiver));
1518 56 : TNode<Context> native_context = LoadNativeContext(context);
1519 :
1520 : // 1. Let O be ? RequireObjectCoercible(this value).
1521 56 : RequireObjectCoercible(context, receiver, method_name);
1522 :
1523 : // 2. If regexp is neither undefined nor null, then
1524 : // a. Let matcher be ? GetMethod(regexp, @@matchAll).
1525 : // b. If matcher is not undefined, then
1526 : // i. Return ? Call(matcher, regexp, « O »).
1527 56 : auto if_regexp_call = [&] {
1528 : // MaybeCallFunctionAtSymbol guarantees fast path is chosen only if
1529 : // maybe_regexp is a fast regexp and receiver is a string.
1530 56 : TNode<String> s = CAST(receiver);
1531 :
1532 56 : RegExpMatchAllAssembler regexp_asm(state());
1533 56 : regexp_asm.Generate(context, native_context, maybe_regexp, s);
1534 56 : };
1535 56 : auto if_generic_call = [=](Node* fn) {
1536 56 : Callable call_callable = CodeFactory::Call(isolate());
1537 112 : Return(CallJS(call_callable, context, fn, maybe_regexp, receiver));
1538 112 : };
1539 : MaybeCallFunctionAtSymbol(
1540 : context, maybe_regexp, receiver, isolate()->factory()->match_all_symbol(),
1541 : DescriptorIndexAndName{JSRegExp::kSymbolMatchAllFunctionDescriptorIndex,
1542 : RootIndex::kmatch_all_symbol},
1543 224 : if_regexp_call, if_generic_call);
1544 :
1545 : RegExpMatchAllAssembler regexp_asm(state());
1546 :
1547 : // 3. Let S be ? ToString(O).
1548 56 : TNode<String> s = ToString_Inline(context, receiver);
1549 :
1550 : // 4. Let rx be ? RegExpCreate(R, "g").
1551 : TNode<Object> rx = regexp_asm.RegExpCreate(context, native_context,
1552 56 : maybe_regexp, StringConstant("g"));
1553 :
1554 : // 5. Return ? Invoke(rx, @@matchAll, « S »).
1555 56 : Callable callable = CodeFactory::Call(isolate());
1556 : TNode<Object> match_all_func =
1557 112 : GetProperty(context, rx, isolate()->factory()->match_all_symbol());
1558 112 : Return(CallJS(callable, context, match_all_func, rx, s));
1559 56 : }
1560 :
1561 : class StringPadAssembler : public StringBuiltinsAssembler {
1562 : public:
1563 : explicit StringPadAssembler(compiler::CodeAssemblerState* state)
1564 : : StringBuiltinsAssembler(state) {}
1565 :
1566 : protected:
1567 : enum Variant { kStart, kEnd };
1568 :
1569 112 : void Generate(Variant variant, const char* method_name, TNode<IntPtrT> argc,
1570 : TNode<Context> context) {
1571 112 : CodeStubArguments arguments(this, argc);
1572 224 : Node* const receiver = arguments.GetReceiver();
1573 224 : Node* const receiver_string = ToThisString(context, receiver, method_name);
1574 112 : TNode<Smi> const string_length = LoadStringLengthAsSmi(receiver_string);
1575 :
1576 112 : TVARIABLE(String, var_fill_string, StringConstant(" "));
1577 112 : TVARIABLE(IntPtrT, var_fill_length, IntPtrConstant(1));
1578 :
1579 112 : Label check_fill(this), dont_pad(this), invalid_string_length(this),
1580 112 : pad(this);
1581 :
1582 : // If no max_length was provided, return the string.
1583 336 : GotoIf(IntPtrEqual(argc, IntPtrConstant(0)), &dont_pad);
1584 :
1585 : TNode<Number> const max_length =
1586 224 : ToLength_Inline(context, arguments.AtIndex(0));
1587 : CSA_ASSERT(this, IsNumberNormalized(max_length));
1588 :
1589 : // If max_length <= string_length, return the string.
1590 224 : GotoIfNot(TaggedIsSmi(max_length), &check_fill);
1591 : Branch(SmiLessThanOrEqual(CAST(max_length), string_length), &dont_pad,
1592 224 : &check_fill);
1593 :
1594 112 : BIND(&check_fill);
1595 : {
1596 336 : GotoIf(IntPtrEqual(argc, IntPtrConstant(1)), &pad);
1597 224 : Node* const fill = arguments.AtIndex(1);
1598 224 : GotoIf(IsUndefined(fill), &pad);
1599 :
1600 224 : var_fill_string = ToString_Inline(context, fill);
1601 224 : var_fill_length = LoadStringLengthAsWord(var_fill_string.value());
1602 224 : Branch(WordEqual(var_fill_length.value(), IntPtrConstant(0)), &dont_pad,
1603 224 : &pad);
1604 : }
1605 :
1606 112 : BIND(&pad);
1607 : {
1608 : CSA_ASSERT(this,
1609 : IntPtrGreaterThan(var_fill_length.value(), IntPtrConstant(0)));
1610 :
1611 : // Throw if max_length is greater than String::kMaxLength.
1612 224 : GotoIfNot(TaggedIsSmi(max_length), &invalid_string_length);
1613 112 : TNode<Smi> smi_max_length = CAST(max_length);
1614 : GotoIfNot(
1615 112 : SmiLessThanOrEqual(smi_max_length, SmiConstant(String::kMaxLength)),
1616 224 : &invalid_string_length);
1617 :
1618 : CSA_ASSERT(this, SmiGreaterThan(smi_max_length, string_length));
1619 112 : TNode<Smi> const pad_length = SmiSub(smi_max_length, string_length);
1620 :
1621 112 : VARIABLE(var_pad, MachineRepresentation::kTagged);
1622 112 : Label single_char_fill(this), multi_char_fill(this), return_result(this);
1623 224 : Branch(IntPtrEqual(var_fill_length.value(), IntPtrConstant(1)),
1624 224 : &single_char_fill, &multi_char_fill);
1625 :
1626 : // Fast path for a single character fill. No need to calculate number of
1627 : // repetitions or remainder.
1628 112 : BIND(&single_char_fill);
1629 : {
1630 : var_pad.Bind(CallBuiltin(Builtins::kStringRepeat, context,
1631 : static_cast<Node*>(var_fill_string.value()),
1632 224 : pad_length));
1633 112 : Goto(&return_result);
1634 : }
1635 112 : BIND(&multi_char_fill);
1636 : {
1637 : TNode<Int32T> const fill_length_word32 =
1638 112 : TruncateIntPtrToInt32(var_fill_length.value());
1639 112 : TNode<Int32T> const pad_length_word32 = SmiToInt32(pad_length);
1640 : TNode<Int32T> const repetitions_word32 =
1641 112 : Int32Div(pad_length_word32, fill_length_word32);
1642 : TNode<Int32T> const remaining_word32 =
1643 112 : Int32Mod(pad_length_word32, fill_length_word32);
1644 :
1645 : var_pad.Bind(CallBuiltin(Builtins::kStringRepeat, context,
1646 : var_fill_string.value(),
1647 336 : SmiFromInt32(repetitions_word32)));
1648 :
1649 112 : GotoIfNot(remaining_word32, &return_result);
1650 : {
1651 : Node* const remainder_string = CallBuiltin(
1652 : Builtins::kStringSubstring, context, var_fill_string.value(),
1653 336 : IntPtrConstant(0), ChangeInt32ToIntPtr(remaining_word32));
1654 : var_pad.Bind(CallBuiltin(Builtins::kStringAdd_CheckNone, context,
1655 336 : var_pad.value(), remainder_string));
1656 112 : Goto(&return_result);
1657 : }
1658 : }
1659 112 : BIND(&return_result);
1660 : CSA_ASSERT(this,
1661 : SmiEqual(pad_length, LoadStringLengthAsSmi(var_pad.value())));
1662 : arguments.PopAndReturn(
1663 : variant == kStart
1664 : ? CallBuiltin(Builtins::kStringAdd_CheckNone, context,
1665 224 : var_pad.value(), receiver_string)
1666 : : CallBuiltin(Builtins::kStringAdd_CheckNone, context,
1667 504 : receiver_string, var_pad.value()));
1668 : }
1669 112 : BIND(&dont_pad);
1670 112 : arguments.PopAndReturn(receiver_string);
1671 112 : BIND(&invalid_string_length);
1672 : {
1673 : CallRuntime(Runtime::kThrowInvalidStringLength, context);
1674 112 : Unreachable();
1675 : }
1676 112 : }
1677 : };
1678 :
1679 280 : TF_BUILTIN(StringPrototypePadEnd, StringPadAssembler) {
1680 : TNode<IntPtrT> argc =
1681 56 : ChangeInt32ToIntPtr(Parameter(Descriptor::kJSActualArgumentsCount));
1682 56 : TNode<Context> context = CAST(Parameter(Descriptor::kContext));
1683 :
1684 56 : Generate(kEnd, "String.prototype.padEnd", argc, context);
1685 56 : }
1686 :
1687 280 : TF_BUILTIN(StringPrototypePadStart, StringPadAssembler) {
1688 : TNode<IntPtrT> argc =
1689 56 : ChangeInt32ToIntPtr(Parameter(Descriptor::kJSActualArgumentsCount));
1690 56 : TNode<Context> context = CAST(Parameter(Descriptor::kContext));
1691 :
1692 56 : Generate(kStart, "String.prototype.padStart", argc, context);
1693 56 : }
1694 :
1695 : // ES6 #sec-string.prototype.search
1696 336 : TF_BUILTIN(StringPrototypeSearch, StringMatchSearchAssembler) {
1697 56 : TNode<Object> receiver = CAST(Parameter(Descriptor::kReceiver));
1698 56 : TNode<Object> maybe_regexp = CAST(Parameter(Descriptor::kRegexp));
1699 56 : TNode<Context> context = CAST(Parameter(Descriptor::kContext));
1700 56 : Generate(kSearch, "String.prototype.search", receiver, maybe_regexp, context);
1701 56 : }
1702 :
1703 : // ES6 section 21.1.3.18 String.prototype.slice ( start, end )
1704 336 : TF_BUILTIN(StringPrototypeSlice, StringBuiltinsAssembler) {
1705 56 : Label out(this);
1706 : TVARIABLE(IntPtrT, var_start);
1707 : TVARIABLE(IntPtrT, var_end);
1708 :
1709 : const int kStart = 0;
1710 : const int kEnd = 1;
1711 : Node* argc =
1712 112 : ChangeInt32ToIntPtr(Parameter(Descriptor::kJSActualArgumentsCount));
1713 56 : CodeStubArguments args(this, argc);
1714 112 : Node* const receiver = args.GetReceiver();
1715 56 : TNode<Object> start = args.GetOptionalArgumentValue(kStart);
1716 56 : TNode<Object> end = args.GetOptionalArgumentValue(kEnd);
1717 : TNode<Context> context = CAST(Parameter(Descriptor::kContext));
1718 :
1719 : // 1. Let O be ? RequireObjectCoercible(this value).
1720 56 : RequireObjectCoercible(context, receiver, "String.prototype.slice");
1721 :
1722 : // 2. Let S be ? ToString(O).
1723 : TNode<String> const subject_string =
1724 56 : CAST(CallBuiltin(Builtins::kToString, context, receiver));
1725 :
1726 : // 3. Let len be the number of elements in S.
1727 56 : TNode<IntPtrT> const length = LoadStringLengthAsWord(subject_string);
1728 :
1729 : // Convert {start} to a relative index.
1730 56 : var_start = ConvertToRelativeIndex(context, start, length);
1731 :
1732 : // 5. If end is undefined, let intEnd be len;
1733 : var_end = length;
1734 112 : GotoIf(IsUndefined(end), &out);
1735 :
1736 : // Convert {end} to a relative index.
1737 56 : var_end = ConvertToRelativeIndex(context, end, length);
1738 56 : Goto(&out);
1739 :
1740 56 : Label return_emptystring(this);
1741 56 : BIND(&out);
1742 : {
1743 56 : GotoIf(IntPtrLessThanOrEqual(var_end.value(), var_start.value()),
1744 112 : &return_emptystring);
1745 : TNode<String> const result =
1746 56 : SubString(subject_string, var_start.value(), var_end.value());
1747 56 : args.PopAndReturn(result);
1748 : }
1749 :
1750 56 : BIND(&return_emptystring);
1751 168 : args.PopAndReturn(EmptyStringConstant());
1752 56 : }
1753 :
1754 56 : TNode<JSArray> StringBuiltinsAssembler::StringToArray(
1755 : TNode<Context> context, TNode<String> subject_string,
1756 : TNode<Smi> subject_length, TNode<Number> limit_number) {
1757 : CSA_ASSERT(this, SmiGreaterThan(subject_length, SmiConstant(0)));
1758 :
1759 112 : Label done(this), call_runtime(this, Label::kDeferred),
1760 56 : fill_thehole_and_call_runtime(this, Label::kDeferred);
1761 : TVARIABLE(JSArray, result_array);
1762 :
1763 56 : TNode<Int32T> instance_type = LoadInstanceType(subject_string);
1764 112 : GotoIfNot(IsOneByteStringInstanceType(instance_type), &call_runtime);
1765 :
1766 : // Try to use cached one byte characters.
1767 : {
1768 : TNode<Smi> length_smi =
1769 56 : Select<Smi>(TaggedIsSmi(limit_number),
1770 56 : [=] { return SmiMin(CAST(limit_number), subject_length); },
1771 280 : [=] { return subject_length; });
1772 : TNode<IntPtrT> length = SmiToIntPtr(length_smi);
1773 :
1774 56 : ToDirectStringAssembler to_direct(state(), subject_string);
1775 56 : to_direct.TryToDirect(&call_runtime);
1776 56 : TNode<FixedArray> elements = CAST(AllocateFixedArray(
1777 : PACKED_ELEMENTS, length, AllocationFlag::kAllowLargeObjectAllocation));
1778 : // Don't allocate anything while {string_data} is live!
1779 : TNode<RawPtrT> string_data = UncheckedCast<RawPtrT>(
1780 56 : to_direct.PointerToData(&fill_thehole_and_call_runtime));
1781 56 : TNode<IntPtrT> string_data_offset = to_direct.offset();
1782 56 : TNode<Object> cache = LoadRoot(RootIndex::kSingleCharacterStringCache);
1783 :
1784 : BuildFastLoop(
1785 : IntPtrConstant(0), length,
1786 56 : [&](Node* index) {
1787 : // TODO(jkummerow): Implement a CSA version of DisallowHeapAllocation
1788 : // and use that to guard ToDirectStringAssembler.PointerToData().
1789 : CSA_ASSERT(this, WordEqual(to_direct.PointerToData(&call_runtime),
1790 : string_data));
1791 : TNode<Int32T> char_code =
1792 : UncheckedCast<Int32T>(Load(MachineType::Uint8(), string_data,
1793 224 : IntPtrAdd(index, string_data_offset)));
1794 112 : Node* code_index = ChangeUint32ToWord(char_code);
1795 56 : TNode<Object> entry = LoadFixedArrayElement(CAST(cache), code_index);
1796 :
1797 : // If we cannot find a char in the cache, fill the hole for the fixed
1798 : // array, and call runtime.
1799 168 : GotoIf(IsUndefined(entry), &fill_thehole_and_call_runtime);
1800 :
1801 56 : StoreFixedArrayElement(elements, index, entry);
1802 56 : },
1803 168 : 1, ParameterMode::INTPTR_PARAMETERS, IndexAdvanceMode::kPost);
1804 :
1805 56 : TNode<Map> array_map = LoadJSArrayElementsMap(PACKED_ELEMENTS, context);
1806 56 : result_array =
1807 : AllocateUninitializedJSArrayWithoutElements(array_map, length_smi);
1808 56 : StoreObjectField(result_array.value(), JSObject::kElementsOffset, elements);
1809 56 : Goto(&done);
1810 :
1811 56 : BIND(&fill_thehole_and_call_runtime);
1812 : {
1813 : FillFixedArrayWithValue(PACKED_ELEMENTS, elements, IntPtrConstant(0),
1814 112 : length, RootIndex::kTheHoleValue);
1815 56 : Goto(&call_runtime);
1816 56 : }
1817 : }
1818 :
1819 56 : BIND(&call_runtime);
1820 : {
1821 : result_array = CAST(CallRuntime(Runtime::kStringToArray, context,
1822 : subject_string, limit_number));
1823 56 : Goto(&done);
1824 : }
1825 :
1826 56 : BIND(&done);
1827 56 : return result_array.value();
1828 : }
1829 :
1830 : // ES6 section 21.1.3.19 String.prototype.split ( separator, limit )
1831 280 : TF_BUILTIN(StringPrototypeSplit, StringBuiltinsAssembler) {
1832 : const int kSeparatorArg = 0;
1833 : const int kLimitArg = 1;
1834 :
1835 : Node* const argc =
1836 112 : ChangeInt32ToIntPtr(Parameter(Descriptor::kJSActualArgumentsCount));
1837 56 : CodeStubArguments args(this, argc);
1838 :
1839 112 : Node* const receiver = args.GetReceiver();
1840 112 : Node* const separator = args.GetOptionalArgumentValue(kSeparatorArg);
1841 112 : Node* const limit = args.GetOptionalArgumentValue(kLimitArg);
1842 56 : TNode<Context> context = CAST(Parameter(Descriptor::kContext));
1843 :
1844 56 : TNode<Smi> smi_zero = SmiConstant(0);
1845 :
1846 112 : RequireObjectCoercible(context, receiver, "String.prototype.split");
1847 :
1848 : // Redirect to splitter method if {separator[@@split]} is not undefined.
1849 :
1850 : MaybeCallFunctionAtSymbol(
1851 : context, separator, receiver, isolate()->factory()->split_symbol(),
1852 : DescriptorIndexAndName{JSRegExp::kSymbolSplitFunctionDescriptorIndex,
1853 : RootIndex::ksplit_symbol},
1854 56 : [&]() {
1855 : args.PopAndReturn(CallBuiltin(Builtins::kRegExpSplit, context,
1856 168 : separator, receiver, limit));
1857 56 : },
1858 56 : [&](Node* fn) {
1859 56 : Callable call_callable = CodeFactory::Call(isolate());
1860 : args.PopAndReturn(
1861 112 : CallJS(call_callable, context, fn, separator, receiver, limit));
1862 336 : });
1863 :
1864 : // String and integer conversions.
1865 :
1866 112 : TNode<String> subject_string = ToString_Inline(context, receiver);
1867 : TNode<Number> limit_number = Select<Number>(
1868 112 : IsUndefined(limit), [=] { return NumberConstant(kMaxUInt32); },
1869 336 : [=] { return ToUint32(context, limit); });
1870 168 : Node* const separator_string = ToString_Inline(context, separator);
1871 :
1872 : Label return_empty_array(this);
1873 :
1874 : // Shortcut for {limit} == 0.
1875 : GotoIf(WordEqual<Object, Object>(limit_number, smi_zero),
1876 56 : &return_empty_array);
1877 :
1878 : // ECMA-262 says that if {separator} is undefined, the result should
1879 : // be an array of size 1 containing the entire string.
1880 : {
1881 : Label next(this);
1882 168 : GotoIfNot(IsUndefined(separator), &next);
1883 :
1884 : const ElementsKind kind = PACKED_ELEMENTS;
1885 112 : Node* const native_context = LoadNativeContext(context);
1886 56 : TNode<Map> array_map = LoadJSArrayElementsMap(kind, native_context);
1887 :
1888 56 : TNode<Smi> length = SmiConstant(1);
1889 56 : TNode<IntPtrT> capacity = IntPtrConstant(1);
1890 : TNode<JSArray> result = AllocateJSArray(kind, array_map, capacity, length);
1891 :
1892 56 : TNode<FixedArray> fixed_array = CAST(LoadElements(result));
1893 56 : StoreFixedArrayElement(fixed_array, 0, subject_string);
1894 :
1895 56 : args.PopAndReturn(result);
1896 :
1897 56 : BIND(&next);
1898 : }
1899 :
1900 : // If the separator string is empty then return the elements in the subject.
1901 : {
1902 : Label next(this);
1903 112 : GotoIfNot(SmiEqual(LoadStringLengthAsSmi(separator_string), smi_zero),
1904 112 : &next);
1905 :
1906 56 : TNode<Smi> subject_length = LoadStringLengthAsSmi(subject_string);
1907 112 : GotoIf(SmiEqual(subject_length, smi_zero), &return_empty_array);
1908 :
1909 : args.PopAndReturn(
1910 112 : StringToArray(context, subject_string, subject_length, limit_number));
1911 :
1912 56 : BIND(&next);
1913 : }
1914 :
1915 : Node* const result =
1916 : CallRuntime(Runtime::kStringSplit, context, subject_string,
1917 : separator_string, limit_number);
1918 56 : args.PopAndReturn(result);
1919 :
1920 56 : BIND(&return_empty_array);
1921 : {
1922 : const ElementsKind kind = PACKED_ELEMENTS;
1923 112 : Node* const native_context = LoadNativeContext(context);
1924 56 : TNode<Map> array_map = LoadJSArrayElementsMap(kind, native_context);
1925 :
1926 : TNode<Smi> length = smi_zero;
1927 56 : TNode<IntPtrT> capacity = IntPtrConstant(0);
1928 : TNode<JSArray> result = AllocateJSArray(kind, array_map, capacity, length);
1929 :
1930 56 : args.PopAndReturn(result);
1931 56 : }
1932 56 : }
1933 :
1934 : // ES6 #sec-string.prototype.substr
1935 280 : TF_BUILTIN(StringPrototypeSubstr, StringBuiltinsAssembler) {
1936 : const int kStartArg = 0;
1937 : const int kLengthArg = 1;
1938 :
1939 : Node* const argc =
1940 112 : ChangeInt32ToIntPtr(Parameter(Descriptor::kJSActualArgumentsCount));
1941 56 : CodeStubArguments args(this, argc);
1942 :
1943 112 : Node* const receiver = args.GetReceiver();
1944 56 : TNode<Object> start = args.GetOptionalArgumentValue(kStartArg);
1945 56 : TNode<Object> length = args.GetOptionalArgumentValue(kLengthArg);
1946 : TNode<Context> context = CAST(Parameter(Descriptor::kContext));
1947 :
1948 : Label out(this);
1949 :
1950 : TVARIABLE(IntPtrT, var_start);
1951 : TVARIABLE(Number, var_length);
1952 :
1953 56 : TNode<IntPtrT> const zero = IntPtrConstant(0);
1954 :
1955 : // Check that {receiver} is coercible to Object and convert it to a String.
1956 : TNode<String> const string =
1957 56 : ToThisString(context, receiver, "String.prototype.substr");
1958 :
1959 56 : TNode<IntPtrT> const string_length = LoadStringLengthAsWord(string);
1960 :
1961 : // Convert {start} to a relative index.
1962 56 : var_start = ConvertToRelativeIndex(context, start, string_length);
1963 :
1964 : // Conversions and bounds-checks for {length}.
1965 56 : Label if_issmi(this), if_isheapnumber(this, Label::kDeferred);
1966 :
1967 : // Default to {string_length} if {length} is undefined.
1968 : {
1969 56 : Label if_isundefined(this, Label::kDeferred), if_isnotundefined(this);
1970 112 : Branch(IsUndefined(length), &if_isundefined, &if_isnotundefined);
1971 :
1972 56 : BIND(&if_isundefined);
1973 112 : var_length = SmiTag(string_length);
1974 56 : Goto(&if_issmi);
1975 :
1976 56 : BIND(&if_isnotundefined);
1977 112 : var_length = ToInteger_Inline(context, length,
1978 56 : CodeStubAssembler::kTruncateMinusZero);
1979 : }
1980 :
1981 : TVARIABLE(IntPtrT, var_result_length);
1982 :
1983 112 : Branch(TaggedIsSmi(var_length.value()), &if_issmi, &if_isheapnumber);
1984 :
1985 : // Set {length} to min(max({length}, 0), {string_length} - {start}
1986 56 : BIND(&if_issmi);
1987 : {
1988 : TNode<IntPtrT> const positive_length =
1989 112 : IntPtrMax(SmiUntag(CAST(var_length.value())), zero);
1990 : TNode<IntPtrT> const minimal_length =
1991 : IntPtrSub(string_length, var_start.value());
1992 112 : var_result_length = IntPtrMin(positive_length, minimal_length);
1993 :
1994 112 : GotoIfNot(IntPtrLessThanOrEqual(var_result_length.value(), zero), &out);
1995 112 : args.PopAndReturn(EmptyStringConstant());
1996 : }
1997 :
1998 56 : BIND(&if_isheapnumber);
1999 : {
2000 : // If {length} is a heap number, it is definitely out of bounds. There are
2001 : // two cases according to the spec: if it is negative, "" is returned; if
2002 : // it is positive, then length is set to {string_length} - {start}.
2003 :
2004 : CSA_ASSERT(this, IsHeapNumber(CAST(var_length.value())));
2005 :
2006 56 : Label if_isnegative(this), if_ispositive(this);
2007 56 : TNode<Float64T> const float_zero = Float64Constant(0.);
2008 : TNode<Float64T> const length_float =
2009 56 : LoadHeapNumberValue(CAST(var_length.value()));
2010 56 : Branch(Float64LessThan(length_float, float_zero), &if_isnegative,
2011 112 : &if_ispositive);
2012 :
2013 56 : BIND(&if_isnegative);
2014 112 : args.PopAndReturn(EmptyStringConstant());
2015 :
2016 56 : BIND(&if_ispositive);
2017 : {
2018 : var_result_length = IntPtrSub(string_length, var_start.value());
2019 112 : GotoIfNot(IntPtrLessThanOrEqual(var_result_length.value(), zero), &out);
2020 112 : args.PopAndReturn(EmptyStringConstant());
2021 56 : }
2022 : }
2023 :
2024 56 : BIND(&out);
2025 : {
2026 : TNode<IntPtrT> const end =
2027 56 : IntPtrAdd(var_start.value(), var_result_length.value());
2028 112 : args.PopAndReturn(SubString(string, var_start.value(), end));
2029 56 : }
2030 56 : }
2031 :
2032 112 : TNode<Smi> StringBuiltinsAssembler::ToSmiBetweenZeroAnd(
2033 : SloppyTNode<Context> context, SloppyTNode<Object> value,
2034 : SloppyTNode<Smi> limit) {
2035 112 : Label out(this);
2036 : TVARIABLE(Smi, var_result);
2037 :
2038 : TNode<Number> const value_int =
2039 112 : ToInteger_Inline(context, value, CodeStubAssembler::kTruncateMinusZero);
2040 :
2041 112 : Label if_issmi(this), if_isnotsmi(this, Label::kDeferred);
2042 224 : Branch(TaggedIsSmi(value_int), &if_issmi, &if_isnotsmi);
2043 :
2044 112 : BIND(&if_issmi);
2045 : {
2046 112 : TNode<Smi> value_smi = CAST(value_int);
2047 112 : Label if_isinbounds(this), if_isoutofbounds(this, Label::kDeferred);
2048 224 : Branch(SmiAbove(value_smi, limit), &if_isoutofbounds, &if_isinbounds);
2049 :
2050 112 : BIND(&if_isinbounds);
2051 : {
2052 : var_result = CAST(value_int);
2053 112 : Goto(&out);
2054 : }
2055 :
2056 112 : BIND(&if_isoutofbounds);
2057 : {
2058 112 : TNode<Smi> const zero = SmiConstant(0);
2059 112 : var_result =
2060 : SelectConstant<Smi>(SmiLessThan(value_smi, zero), zero, limit);
2061 112 : Goto(&out);
2062 112 : }
2063 : }
2064 :
2065 112 : BIND(&if_isnotsmi);
2066 : {
2067 : // {value} is a heap number - in this case, it is definitely out of bounds.
2068 : TNode<HeapNumber> value_int_hn = CAST(value_int);
2069 :
2070 112 : TNode<Float64T> const float_zero = Float64Constant(0.);
2071 112 : TNode<Smi> const smi_zero = SmiConstant(0);
2072 112 : TNode<Float64T> const value_float = LoadHeapNumberValue(value_int_hn);
2073 224 : var_result = SelectConstant<Smi>(Float64LessThan(value_float, float_zero),
2074 : smi_zero, limit);
2075 112 : Goto(&out);
2076 : }
2077 :
2078 112 : BIND(&out);
2079 112 : return var_result.value();
2080 : }
2081 :
2082 280 : TF_BUILTIN(StringSubstring, CodeStubAssembler) {
2083 56 : TNode<String> string = CAST(Parameter(Descriptor::kString));
2084 56 : TNode<IntPtrT> from = UncheckedCast<IntPtrT>(Parameter(Descriptor::kFrom));
2085 56 : TNode<IntPtrT> to = UncheckedCast<IntPtrT>(Parameter(Descriptor::kTo));
2086 :
2087 112 : Return(SubString(string, from, to));
2088 56 : }
2089 :
2090 : // ES6 #sec-string.prototype.substring
2091 280 : TF_BUILTIN(StringPrototypeSubstring, StringBuiltinsAssembler) {
2092 : const int kStartArg = 0;
2093 : const int kEndArg = 1;
2094 :
2095 : Node* const argc =
2096 112 : ChangeInt32ToIntPtr(Parameter(Descriptor::kJSActualArgumentsCount));
2097 56 : CodeStubArguments args(this, argc);
2098 :
2099 112 : Node* const receiver = args.GetReceiver();
2100 112 : Node* const start = args.GetOptionalArgumentValue(kStartArg);
2101 112 : Node* const end = args.GetOptionalArgumentValue(kEndArg);
2102 : Node* const context = Parameter(Descriptor::kContext);
2103 :
2104 : Label out(this);
2105 :
2106 : TVARIABLE(Smi, var_start);
2107 : TVARIABLE(Smi, var_end);
2108 :
2109 : // Check that {receiver} is coercible to Object and convert it to a String.
2110 : TNode<String> const string =
2111 56 : ToThisString(context, receiver, "String.prototype.substring");
2112 :
2113 56 : TNode<Smi> const length = LoadStringLengthAsSmi(string);
2114 :
2115 : // Conversion and bounds-checks for {start}.
2116 112 : var_start = ToSmiBetweenZeroAnd(context, start, length);
2117 :
2118 : // Conversion and bounds-checks for {end}.
2119 : {
2120 : var_end = length;
2121 112 : GotoIf(IsUndefined(end), &out);
2122 :
2123 112 : var_end = ToSmiBetweenZeroAnd(context, end, length);
2124 :
2125 : Label if_endislessthanstart(this);
2126 : Branch(SmiLessThan(var_end.value(), var_start.value()),
2127 112 : &if_endislessthanstart, &out);
2128 :
2129 56 : BIND(&if_endislessthanstart);
2130 : {
2131 : TNode<Smi> const tmp = var_end.value();
2132 : var_end = var_start.value();
2133 : var_start = tmp;
2134 56 : Goto(&out);
2135 56 : }
2136 : }
2137 :
2138 56 : BIND(&out);
2139 : {
2140 : args.PopAndReturn(SubString(string, SmiUntag(var_start.value()),
2141 168 : SmiUntag(var_end.value())));
2142 56 : }
2143 56 : }
2144 :
2145 : // ES6 #sec-string.prototype.trim
2146 280 : TF_BUILTIN(StringPrototypeTrim, StringTrimAssembler) {
2147 : TNode<IntPtrT> argc =
2148 56 : ChangeInt32ToIntPtr(Parameter(Descriptor::kJSActualArgumentsCount));
2149 56 : TNode<Context> context = CAST(Parameter(Descriptor::kContext));
2150 :
2151 56 : Generate(String::kTrim, "String.prototype.trim", argc, context);
2152 56 : }
2153 :
2154 : // https://github.com/tc39/proposal-string-left-right-trim
2155 280 : TF_BUILTIN(StringPrototypeTrimStart, StringTrimAssembler) {
2156 : TNode<IntPtrT> argc =
2157 56 : ChangeInt32ToIntPtr(Parameter(Descriptor::kJSActualArgumentsCount));
2158 56 : TNode<Context> context = CAST(Parameter(Descriptor::kContext));
2159 :
2160 56 : Generate(String::kTrimStart, "String.prototype.trimLeft", argc, context);
2161 56 : }
2162 :
2163 : // https://github.com/tc39/proposal-string-left-right-trim
2164 280 : TF_BUILTIN(StringPrototypeTrimEnd, StringTrimAssembler) {
2165 : TNode<IntPtrT> argc =
2166 56 : ChangeInt32ToIntPtr(Parameter(Descriptor::kJSActualArgumentsCount));
2167 56 : TNode<Context> context = CAST(Parameter(Descriptor::kContext));
2168 :
2169 56 : Generate(String::kTrimEnd, "String.prototype.trimRight", argc, context);
2170 56 : }
2171 :
2172 168 : void StringTrimAssembler::Generate(String::TrimMode mode,
2173 : const char* method_name, TNode<IntPtrT> argc,
2174 : TNode<Context> context) {
2175 336 : Label return_emptystring(this), if_runtime(this);
2176 :
2177 168 : CodeStubArguments arguments(this, argc);
2178 336 : Node* const receiver = arguments.GetReceiver();
2179 :
2180 : // Check that {receiver} is coercible to Object and convert it to a String.
2181 168 : TNode<String> const string = ToThisString(context, receiver, method_name);
2182 168 : TNode<IntPtrT> const string_length = LoadStringLengthAsWord(string);
2183 :
2184 336 : ToDirectStringAssembler to_direct(state(), string);
2185 168 : to_direct.TryToDirect(&if_runtime);
2186 : Node* const string_data = to_direct.PointerToData(&if_runtime);
2187 : Node* const instance_type = to_direct.instance_type();
2188 336 : Node* const is_stringonebyte = IsOneByteStringInstanceType(instance_type);
2189 : Node* const string_data_offset = to_direct.offset();
2190 :
2191 168 : TVARIABLE(IntPtrT, var_start, IntPtrConstant(0));
2192 168 : TVARIABLE(IntPtrT, var_end, IntPtrSub(string_length, IntPtrConstant(1)));
2193 :
2194 168 : if (mode == String::kTrimStart || mode == String::kTrim) {
2195 : ScanForNonWhiteSpaceOrLineTerminator(string_data, string_data_offset,
2196 : is_stringonebyte, &var_start,
2197 112 : string_length, 1, &return_emptystring);
2198 : }
2199 168 : if (mode == String::kTrimEnd || mode == String::kTrim) {
2200 : ScanForNonWhiteSpaceOrLineTerminator(
2201 : string_data, string_data_offset, is_stringonebyte, &var_end,
2202 224 : IntPtrConstant(-1), -1, &return_emptystring);
2203 : }
2204 :
2205 : arguments.PopAndReturn(
2206 : SubString(string, var_start.value(),
2207 504 : IntPtrAdd(var_end.value(), IntPtrConstant(1))));
2208 :
2209 168 : BIND(&if_runtime);
2210 : arguments.PopAndReturn(
2211 168 : CallRuntime(Runtime::kStringTrim, context, string, SmiConstant(mode)));
2212 :
2213 168 : BIND(&return_emptystring);
2214 504 : arguments.PopAndReturn(EmptyStringConstant());
2215 168 : }
2216 :
2217 224 : void StringTrimAssembler::ScanForNonWhiteSpaceOrLineTerminator(
2218 : Node* const string_data, Node* const string_data_offset,
2219 : Node* const is_stringonebyte, Variable* const var_index, Node* const end,
2220 : int increment, Label* const if_none_found) {
2221 448 : Label if_stringisonebyte(this), out(this);
2222 :
2223 224 : GotoIf(is_stringonebyte, &if_stringisonebyte);
2224 :
2225 : // Two Byte String
2226 : BuildLoop(
2227 224 : var_index, end, increment, if_none_found, &out, [&](Node* const index) {
2228 : return Load(
2229 : MachineType::Uint16(), string_data,
2230 1344 : WordShl(IntPtrAdd(index, string_data_offset), IntPtrConstant(1)));
2231 896 : });
2232 :
2233 224 : BIND(&if_stringisonebyte);
2234 : BuildLoop(var_index, end, increment, if_none_found, &out,
2235 224 : [&](Node* const index) {
2236 : return Load(MachineType::Uint8(), string_data,
2237 896 : IntPtrAdd(index, string_data_offset));
2238 896 : });
2239 :
2240 448 : BIND(&out);
2241 224 : }
2242 :
2243 448 : void StringTrimAssembler::BuildLoop(
2244 : Variable* const var_index, Node* const end, int increment,
2245 : Label* const if_none_found, Label* const out,
2246 : const std::function<Node*(Node*)>& get_character) {
2247 448 : Label loop(this, var_index);
2248 448 : Goto(&loop);
2249 448 : BIND(&loop);
2250 : {
2251 448 : Node* const index = var_index->value();
2252 896 : GotoIf(IntPtrEqual(index, end), if_none_found);
2253 : GotoIfNotWhiteSpaceOrLineTerminator(
2254 448 : UncheckedCast<Uint32T>(get_character(index)), out);
2255 448 : Increment(var_index, increment);
2256 448 : Goto(&loop);
2257 448 : }
2258 448 : }
2259 :
2260 453 : void StringTrimAssembler::GotoIfNotWhiteSpaceOrLineTerminator(
2261 : Node* const char_code, Label* const if_not_whitespace) {
2262 453 : Label out(this);
2263 :
2264 : // 0x0020 - SPACE (Intentionally out of order to fast path a commmon case)
2265 1359 : GotoIf(Word32Equal(char_code, Int32Constant(0x0020)), &out);
2266 :
2267 : // 0x0009 - HORIZONTAL TAB
2268 1359 : GotoIf(Uint32LessThan(char_code, Int32Constant(0x0009)), if_not_whitespace);
2269 : // 0x000A - LINE FEED OR NEW LINE
2270 : // 0x000B - VERTICAL TAB
2271 : // 0x000C - FORMFEED
2272 : // 0x000D - HORIZONTAL TAB
2273 1359 : GotoIf(Uint32LessThanOrEqual(char_code, Int32Constant(0x000D)), &out);
2274 :
2275 : // Common Non-whitespace characters
2276 1359 : GotoIf(Uint32LessThan(char_code, Int32Constant(0x00A0)), if_not_whitespace);
2277 :
2278 : // 0x00A0 - NO-BREAK SPACE
2279 1359 : GotoIf(Word32Equal(char_code, Int32Constant(0x00A0)), &out);
2280 :
2281 : // 0x1680 - Ogham Space Mark
2282 1359 : GotoIf(Word32Equal(char_code, Int32Constant(0x1680)), &out);
2283 :
2284 : // 0x2000 - EN QUAD
2285 1359 : GotoIf(Uint32LessThan(char_code, Int32Constant(0x2000)), if_not_whitespace);
2286 : // 0x2001 - EM QUAD
2287 : // 0x2002 - EN SPACE
2288 : // 0x2003 - EM SPACE
2289 : // 0x2004 - THREE-PER-EM SPACE
2290 : // 0x2005 - FOUR-PER-EM SPACE
2291 : // 0x2006 - SIX-PER-EM SPACE
2292 : // 0x2007 - FIGURE SPACE
2293 : // 0x2008 - PUNCTUATION SPACE
2294 : // 0x2009 - THIN SPACE
2295 : // 0x200A - HAIR SPACE
2296 1359 : GotoIf(Uint32LessThanOrEqual(char_code, Int32Constant(0x200A)), &out);
2297 :
2298 : // 0x2028 - LINE SEPARATOR
2299 1359 : GotoIf(Word32Equal(char_code, Int32Constant(0x2028)), &out);
2300 : // 0x2029 - PARAGRAPH SEPARATOR
2301 1359 : GotoIf(Word32Equal(char_code, Int32Constant(0x2029)), &out);
2302 : // 0x202F - NARROW NO-BREAK SPACE
2303 1359 : GotoIf(Word32Equal(char_code, Int32Constant(0x202F)), &out);
2304 : // 0x205F - MEDIUM MATHEMATICAL SPACE
2305 1359 : GotoIf(Word32Equal(char_code, Int32Constant(0x205F)), &out);
2306 : // 0xFEFF - BYTE ORDER MARK
2307 1359 : GotoIf(Word32Equal(char_code, Int32Constant(0xFEFF)), &out);
2308 : // 0x3000 - IDEOGRAPHIC SPACE
2309 906 : Branch(Word32Equal(char_code, Int32Constant(0x3000)), &out,
2310 906 : if_not_whitespace);
2311 :
2312 453 : BIND(&out);
2313 453 : }
2314 :
2315 : // ES6 #sec-string.prototype.tostring
2316 168 : TF_BUILTIN(StringPrototypeToString, CodeStubAssembler) {
2317 : Node* context = Parameter(Descriptor::kContext);
2318 : Node* receiver = Parameter(Descriptor::kReceiver);
2319 :
2320 : Node* result = ToThisValue(context, receiver, PrimitiveType::kString,
2321 56 : "String.prototype.toString");
2322 56 : Return(result);
2323 56 : }
2324 :
2325 : // ES6 #sec-string.prototype.valueof
2326 168 : TF_BUILTIN(StringPrototypeValueOf, CodeStubAssembler) {
2327 : Node* context = Parameter(Descriptor::kContext);
2328 : Node* receiver = Parameter(Descriptor::kReceiver);
2329 :
2330 : Node* result = ToThisValue(context, receiver, PrimitiveType::kString,
2331 56 : "String.prototype.valueOf");
2332 56 : Return(result);
2333 56 : }
2334 :
2335 168 : TF_BUILTIN(StringPrototypeIterator, CodeStubAssembler) {
2336 : Node* context = Parameter(Descriptor::kContext);
2337 : Node* receiver = Parameter(Descriptor::kReceiver);
2338 :
2339 : Node* string =
2340 112 : ToThisString(context, receiver, "String.prototype[Symbol.iterator]");
2341 :
2342 112 : Node* native_context = LoadNativeContext(context);
2343 : Node* map = LoadContextElement(native_context,
2344 112 : Context::INITIAL_STRING_ITERATOR_MAP_INDEX);
2345 112 : Node* iterator = Allocate(JSStringIterator::kSize);
2346 56 : StoreMapNoWriteBarrier(iterator, map);
2347 : StoreObjectFieldRoot(iterator, JSValue::kPropertiesOrHashOffset,
2348 56 : RootIndex::kEmptyFixedArray);
2349 : StoreObjectFieldRoot(iterator, JSObject::kElementsOffset,
2350 56 : RootIndex::kEmptyFixedArray);
2351 : StoreObjectFieldNoWriteBarrier(iterator, JSStringIterator::kStringOffset,
2352 56 : string);
2353 112 : Node* index = SmiConstant(0);
2354 : StoreObjectFieldNoWriteBarrier(iterator, JSStringIterator::kNextIndexOffset,
2355 56 : index);
2356 56 : Return(iterator);
2357 56 : }
2358 :
2359 : // Return the |word32| codepoint at {index}. Supports SeqStrings and
2360 : // ExternalStrings.
2361 280 : TNode<Int32T> StringBuiltinsAssembler::LoadSurrogatePairAt(
2362 : SloppyTNode<String> string, SloppyTNode<IntPtrT> length,
2363 : SloppyTNode<IntPtrT> index, UnicodeEncoding encoding) {
2364 560 : Label handle_surrogate_pair(this), return_result(this);
2365 : TVARIABLE(Int32T, var_result);
2366 : TVARIABLE(Int32T, var_trail);
2367 280 : var_result = StringCharCodeAt(string, index);
2368 280 : var_trail = Int32Constant(0);
2369 :
2370 560 : GotoIf(Word32NotEqual(Word32And(var_result.value(), Int32Constant(0xFC00)),
2371 1120 : Int32Constant(0xD800)),
2372 560 : &return_result);
2373 280 : TNode<IntPtrT> next_index = IntPtrAdd(index, IntPtrConstant(1));
2374 :
2375 560 : GotoIfNot(IntPtrLessThan(next_index, length), &return_result);
2376 560 : var_trail = StringCharCodeAt(string, next_index);
2377 560 : Branch(Word32Equal(Word32And(var_trail.value(), Int32Constant(0xFC00)),
2378 1120 : Int32Constant(0xDC00)),
2379 560 : &handle_surrogate_pair, &return_result);
2380 :
2381 280 : BIND(&handle_surrogate_pair);
2382 : {
2383 : TNode<Int32T> lead = var_result.value();
2384 : TNode<Int32T> trail = var_trail.value();
2385 :
2386 : // Check that this path is only taken if a surrogate pair is found
2387 : CSA_SLOW_ASSERT(this,
2388 : Uint32GreaterThanOrEqual(lead, Int32Constant(0xD800)));
2389 : CSA_SLOW_ASSERT(this, Uint32LessThan(lead, Int32Constant(0xDC00)));
2390 : CSA_SLOW_ASSERT(this,
2391 : Uint32GreaterThanOrEqual(trail, Int32Constant(0xDC00)));
2392 : CSA_SLOW_ASSERT(this, Uint32LessThan(trail, Int32Constant(0xE000)));
2393 :
2394 280 : switch (encoding) {
2395 : case UnicodeEncoding::UTF16:
2396 672 : var_result = Signed(Word32Or(
2397 : // Need to swap the order for big-endian platforms
2398 : #if V8_TARGET_BIG_ENDIAN
2399 : Word32Shl(lead, Int32Constant(16)), trail));
2400 : #else
2401 336 : Word32Shl(trail, Int32Constant(16)), lead));
2402 : #endif
2403 168 : break;
2404 :
2405 : case UnicodeEncoding::UTF32: {
2406 : // Convert UTF16 surrogate pair into |word32| code point, encoded as
2407 : // UTF32.
2408 : TNode<Int32T> surrogate_offset =
2409 112 : Int32Constant(0x10000 - (0xD800 << 10) - 0xDC00);
2410 :
2411 : // (lead << 10) + trail + SURROGATE_OFFSET
2412 448 : var_result = Signed(Int32Add(Word32Shl(lead, Int32Constant(10)),
2413 : Int32Add(trail, surrogate_offset)));
2414 : break;
2415 : }
2416 : }
2417 280 : Goto(&return_result);
2418 : }
2419 :
2420 280 : BIND(&return_result);
2421 280 : return var_result.value();
2422 : }
2423 :
2424 : // ES6 #sec-%stringiteratorprototype%.next
2425 280 : TF_BUILTIN(StringIteratorPrototypeNext, StringBuiltinsAssembler) {
2426 56 : VARIABLE(var_value, MachineRepresentation::kTagged);
2427 112 : VARIABLE(var_done, MachineRepresentation::kTagged);
2428 :
2429 112 : var_value.Bind(UndefinedConstant());
2430 112 : var_done.Bind(TrueConstant());
2431 :
2432 56 : Label throw_bad_receiver(this), next_codepoint(this), return_result(this);
2433 :
2434 : Node* context = Parameter(Descriptor::kContext);
2435 : Node* iterator = Parameter(Descriptor::kReceiver);
2436 :
2437 112 : GotoIf(TaggedIsSmi(iterator), &throw_bad_receiver);
2438 : GotoIfNot(
2439 112 : InstanceTypeEqual(LoadInstanceType(iterator), JS_STRING_ITERATOR_TYPE),
2440 112 : &throw_bad_receiver);
2441 :
2442 : Node* string = LoadObjectField(iterator, JSStringIterator::kStringOffset);
2443 : TNode<IntPtrT> position = SmiUntag(
2444 56 : CAST(LoadObjectField(iterator, JSStringIterator::kNextIndexOffset)));
2445 56 : TNode<IntPtrT> length = LoadStringLengthAsWord(string);
2446 :
2447 112 : Branch(IntPtrLessThan(position, length), &next_codepoint, &return_result);
2448 :
2449 56 : BIND(&next_codepoint);
2450 : {
2451 : UnicodeEncoding encoding = UnicodeEncoding::UTF16;
2452 56 : TNode<Int32T> ch = LoadSurrogatePairAt(string, length, position, encoding);
2453 56 : TNode<String> value = StringFromSingleCodePoint(ch, encoding);
2454 56 : var_value.Bind(value);
2455 56 : TNode<IntPtrT> length = LoadStringLengthAsWord(value);
2456 : StoreObjectFieldNoWriteBarrier(iterator, JSStringIterator::kNextIndexOffset,
2457 112 : SmiTag(Signed(IntPtrAdd(position, length))));
2458 112 : var_done.Bind(FalseConstant());
2459 56 : Goto(&return_result);
2460 : }
2461 :
2462 56 : BIND(&return_result);
2463 : {
2464 : Node* result =
2465 56 : AllocateJSIteratorResult(context, var_value.value(), var_done.value());
2466 56 : Return(result);
2467 : }
2468 :
2469 56 : BIND(&throw_bad_receiver);
2470 : {
2471 : // The {receiver} is not a valid JSGeneratorObject.
2472 : ThrowTypeError(context, MessageTemplate::kIncompatibleMethodReceiver,
2473 112 : StringConstant("String Iterator.prototype.next"), iterator);
2474 56 : }
2475 56 : }
2476 :
2477 112 : void StringBuiltinsAssembler::BranchIfStringPrimitiveWithNoCustomIteration(
2478 : TNode<Object> object, TNode<Context> context, Label* if_true,
2479 : Label* if_false) {
2480 224 : GotoIf(TaggedIsSmi(object), if_false);
2481 224 : GotoIfNot(IsString(CAST(object)), if_false);
2482 :
2483 : // Check that the String iterator hasn't been modified in a way that would
2484 : // affect iteration.
2485 224 : Node* protector_cell = LoadRoot(RootIndex::kStringIteratorProtector);
2486 : DCHECK(isolate()->heap()->string_iterator_protector()->IsPropertyCell());
2487 : Branch(WordEqual(LoadObjectField(protector_cell, PropertyCell::kValueOffset),
2488 112 : SmiConstant(Isolate::kProtectorValid)),
2489 112 : if_true, if_false);
2490 112 : }
2491 :
2492 : // This function assumes StringPrimitiveWithNoCustomIteration is true.
2493 56 : TNode<JSArray> StringBuiltinsAssembler::StringToList(TNode<Context> context,
2494 : TNode<String> string) {
2495 : const ElementsKind kind = PACKED_ELEMENTS;
2496 56 : const TNode<IntPtrT> length = LoadStringLengthAsWord(string);
2497 :
2498 : TNode<Map> array_map =
2499 112 : LoadJSArrayElementsMap(kind, LoadNativeContext(context));
2500 : TNode<JSArray> array =
2501 : AllocateJSArray(kind, array_map, length, SmiTag(length), nullptr,
2502 56 : INTPTR_PARAMETERS, kAllowLargeObjectAllocation);
2503 : TNode<FixedArrayBase> elements = LoadElements(array);
2504 :
2505 : const int first_element_offset = FixedArray::kHeaderSize - kHeapObjectTag;
2506 : TNode<IntPtrT> first_to_element_offset =
2507 112 : ElementOffsetFromIndex(IntPtrConstant(0), kind, INTPTR_PARAMETERS, 0);
2508 : TNode<IntPtrT> first_offset =
2509 56 : IntPtrAdd(first_to_element_offset, IntPtrConstant(first_element_offset));
2510 : TVARIABLE(IntPtrT, var_offset, first_offset);
2511 56 : TVARIABLE(IntPtrT, var_position, IntPtrConstant(0));
2512 168 : Label done(this), next_codepoint(this, {&var_position, &var_offset});
2513 :
2514 56 : Goto(&next_codepoint);
2515 :
2516 56 : BIND(&next_codepoint);
2517 : {
2518 : // Loop condition.
2519 112 : GotoIfNot(IntPtrLessThan(var_position.value(), length), &done);
2520 : const UnicodeEncoding encoding = UnicodeEncoding::UTF16;
2521 : TNode<Int32T> ch =
2522 56 : LoadSurrogatePairAt(string, length, var_position.value(), encoding);
2523 56 : TNode<String> value = StringFromSingleCodePoint(ch, encoding);
2524 :
2525 56 : Store(elements, var_offset.value(), value);
2526 :
2527 : // Increment the position.
2528 56 : TNode<IntPtrT> ch_length = LoadStringLengthAsWord(value);
2529 : var_position = IntPtrAdd(var_position.value(), ch_length);
2530 : // Increment the array offset and continue the loop.
2531 56 : var_offset = IntPtrAdd(var_offset.value(), IntPtrConstant(kTaggedSize));
2532 56 : Goto(&next_codepoint);
2533 : }
2534 :
2535 56 : BIND(&done);
2536 : TNode<IntPtrT> new_length = IntPtrDiv(
2537 112 : IntPtrSub(var_offset.value(), first_offset), IntPtrConstant(kTaggedSize));
2538 : CSA_ASSERT(this, IntPtrGreaterThanOrEqual(new_length, IntPtrConstant(0)));
2539 : CSA_ASSERT(this, IntPtrGreaterThanOrEqual(length, new_length));
2540 : StoreObjectFieldNoWriteBarrier(array, JSArray::kLengthOffset,
2541 112 : SmiTag(new_length));
2542 :
2543 56 : return UncheckedCast<JSArray>(array);
2544 : }
2545 :
2546 280 : TF_BUILTIN(StringToList, StringBuiltinsAssembler) {
2547 56 : TNode<Context> context = CAST(Parameter(Descriptor::kContext));
2548 56 : TNode<String> string = CAST(Parameter(Descriptor::kSource));
2549 112 : Return(StringToList(context, string));
2550 56 : }
2551 :
2552 : // -----------------------------------------------------------------------------
2553 : // ES6 section B.2.3 Additional Properties of the String.prototype object
2554 :
2555 : class StringHtmlAssembler : public StringBuiltinsAssembler {
2556 : public:
2557 : explicit StringHtmlAssembler(compiler::CodeAssemblerState* state)
2558 : : StringBuiltinsAssembler(state) {}
2559 :
2560 : protected:
2561 504 : void Generate(Node* const context, Node* const receiver,
2562 : const char* method_name, const char* tag_name) {
2563 1008 : Node* const string = ToThisString(context, receiver, method_name);
2564 1512 : std::string open_tag = "<" + std::string(tag_name) + ">";
2565 1512 : std::string close_tag = "</" + std::string(tag_name) + ">";
2566 :
2567 504 : Node* strings[] = {StringConstant(open_tag.c_str()), string,
2568 1512 : StringConstant(close_tag.c_str())};
2569 1008 : Return(ConcatStrings(context, strings, arraysize(strings)));
2570 504 : }
2571 :
2572 224 : void GenerateWithAttribute(Node* const context, Node* const receiver,
2573 : const char* method_name, const char* tag_name,
2574 : const char* attr, Node* const value) {
2575 448 : Node* const string = ToThisString(context, receiver, method_name);
2576 : Node* const value_string =
2577 448 : EscapeQuotes(context, ToString_Inline(context, value));
2578 : std::string open_tag_attr =
2579 1568 : "<" + std::string(tag_name) + " " + std::string(attr) + "=\"";
2580 672 : std::string close_tag = "</" + std::string(tag_name) + ">";
2581 :
2582 224 : Node* strings[] = {StringConstant(open_tag_attr.c_str()), value_string,
2583 : StringConstant("\">"), string,
2584 896 : StringConstant(close_tag.c_str())};
2585 448 : Return(ConcatStrings(context, strings, arraysize(strings)));
2586 224 : }
2587 :
2588 728 : Node* ConcatStrings(Node* const context, Node** strings, int len) {
2589 728 : VARIABLE(var_result, MachineRepresentation::kTagged, strings[0]);
2590 2632 : for (int i = 1; i < len; i++) {
2591 : var_result.Bind(CallStub(CodeFactory::StringAdd(isolate()), context,
2592 7616 : var_result.value(), strings[i]));
2593 : }
2594 728 : return var_result.value();
2595 : }
2596 :
2597 224 : Node* EscapeQuotes(Node* const context, Node* const string) {
2598 : CSA_ASSERT(this, IsString(string));
2599 : Node* const regexp_function = LoadContextElement(
2600 672 : LoadNativeContext(context), Context::REGEXP_FUNCTION_INDEX);
2601 : Node* const initial_map = LoadObjectField(
2602 : regexp_function, JSFunction::kPrototypeOrInitialMapOffset);
2603 : // TODO(pwong): Refactor to not allocate RegExp
2604 : Node* const regexp =
2605 : CallRuntime(Runtime::kRegExpInitializeAndCompile, context,
2606 : AllocateJSObjectFromMap(initial_map), StringConstant("\""),
2607 672 : StringConstant("g"));
2608 :
2609 : return CallRuntime(Runtime::kRegExpInternalReplace, context, regexp, string,
2610 448 : StringConstant("""));
2611 : }
2612 : };
2613 :
2614 : // ES6 #sec-string.prototype.anchor
2615 224 : TF_BUILTIN(StringPrototypeAnchor, StringHtmlAssembler) {
2616 : Node* const context = Parameter(Descriptor::kContext);
2617 : Node* const receiver = Parameter(Descriptor::kReceiver);
2618 : Node* const value = Parameter(Descriptor::kValue);
2619 : GenerateWithAttribute(context, receiver, "String.prototype.anchor", "a",
2620 56 : "name", value);
2621 56 : }
2622 :
2623 : // ES6 #sec-string.prototype.big
2624 224 : TF_BUILTIN(StringPrototypeBig, StringHtmlAssembler) {
2625 : Node* const context = Parameter(Descriptor::kContext);
2626 : Node* const receiver = Parameter(Descriptor::kReceiver);
2627 56 : Generate(context, receiver, "String.prototype.big", "big");
2628 56 : }
2629 :
2630 : // ES6 #sec-string.prototype.blink
2631 224 : TF_BUILTIN(StringPrototypeBlink, StringHtmlAssembler) {
2632 : Node* const context = Parameter(Descriptor::kContext);
2633 : Node* const receiver = Parameter(Descriptor::kReceiver);
2634 56 : Generate(context, receiver, "String.prototype.blink", "blink");
2635 56 : }
2636 :
2637 : // ES6 #sec-string.prototype.bold
2638 224 : TF_BUILTIN(StringPrototypeBold, StringHtmlAssembler) {
2639 : Node* const context = Parameter(Descriptor::kContext);
2640 : Node* const receiver = Parameter(Descriptor::kReceiver);
2641 56 : Generate(context, receiver, "String.prototype.bold", "b");
2642 56 : }
2643 :
2644 : // ES6 #sec-string.prototype.fontcolor
2645 224 : TF_BUILTIN(StringPrototypeFontcolor, StringHtmlAssembler) {
2646 : Node* const context = Parameter(Descriptor::kContext);
2647 : Node* const receiver = Parameter(Descriptor::kReceiver);
2648 : Node* const value = Parameter(Descriptor::kValue);
2649 : GenerateWithAttribute(context, receiver, "String.prototype.fontcolor", "font",
2650 56 : "color", value);
2651 56 : }
2652 :
2653 : // ES6 #sec-string.prototype.fontsize
2654 224 : TF_BUILTIN(StringPrototypeFontsize, StringHtmlAssembler) {
2655 : Node* const context = Parameter(Descriptor::kContext);
2656 : Node* const receiver = Parameter(Descriptor::kReceiver);
2657 : Node* const value = Parameter(Descriptor::kValue);
2658 : GenerateWithAttribute(context, receiver, "String.prototype.fontsize", "font",
2659 56 : "size", value);
2660 56 : }
2661 :
2662 : // ES6 #sec-string.prototype.fixed
2663 224 : TF_BUILTIN(StringPrototypeFixed, StringHtmlAssembler) {
2664 : Node* const context = Parameter(Descriptor::kContext);
2665 : Node* const receiver = Parameter(Descriptor::kReceiver);
2666 56 : Generate(context, receiver, "String.prototype.fixed", "tt");
2667 56 : }
2668 :
2669 : // ES6 #sec-string.prototype.italics
2670 224 : TF_BUILTIN(StringPrototypeItalics, StringHtmlAssembler) {
2671 : Node* const context = Parameter(Descriptor::kContext);
2672 : Node* const receiver = Parameter(Descriptor::kReceiver);
2673 56 : Generate(context, receiver, "String.prototype.italics", "i");
2674 56 : }
2675 :
2676 : // ES6 #sec-string.prototype.link
2677 224 : TF_BUILTIN(StringPrototypeLink, StringHtmlAssembler) {
2678 : Node* const context = Parameter(Descriptor::kContext);
2679 : Node* const receiver = Parameter(Descriptor::kReceiver);
2680 : Node* const value = Parameter(Descriptor::kValue);
2681 : GenerateWithAttribute(context, receiver, "String.prototype.link", "a", "href",
2682 56 : value);
2683 56 : }
2684 :
2685 : // ES6 #sec-string.prototype.small
2686 224 : TF_BUILTIN(StringPrototypeSmall, StringHtmlAssembler) {
2687 : Node* const context = Parameter(Descriptor::kContext);
2688 : Node* const receiver = Parameter(Descriptor::kReceiver);
2689 56 : Generate(context, receiver, "String.prototype.small", "small");
2690 56 : }
2691 :
2692 : // ES6 #sec-string.prototype.strike
2693 224 : TF_BUILTIN(StringPrototypeStrike, StringHtmlAssembler) {
2694 : Node* const context = Parameter(Descriptor::kContext);
2695 : Node* const receiver = Parameter(Descriptor::kReceiver);
2696 56 : Generate(context, receiver, "String.prototype.strike", "strike");
2697 56 : }
2698 :
2699 : // ES6 #sec-string.prototype.sub
2700 224 : TF_BUILTIN(StringPrototypeSub, StringHtmlAssembler) {
2701 : Node* const context = Parameter(Descriptor::kContext);
2702 : Node* const receiver = Parameter(Descriptor::kReceiver);
2703 56 : Generate(context, receiver, "String.prototype.sub", "sub");
2704 56 : }
2705 :
2706 : // ES6 #sec-string.prototype.sup
2707 224 : TF_BUILTIN(StringPrototypeSup, StringHtmlAssembler) {
2708 : Node* const context = Parameter(Descriptor::kContext);
2709 : Node* const receiver = Parameter(Descriptor::kReceiver);
2710 56 : Generate(context, receiver, "String.prototype.sup", "sup");
2711 56 : }
2712 :
2713 : } // namespace internal
2714 94089 : } // namespace v8
|