/
js-native-context-specialization.cc
3552 lines (3198 loc) Β· 150 KB
/
js-native-context-specialization.cc
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// Copyright 2015 the V8 project authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "src/compiler/js-native-context-specialization.h"
#include "src/api/api-inl.h"
#include "src/base/optional.h"
#include "src/builtins/accessors.h"
#include "src/codegen/code-factory.h"
#include "src/codegen/string-constants.h"
#include "src/compiler/access-builder.h"
#include "src/compiler/access-info.h"
#include "src/compiler/allocation-builder-inl.h"
#include "src/compiler/allocation-builder.h"
#include "src/compiler/compilation-dependencies.h"
#include "src/compiler/js-graph.h"
#include "src/compiler/js-operator.h"
#include "src/compiler/linkage.h"
#include "src/compiler/map-inference.h"
#include "src/compiler/node-matchers.h"
#include "src/compiler/property-access-builder.h"
#include "src/compiler/type-cache.h"
#include "src/execution/isolate-inl.h"
#include "src/objects/feedback-vector.h"
#include "src/objects/field-index-inl.h"
#include "src/objects/heap-number.h"
#include "src/objects/js-array-buffer-inl.h"
#include "src/objects/js-array-inl.h"
#include "src/objects/templates.h"
namespace v8 {
namespace internal {
namespace compiler {
namespace {
bool HasNumberMaps(JSHeapBroker* broker, ZoneVector<Handle<Map>> const& maps) {
for (auto map : maps) {
MapRef map_ref = MakeRef(broker, map);
if (map_ref.IsHeapNumberMap()) return true;
}
return false;
}
bool HasOnlyJSArrayMaps(JSHeapBroker* broker,
ZoneVector<Handle<Map>> const& maps) {
for (auto map : maps) {
MapRef map_ref = MakeRef(broker, map);
if (!map_ref.IsJSArrayMap()) return false;
}
return true;
}
} // namespace
JSNativeContextSpecialization::JSNativeContextSpecialization(
Editor* editor, JSGraph* jsgraph, JSHeapBroker* broker, Flags flags,
CompilationDependencies* dependencies, Zone* zone, Zone* shared_zone)
: AdvancedReducer(editor),
jsgraph_(jsgraph),
broker_(broker),
flags_(flags),
global_object_(broker->target_native_context().global_object().object()),
global_proxy_(
broker->target_native_context().global_proxy_object().object()),
dependencies_(dependencies),
zone_(zone),
shared_zone_(shared_zone),
type_cache_(TypeCache::Get()) {}
Reduction JSNativeContextSpecialization::Reduce(Node* node) {
switch (node->opcode()) {
case IrOpcode::kJSAdd:
return ReduceJSAdd(node);
case IrOpcode::kJSAsyncFunctionEnter:
return ReduceJSAsyncFunctionEnter(node);
case IrOpcode::kJSAsyncFunctionReject:
return ReduceJSAsyncFunctionReject(node);
case IrOpcode::kJSAsyncFunctionResolve:
return ReduceJSAsyncFunctionResolve(node);
case IrOpcode::kJSGetSuperConstructor:
return ReduceJSGetSuperConstructor(node);
case IrOpcode::kJSInstanceOf:
return ReduceJSInstanceOf(node);
case IrOpcode::kJSHasInPrototypeChain:
return ReduceJSHasInPrototypeChain(node);
case IrOpcode::kJSOrdinaryHasInstance:
return ReduceJSOrdinaryHasInstance(node);
case IrOpcode::kJSPromiseResolve:
return ReduceJSPromiseResolve(node);
case IrOpcode::kJSResolvePromise:
return ReduceJSResolvePromise(node);
case IrOpcode::kJSLoadGlobal:
return ReduceJSLoadGlobal(node);
case IrOpcode::kJSStoreGlobal:
return ReduceJSStoreGlobal(node);
case IrOpcode::kJSLoadNamed:
return ReduceJSLoadNamed(node);
case IrOpcode::kJSLoadNamedFromSuper:
return ReduceJSLoadNamedFromSuper(node);
case IrOpcode::kJSStoreNamed:
return ReduceJSStoreNamed(node);
case IrOpcode::kJSHasProperty:
return ReduceJSHasProperty(node);
case IrOpcode::kJSLoadProperty:
return ReduceJSLoadProperty(node);
case IrOpcode::kJSStoreProperty:
return ReduceJSStoreProperty(node);
case IrOpcode::kJSStoreNamedOwn:
return ReduceJSStoreNamedOwn(node);
case IrOpcode::kJSStoreDataPropertyInLiteral:
return ReduceJSStoreDataPropertyInLiteral(node);
case IrOpcode::kJSStoreInArrayLiteral:
return ReduceJSStoreInArrayLiteral(node);
case IrOpcode::kJSToObject:
return ReduceJSToObject(node);
case IrOpcode::kJSToString:
return ReduceJSToString(node);
case IrOpcode::kJSGetIterator:
return ReduceJSGetIterator(node);
default:
break;
}
return NoChange();
}
// static
base::Optional<size_t> JSNativeContextSpecialization::GetMaxStringLength(
JSHeapBroker* broker, Node* node) {
if (node->opcode() == IrOpcode::kDelayedStringConstant) {
return StringConstantBaseOf(node->op())->GetMaxStringConstantLength();
}
HeapObjectMatcher matcher(node);
if (matcher.HasResolvedValue() && matcher.Ref(broker).IsString()) {
StringRef input = matcher.Ref(broker).AsString();
return input.length();
}
NumberMatcher number_matcher(node);
if (number_matcher.HasResolvedValue()) {
return kMaxDoubleStringLength;
}
// We don't support objects with possibly monkey-patched prototype.toString
// as it might have side-effects, so we shouldn't attempt lowering them.
return base::nullopt;
}
Reduction JSNativeContextSpecialization::ReduceJSToString(Node* node) {
DCHECK_EQ(IrOpcode::kJSToString, node->opcode());
Node* const input = node->InputAt(0);
Reduction reduction;
HeapObjectMatcher matcher(input);
if (matcher.HasResolvedValue() && matcher.Ref(broker()).IsString()) {
reduction = Changed(input); // JSToString(x:string) => x
ReplaceWithValue(node, reduction.replacement());
return reduction;
}
// TODO(turbofan): This optimization is weaker than what we used to have
// in js-typed-lowering for OrderedNumbers. We don't have types here though,
// so alternative approach should be designed if this causes performance
// regressions and the stronger optimization should be re-implemented.
NumberMatcher number_matcher(input);
if (number_matcher.HasResolvedValue()) {
const StringConstantBase* base = shared_zone()->New<NumberToStringConstant>(
number_matcher.ResolvedValue());
reduction =
Replace(graph()->NewNode(common()->DelayedStringConstant(base)));
ReplaceWithValue(node, reduction.replacement());
return reduction;
}
return NoChange();
}
base::Optional<const StringConstantBase*>
JSNativeContextSpecialization::CreateDelayedStringConstant(Node* node) {
if (node->opcode() == IrOpcode::kDelayedStringConstant) {
return StringConstantBaseOf(node->op());
} else {
NumberMatcher number_matcher(node);
if (number_matcher.HasResolvedValue()) {
return shared_zone()->New<NumberToStringConstant>(
number_matcher.ResolvedValue());
} else {
HeapObjectMatcher matcher(node);
if (matcher.HasResolvedValue() && matcher.Ref(broker()).IsString()) {
StringRef s = matcher.Ref(broker()).AsString();
if (!s.length().has_value()) return base::nullopt;
return shared_zone()->New<StringLiteral>(
s.object(), static_cast<size_t>(s.length().value()));
} else {
UNREACHABLE();
}
}
}
}
namespace {
bool IsStringConstant(JSHeapBroker* broker, Node* node) {
if (node->opcode() == IrOpcode::kDelayedStringConstant) {
return true;
}
HeapObjectMatcher matcher(node);
return matcher.HasResolvedValue() && matcher.Ref(broker).IsString();
}
} // namespace
Reduction JSNativeContextSpecialization::ReduceJSAsyncFunctionEnter(
Node* node) {
DCHECK_EQ(IrOpcode::kJSAsyncFunctionEnter, node->opcode());
Node* closure = NodeProperties::GetValueInput(node, 0);
Node* receiver = NodeProperties::GetValueInput(node, 1);
Node* context = NodeProperties::GetContextInput(node);
Node* frame_state = NodeProperties::GetFrameStateInput(node);
Node* effect = NodeProperties::GetEffectInput(node);
Node* control = NodeProperties::GetControlInput(node);
if (!dependencies()->DependOnPromiseHookProtector()) return NoChange();
// Create the promise for the async function.
Node* promise = effect =
graph()->NewNode(javascript()->CreatePromise(), context, effect);
// Create the JSAsyncFunctionObject based on the SharedFunctionInfo
// extracted from the top-most frame in {frame_state}.
SharedFunctionInfoRef shared = MakeRef(
broker(),
FrameStateInfoOf(frame_state->op()).shared_info().ToHandleChecked());
DCHECK(shared.is_compiled());
int register_count = shared.internal_formal_parameter_count() +
shared.GetBytecodeArray().register_count();
MapRef fixed_array_map = MakeRef(broker(), factory()->fixed_array_map());
AllocationBuilder ab(jsgraph(), effect, control);
if (!ab.CanAllocateArray(register_count, fixed_array_map)) {
return NoChange();
}
Node* value = effect =
graph()->NewNode(javascript()->CreateAsyncFunctionObject(register_count),
closure, receiver, promise, context, effect, control);
ReplaceWithValue(node, value, effect, control);
return Replace(value);
}
Reduction JSNativeContextSpecialization::ReduceJSAsyncFunctionReject(
Node* node) {
DCHECK_EQ(IrOpcode::kJSAsyncFunctionReject, node->opcode());
Node* async_function_object = NodeProperties::GetValueInput(node, 0);
Node* reason = NodeProperties::GetValueInput(node, 1);
Node* context = NodeProperties::GetContextInput(node);
Node* frame_state = NodeProperties::GetFrameStateInput(node);
Node* effect = NodeProperties::GetEffectInput(node);
Node* control = NodeProperties::GetControlInput(node);
if (!dependencies()->DependOnPromiseHookProtector()) return NoChange();
// Load the promise from the {async_function_object}.
Node* promise = effect = graph()->NewNode(
simplified()->LoadField(AccessBuilder::ForJSAsyncFunctionObjectPromise()),
async_function_object, effect, control);
// Create a nested frame state inside the current method's most-recent
// {frame_state} that will ensure that lazy deoptimizations at this
// point will still return the {promise} instead of the result of the
// JSRejectPromise operation (which yields undefined).
Node* parameters[] = {promise};
frame_state = CreateStubBuiltinContinuationFrameState(
jsgraph(), Builtin::kAsyncFunctionLazyDeoptContinuation, context,
parameters, arraysize(parameters), frame_state,
ContinuationFrameStateMode::LAZY);
// Disable the additional debug event for the rejection since a
// debug event already happend for the exception that got us here.
Node* debug_event = jsgraph()->FalseConstant();
effect = graph()->NewNode(javascript()->RejectPromise(), promise, reason,
debug_event, context, frame_state, effect, control);
ReplaceWithValue(node, promise, effect, control);
return Replace(promise);
}
Reduction JSNativeContextSpecialization::ReduceJSAsyncFunctionResolve(
Node* node) {
DCHECK_EQ(IrOpcode::kJSAsyncFunctionResolve, node->opcode());
Node* async_function_object = NodeProperties::GetValueInput(node, 0);
Node* value = NodeProperties::GetValueInput(node, 1);
Node* context = NodeProperties::GetContextInput(node);
Node* frame_state = NodeProperties::GetFrameStateInput(node);
Node* effect = NodeProperties::GetEffectInput(node);
Node* control = NodeProperties::GetControlInput(node);
if (!dependencies()->DependOnPromiseHookProtector()) return NoChange();
// Load the promise from the {async_function_object}.
Node* promise = effect = graph()->NewNode(
simplified()->LoadField(AccessBuilder::ForJSAsyncFunctionObjectPromise()),
async_function_object, effect, control);
// Create a nested frame state inside the current method's most-recent
// {frame_state} that will ensure that lazy deoptimizations at this
// point will still return the {promise} instead of the result of the
// JSResolvePromise operation (which yields undefined).
Node* parameters[] = {promise};
frame_state = CreateStubBuiltinContinuationFrameState(
jsgraph(), Builtin::kAsyncFunctionLazyDeoptContinuation, context,
parameters, arraysize(parameters), frame_state,
ContinuationFrameStateMode::LAZY);
effect = graph()->NewNode(javascript()->ResolvePromise(), promise, value,
context, frame_state, effect, control);
ReplaceWithValue(node, promise, effect, control);
return Replace(promise);
}
Reduction JSNativeContextSpecialization::ReduceJSAdd(Node* node) {
// TODO(turbofan): This has to run together with the inlining and
// native context specialization to be able to leverage the string
// constant-folding for optimizing property access, but we should
// nevertheless find a better home for this at some point.
DCHECK_EQ(IrOpcode::kJSAdd, node->opcode());
Node* const lhs = node->InputAt(0);
Node* const rhs = node->InputAt(1);
base::Optional<size_t> lhs_len = GetMaxStringLength(broker(), lhs);
base::Optional<size_t> rhs_len = GetMaxStringLength(broker(), rhs);
if (!lhs_len || !rhs_len) {
return NoChange();
}
// Fold into DelayedStringConstant if at least one of the parameters is a
// string constant and the addition won't throw due to too long result.
if (*lhs_len + *rhs_len <= String::kMaxLength &&
(IsStringConstant(broker(), lhs) || IsStringConstant(broker(), rhs))) {
base::Optional<const StringConstantBase*> left =
CreateDelayedStringConstant(lhs);
if (!left.has_value()) return NoChange();
base::Optional<const StringConstantBase*> right =
CreateDelayedStringConstant(rhs);
if (!right.has_value()) return NoChange();
const StringConstantBase* cons =
shared_zone()->New<StringCons>(left.value(), right.value());
Node* reduced = graph()->NewNode(common()->DelayedStringConstant(cons));
ReplaceWithValue(node, reduced);
return Replace(reduced);
}
return NoChange();
}
Reduction JSNativeContextSpecialization::ReduceJSGetSuperConstructor(
Node* node) {
DCHECK_EQ(IrOpcode::kJSGetSuperConstructor, node->opcode());
Node* constructor = NodeProperties::GetValueInput(node, 0);
// Check if the input is a known JSFunction.
HeapObjectMatcher m(constructor);
if (!m.HasResolvedValue() || !m.Ref(broker()).IsJSFunction()) {
return NoChange();
}
JSFunctionRef function = m.Ref(broker()).AsJSFunction();
MapRef function_map = function.map();
base::Optional<HeapObjectRef> function_prototype = function_map.prototype();
if (!function_prototype.has_value()) return NoChange();
// We can constant-fold the super constructor access if the
// {function}s map is stable, i.e. we can use a code dependency
// to guard against [[Prototype]] changes of {function}.
if (function_map.is_stable()) {
dependencies()->DependOnStableMap(function_map);
Node* value = jsgraph()->Constant(*function_prototype);
ReplaceWithValue(node, value);
return Replace(value);
}
return NoChange();
}
Reduction JSNativeContextSpecialization::ReduceJSInstanceOf(Node* node) {
JSInstanceOfNode n(node);
FeedbackParameter const& p = n.Parameters();
Node* object = n.left();
Node* constructor = n.right();
TNode<Object> context = n.context();
FrameState frame_state = n.frame_state();
Effect effect = n.effect();
Control control = n.control();
// Check if the right hand side is a known {receiver}, or
// we have feedback from the InstanceOfIC.
Handle<JSObject> receiver;
HeapObjectMatcher m(constructor);
if (m.HasResolvedValue() && m.Ref(broker()).IsJSObject()) {
receiver = m.Ref(broker()).AsJSObject().object();
} else if (p.feedback().IsValid()) {
ProcessedFeedback const& feedback =
broker()->GetFeedbackForInstanceOf(FeedbackSource(p.feedback()));
if (feedback.IsInsufficient()) return NoChange();
base::Optional<JSObjectRef> maybe_receiver =
feedback.AsInstanceOf().value();
if (!maybe_receiver.has_value()) return NoChange();
receiver = maybe_receiver->object();
} else {
return NoChange();
}
JSObjectRef receiver_ref = MakeRef(broker(), receiver);
MapRef receiver_map = receiver_ref.map();
PropertyAccessInfo access_info = PropertyAccessInfo::Invalid(graph()->zone());
if (broker()->is_concurrent_inlining()) {
access_info = broker()->GetPropertyAccessInfo(
receiver_map,
MakeRef(broker(), isolate()->factory()->has_instance_symbol()),
AccessMode::kLoad, dependencies());
} else {
AccessInfoFactory access_info_factory(broker(), dependencies(),
graph()->zone());
access_info = access_info_factory.ComputePropertyAccessInfo(
receiver_map.object(), factory()->has_instance_symbol(),
AccessMode::kLoad);
}
// TODO(v8:11457) Support dictionary mode holders here.
if (access_info.IsInvalid() || access_info.HasDictionaryHolder())
return NoChange();
access_info.RecordDependencies(dependencies());
PropertyAccessBuilder access_builder(jsgraph(), broker(), dependencies());
if (access_info.IsNotFound()) {
// If there's no @@hasInstance handler, the OrdinaryHasInstance operation
// takes over, but that requires the constructor to be callable.
if (!receiver_map.is_callable()) return NoChange();
dependencies()->DependOnStablePrototypeChains(
access_info.lookup_start_object_maps(), kStartAtPrototype);
// Monomorphic property access.
access_builder.BuildCheckMaps(constructor, &effect, control,
access_info.lookup_start_object_maps());
// Lower to OrdinaryHasInstance(C, O).
NodeProperties::ReplaceValueInput(node, constructor, 0);
NodeProperties::ReplaceValueInput(node, object, 1);
NodeProperties::ReplaceEffectInput(node, effect);
STATIC_ASSERT(n.FeedbackVectorIndex() == 2);
node->RemoveInput(n.FeedbackVectorIndex());
NodeProperties::ChangeOp(node, javascript()->OrdinaryHasInstance());
return Changed(node).FollowedBy(ReduceJSOrdinaryHasInstance(node));
}
if (access_info.IsFastDataConstant()) {
Handle<JSObject> holder;
bool found_on_proto = access_info.holder().ToHandle(&holder);
JSObjectRef holder_ref =
found_on_proto ? MakeRef(broker(), holder) : receiver_ref;
base::Optional<ObjectRef> constant = holder_ref.GetOwnFastDataProperty(
access_info.field_representation(), access_info.field_index(),
dependencies());
if (!constant.has_value() || !constant->IsHeapObject() ||
!constant->AsHeapObject().map().is_callable())
return NoChange();
if (found_on_proto) {
dependencies()->DependOnStablePrototypeChains(
access_info.lookup_start_object_maps(), kStartAtPrototype,
MakeRef(broker(), holder));
}
// Check that {constructor} is actually {receiver}.
constructor =
access_builder.BuildCheckValue(constructor, &effect, control, receiver);
// Monomorphic property access.
access_builder.BuildCheckMaps(constructor, &effect, control,
access_info.lookup_start_object_maps());
// Create a nested frame state inside the current method's most-recent frame
// state that will ensure that deopts that happen after this point will not
// fallback to the last Checkpoint--which would completely re-execute the
// instanceof logic--but rather create an activation of a version of the
// ToBoolean stub that finishes the remaining work of instanceof and returns
// to the caller without duplicating side-effects upon a lazy deopt.
Node* continuation_frame_state = CreateStubBuiltinContinuationFrameState(
jsgraph(), Builtin::kToBooleanLazyDeoptContinuation, context, nullptr,
0, frame_state, ContinuationFrameStateMode::LAZY);
// Call the @@hasInstance handler.
Node* target = jsgraph()->Constant(*constant);
Node* feedback = jsgraph()->UndefinedConstant();
// Value inputs plus context, frame state, effect, control.
STATIC_ASSERT(JSCallNode::ArityForArgc(1) + 4 == 8);
node->EnsureInputCount(graph()->zone(), 8);
node->ReplaceInput(JSCallNode::TargetIndex(), target);
node->ReplaceInput(JSCallNode::ReceiverIndex(), constructor);
node->ReplaceInput(JSCallNode::ArgumentIndex(0), object);
node->ReplaceInput(3, feedback);
node->ReplaceInput(4, context);
node->ReplaceInput(5, continuation_frame_state);
node->ReplaceInput(6, effect);
node->ReplaceInput(7, control);
NodeProperties::ChangeOp(
node, javascript()->Call(JSCallNode::ArityForArgc(1), CallFrequency(),
FeedbackSource(),
ConvertReceiverMode::kNotNullOrUndefined));
// Rewire the value uses of {node} to ToBoolean conversion of the result.
Node* value = graph()->NewNode(simplified()->ToBoolean(), node);
for (Edge edge : node->use_edges()) {
if (NodeProperties::IsValueEdge(edge) && edge.from() != value) {
edge.UpdateTo(value);
Revisit(edge.from());
}
}
return Changed(node);
}
return NoChange();
}
JSNativeContextSpecialization::InferHasInPrototypeChainResult
JSNativeContextSpecialization::InferHasInPrototypeChain(
Node* receiver, Node* effect, HeapObjectRef const& prototype) {
ZoneHandleSet<Map> receiver_maps;
NodeProperties::InferMapsResult result = NodeProperties::InferMapsUnsafe(
broker(), receiver, effect, &receiver_maps);
if (result == NodeProperties::kNoMaps) return kMayBeInPrototypeChain;
// Try to determine either that all of the {receiver_maps} have the given
// {prototype} in their chain, or that none do. If we can't tell, return
// kMayBeInPrototypeChain.
bool all = true;
bool none = true;
for (size_t i = 0; i < receiver_maps.size(); ++i) {
MapRef map = MakeRef(broker(), receiver_maps[i]);
if (result == NodeProperties::kUnreliableMaps && !map.is_stable()) {
return kMayBeInPrototypeChain;
}
while (true) {
if (IsSpecialReceiverInstanceType(map.instance_type())) {
return kMayBeInPrototypeChain;
}
if (!map.IsJSObjectMap()) {
all = false;
break;
}
base::Optional<HeapObjectRef> map_prototype = map.prototype();
if (!map_prototype.has_value()) return kMayBeInPrototypeChain;
if (map_prototype->equals(prototype)) {
none = false;
break;
}
map = map_prototype->map();
// TODO(v8:11457) Support dictionary mode protoypes here.
if (!map.is_stable() || map.is_dictionary_map())
return kMayBeInPrototypeChain;
if (map.oddball_type() == OddballType::kNull) {
all = false;
break;
}
}
}
DCHECK_IMPLIES(all, !none);
if (!all && !none) return kMayBeInPrototypeChain;
{
base::Optional<JSObjectRef> last_prototype;
if (all) {
// We don't need to protect the full chain if we found the prototype, we
// can stop at {prototype}. In fact we could stop at the one before
// {prototype} but since we're dealing with multiple receiver maps this
// might be a different object each time, so it's much simpler to include
// {prototype}. That does, however, mean that we must check {prototype}'s
// map stability.
if (!prototype.map().is_stable()) return kMayBeInPrototypeChain;
last_prototype = prototype.AsJSObject();
}
WhereToStart start = result == NodeProperties::kUnreliableMaps
? kStartAtReceiver
: kStartAtPrototype;
dependencies()->DependOnStablePrototypeChains(receiver_maps, start,
last_prototype);
}
DCHECK_EQ(all, !none);
return all ? kIsInPrototypeChain : kIsNotInPrototypeChain;
}
Reduction JSNativeContextSpecialization::ReduceJSHasInPrototypeChain(
Node* node) {
DCHECK_EQ(IrOpcode::kJSHasInPrototypeChain, node->opcode());
Node* value = NodeProperties::GetValueInput(node, 0);
Node* prototype = NodeProperties::GetValueInput(node, 1);
Node* effect = NodeProperties::GetEffectInput(node);
// Check if we can constant-fold the prototype chain walk
// for the given {value} and the {prototype}.
HeapObjectMatcher m(prototype);
if (m.HasResolvedValue()) {
InferHasInPrototypeChainResult result =
InferHasInPrototypeChain(value, effect, m.Ref(broker()));
if (result != kMayBeInPrototypeChain) {
Node* value = jsgraph()->BooleanConstant(result == kIsInPrototypeChain);
ReplaceWithValue(node, value);
return Replace(value);
}
}
return NoChange();
}
Reduction JSNativeContextSpecialization::ReduceJSOrdinaryHasInstance(
Node* node) {
DCHECK_EQ(IrOpcode::kJSOrdinaryHasInstance, node->opcode());
Node* constructor = NodeProperties::GetValueInput(node, 0);
Node* object = NodeProperties::GetValueInput(node, 1);
// Check if the {constructor} is known at compile time.
HeapObjectMatcher m(constructor);
if (!m.HasResolvedValue()) return NoChange();
if (m.Ref(broker()).IsJSBoundFunction()) {
// OrdinaryHasInstance on bound functions turns into a recursive invocation
// of the instanceof operator again.
JSBoundFunctionRef function = m.Ref(broker()).AsJSBoundFunction();
base::Optional<JSReceiverRef> bound_target_function =
function.bound_target_function();
if (bound_target_function.has_value()) return NoChange();
Node* feedback = jsgraph()->UndefinedConstant();
NodeProperties::ReplaceValueInput(node, object,
JSInstanceOfNode::LeftIndex());
NodeProperties::ReplaceValueInput(
node, jsgraph()->Constant(*bound_target_function),
JSInstanceOfNode::RightIndex());
node->InsertInput(zone(), JSInstanceOfNode::FeedbackVectorIndex(),
feedback);
NodeProperties::ChangeOp(node, javascript()->InstanceOf(FeedbackSource()));
return Changed(node).FollowedBy(ReduceJSInstanceOf(node));
}
if (m.Ref(broker()).IsJSFunction()) {
// Optimize if we currently know the "prototype" property.
JSFunctionRef function = m.Ref(broker()).AsJSFunction();
if (!function.serialized()) return NoChange();
// TODO(neis): Remove the has_prototype_slot condition once the broker is
// always enabled.
if (!function.map().has_prototype_slot() || !function.has_prototype() ||
function.PrototypeRequiresRuntimeLookup()) {
return NoChange();
}
ObjectRef prototype = dependencies()->DependOnPrototypeProperty(function);
Node* prototype_constant = jsgraph()->Constant(prototype);
// Lower the {node} to JSHasInPrototypeChain.
NodeProperties::ReplaceValueInput(node, object, 0);
NodeProperties::ReplaceValueInput(node, prototype_constant, 1);
NodeProperties::ChangeOp(node, javascript()->HasInPrototypeChain());
return Changed(node).FollowedBy(ReduceJSHasInPrototypeChain(node));
}
return NoChange();
}
// ES section #sec-promise-resolve
Reduction JSNativeContextSpecialization::ReduceJSPromiseResolve(Node* node) {
DCHECK_EQ(IrOpcode::kJSPromiseResolve, node->opcode());
Node* constructor = NodeProperties::GetValueInput(node, 0);
Node* value = NodeProperties::GetValueInput(node, 1);
Node* context = NodeProperties::GetContextInput(node);
Node* frame_state = NodeProperties::GetFrameStateInput(node);
Node* effect = NodeProperties::GetEffectInput(node);
Node* control = NodeProperties::GetControlInput(node);
// Check if the {constructor} is the %Promise% function.
HeapObjectMatcher m(constructor);
if (!m.HasResolvedValue() ||
!m.Ref(broker()).equals(native_context().promise_function())) {
return NoChange();
}
// Only optimize if {value} cannot be a JSPromise.
MapInference inference(broker(), value, effect);
if (!inference.HaveMaps() ||
inference.AnyOfInstanceTypesAre(JS_PROMISE_TYPE)) {
return NoChange();
}
if (!dependencies()->DependOnPromiseHookProtector()) return NoChange();
// Create a %Promise% instance and resolve it with {value}.
Node* promise = effect =
graph()->NewNode(javascript()->CreatePromise(), context, effect);
effect = graph()->NewNode(javascript()->ResolvePromise(), promise, value,
context, frame_state, effect, control);
ReplaceWithValue(node, promise, effect, control);
return Replace(promise);
}
// ES section #sec-promise-resolve-functions
Reduction JSNativeContextSpecialization::ReduceJSResolvePromise(Node* node) {
DCHECK_EQ(IrOpcode::kJSResolvePromise, node->opcode());
Node* promise = NodeProperties::GetValueInput(node, 0);
Node* resolution = NodeProperties::GetValueInput(node, 1);
Node* context = NodeProperties::GetContextInput(node);
Node* effect = NodeProperties::GetEffectInput(node);
Node* control = NodeProperties::GetControlInput(node);
// Check if we know something about the {resolution}.
MapInference inference(broker(), resolution, effect);
if (!inference.HaveMaps()) return NoChange();
MapHandles const& resolution_maps = inference.GetMaps();
// Compute property access info for "then" on {resolution}.
ZoneVector<PropertyAccessInfo> access_infos(graph()->zone());
AccessInfoFactory access_info_factory(broker(), dependencies(),
graph()->zone());
if (!broker()->is_concurrent_inlining()) {
access_info_factory.ComputePropertyAccessInfos(
resolution_maps, factory()->then_string(), AccessMode::kLoad,
&access_infos);
} else {
// Obtain pre-computed access infos from the broker.
for (auto map : resolution_maps) {
MapRef map_ref = MakeRef(broker(), map);
access_infos.push_back(broker()->GetPropertyAccessInfo(
map_ref, MakeRef(broker(), isolate()->factory()->then_string()),
AccessMode::kLoad, dependencies()));
}
}
PropertyAccessInfo access_info =
access_info_factory.FinalizePropertyAccessInfosAsOne(access_infos,
AccessMode::kLoad);
// TODO(v8:11457) Support dictionary mode prototypes here.
if (access_info.IsInvalid() || access_info.HasDictionaryHolder())
return inference.NoChange();
// Only optimize when {resolution} definitely doesn't have a "then" property.
if (!access_info.IsNotFound()) return inference.NoChange();
if (!inference.RelyOnMapsViaStability(dependencies())) {
return inference.NoChange();
}
dependencies()->DependOnStablePrototypeChains(
access_info.lookup_start_object_maps(), kStartAtPrototype);
// Simply fulfill the {promise} with the {resolution}.
Node* value = effect =
graph()->NewNode(javascript()->FulfillPromise(), promise, resolution,
context, effect, control);
ReplaceWithValue(node, value, effect, control);
return Replace(value);
}
namespace {
FieldAccess ForPropertyCellValue(MachineRepresentation representation,
Type type, MaybeHandle<Map> map,
NameRef const& name) {
WriteBarrierKind kind = kFullWriteBarrier;
if (representation == MachineRepresentation::kTaggedSigned) {
kind = kNoWriteBarrier;
} else if (representation == MachineRepresentation::kTaggedPointer) {
kind = kPointerWriteBarrier;
}
MachineType r = MachineType::TypeForRepresentation(representation);
FieldAccess access = {
kTaggedBase, PropertyCell::kValueOffset, name.object(), map, type, r,
kind};
return access;
}
} // namespace
// TODO(neis): Try to merge this with ReduceNamedAccess by introducing a new
// PropertyAccessInfo kind for global accesses and using the existing mechanism
// for building loads/stores.
// Note: The "receiver" parameter is only used for DCHECKS, but that's on
// purpose. This way we can assert the super property access cases won't hit the
// code which hasn't been modified to support super property access.
Reduction JSNativeContextSpecialization::ReduceGlobalAccess(
Node* node, Node* lookup_start_object, Node* receiver, Node* value,
NameRef const& name, AccessMode access_mode, Node* key,
PropertyCellRef const& property_cell, Node* effect) {
if (!property_cell.Serialize()) {
TRACE_BROKER_MISSING(broker(), "usable data for " << property_cell);
return NoChange();
}
ObjectRef property_cell_value = property_cell.value();
if (property_cell_value.IsHeapObject() &&
property_cell_value.AsHeapObject().map().oddball_type() ==
OddballType::kHole) {
// The property cell is no longer valid.
return NoChange();
}
PropertyDetails property_details = property_cell.property_details();
PropertyCellType property_cell_type = property_details.cell_type();
DCHECK_EQ(kData, property_details.kind());
Node* control = NodeProperties::GetControlInput(node);
if (effect == nullptr) {
effect = NodeProperties::GetEffectInput(node);
}
// We have additional constraints for stores.
if (access_mode == AccessMode::kStore) {
DCHECK_EQ(receiver, lookup_start_object);
if (property_details.IsReadOnly()) {
// Don't even bother trying to lower stores to read-only data properties.
// TODO(neis): We could generate code that checks if the new value equals
// the old one and then does nothing or deopts, respectively.
return NoChange();
} else if (property_cell_type == PropertyCellType::kUndefined) {
return NoChange();
} else if (property_cell_type == PropertyCellType::kConstantType) {
// We rely on stability further below.
if (property_cell_value.IsHeapObject() &&
!property_cell_value.AsHeapObject().map().is_stable()) {
return NoChange();
}
}
} else if (access_mode == AccessMode::kHas) {
DCHECK_EQ(receiver, lookup_start_object);
// has checks cannot follow the fast-path used by loads when these
// conditions hold.
if ((property_details.IsConfigurable() || !property_details.IsReadOnly()) &&
property_details.cell_type() != PropertyCellType::kConstant &&
property_details.cell_type() != PropertyCellType::kUndefined)
return NoChange();
}
// Ensure that {key} matches the specified {name} (if {key} is given).
if (key != nullptr) {
effect = BuildCheckEqualsName(name, key, effect, control);
}
// If we have a {lookup_start_object} to validate, we do so by checking that
// its map is the (target) global proxy's map. This guarantees that in fact
// the lookup start object is the global proxy.
// Note: we rely on the map constant below being the same as what is used in
// NativeContextRef::GlobalIsDetached().
if (lookup_start_object != nullptr) {
effect = graph()->NewNode(
simplified()->CheckMaps(
CheckMapsFlag::kNone,
ZoneHandleSet<Map>(
native_context().global_proxy_object().map().object())),
lookup_start_object, effect, control);
}
if (access_mode == AccessMode::kLoad || access_mode == AccessMode::kHas) {
// Load from non-configurable, read-only data property on the global
// object can be constant-folded, even without deoptimization support.
if (!property_details.IsConfigurable() && property_details.IsReadOnly()) {
value = access_mode == AccessMode::kHas
? jsgraph()->TrueConstant()
: jsgraph()->Constant(property_cell_value);
} else {
// Record a code dependency on the cell if we can benefit from the
// additional feedback, or the global property is configurable (i.e.
// can be deleted or reconfigured to an accessor property).
if (property_details.cell_type() != PropertyCellType::kMutable ||
property_details.IsConfigurable()) {
dependencies()->DependOnGlobalProperty(property_cell);
}
// Load from constant/undefined global property can be constant-folded.
if (property_details.cell_type() == PropertyCellType::kConstant ||
property_details.cell_type() == PropertyCellType::kUndefined) {
value = access_mode == AccessMode::kHas
? jsgraph()->TrueConstant()
: jsgraph()->Constant(property_cell_value);
DCHECK(!property_cell_value.IsHeapObject() ||
property_cell_value.AsHeapObject().map().oddball_type() !=
OddballType::kHole);
} else {
DCHECK_NE(AccessMode::kHas, access_mode);
// Load from constant type cell can benefit from type feedback.
MaybeHandle<Map> map;
Type property_cell_value_type = Type::NonInternal();
MachineRepresentation representation = MachineRepresentation::kTagged;
if (property_details.cell_type() == PropertyCellType::kConstantType) {
// Compute proper type based on the current value in the cell.
if (property_cell_value.IsSmi()) {
property_cell_value_type = Type::SignedSmall();
representation = MachineRepresentation::kTaggedSigned;
} else if (property_cell_value.IsHeapNumber()) {
property_cell_value_type = Type::Number();
representation = MachineRepresentation::kTaggedPointer;
} else {
MapRef property_cell_value_map =
property_cell_value.AsHeapObject().map();
property_cell_value_type = Type::For(property_cell_value_map);
representation = MachineRepresentation::kTaggedPointer;
// We can only use the property cell value map for map check
// elimination if it's stable, i.e. the HeapObject wasn't
// mutated without the cell state being updated.
if (property_cell_value_map.is_stable()) {
dependencies()->DependOnStableMap(property_cell_value_map);
map = property_cell_value_map.object();
}
}
}
value = effect = graph()->NewNode(
simplified()->LoadField(ForPropertyCellValue(
representation, property_cell_value_type, map, name)),
jsgraph()->Constant(property_cell), effect, control);
}
}
} else {
DCHECK_EQ(AccessMode::kStore, access_mode);
DCHECK_EQ(receiver, lookup_start_object);
DCHECK(!property_details.IsReadOnly());
switch (property_details.cell_type()) {
case PropertyCellType::kConstant: {
// Record a code dependency on the cell, and just deoptimize if the new
// value doesn't match the previous value stored inside the cell.
dependencies()->DependOnGlobalProperty(property_cell);
Node* check =
graph()->NewNode(simplified()->ReferenceEqual(), value,
jsgraph()->Constant(property_cell_value));
effect = graph()->NewNode(
simplified()->CheckIf(DeoptimizeReason::kValueMismatch), check,
effect, control);
break;
}
case PropertyCellType::kConstantType: {
// Record a code dependency on the cell, and just deoptimize if the new
// value's type doesn't match the type of the previous value in the
// cell.
dependencies()->DependOnGlobalProperty(property_cell);
Type property_cell_value_type;
MachineRepresentation representation = MachineRepresentation::kTagged;
if (property_cell_value.IsHeapObject()) {
MapRef property_cell_value_map =
property_cell_value.AsHeapObject().map();
dependencies()->DependOnStableMap(property_cell_value_map);
// Check that the {value} is a HeapObject.
value = effect = graph()->NewNode(simplified()->CheckHeapObject(),
value, effect, control);
// Check {value} map against the {property_cell_value} map.
effect = graph()->NewNode(
simplified()->CheckMaps(
CheckMapsFlag::kNone,
ZoneHandleSet<Map>(property_cell_value_map.object())),
value, effect, control);
property_cell_value_type = Type::OtherInternal();
representation = MachineRepresentation::kTaggedPointer;
} else {
// Check that the {value} is a Smi.
value = effect = graph()->NewNode(
simplified()->CheckSmi(FeedbackSource()), value, effect, control);
property_cell_value_type = Type::SignedSmall();
representation = MachineRepresentation::kTaggedSigned;
}
effect = graph()->NewNode(simplified()->StoreField(ForPropertyCellValue(
representation, property_cell_value_type,
MaybeHandle<Map>(), name)),
jsgraph()->Constant(property_cell), value,
effect, control);
break;
}
case PropertyCellType::kMutable: {
// Record a code dependency on the cell, and just deoptimize if the
// property ever becomes read-only.
dependencies()->DependOnGlobalProperty(property_cell);
effect = graph()->NewNode(
simplified()->StoreField(ForPropertyCellValue(
MachineRepresentation::kTagged, Type::NonInternal(),
MaybeHandle<Map>(), name)),
jsgraph()->Constant(property_cell), value, effect, control);
break;
}
case PropertyCellType::kUndefined:
UNREACHABLE();
}
}
ReplaceWithValue(node, value, effect, control);
return Replace(value);
}
Reduction JSNativeContextSpecialization::ReduceJSLoadGlobal(Node* node) {
JSLoadGlobalNode n(node);