-
Notifications
You must be signed in to change notification settings - Fork 1.6k
/
call_specializer.cc
3527 lines (3259 loc) · 136 KB
/
call_specializer.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 (c) 2017, the Dart project authors. Please see the AUTHORS file
// for details. All rights reserved. Use of this source code is governed by a
// BSD-style license that can be found in the LICENSE file.
#include "vm/compiler/call_specializer.h"
#include "vm/compiler/backend/flow_graph_compiler.h"
#include "vm/compiler/backend/inliner.h"
#include "vm/compiler/cha.h"
#include "vm/compiler/compiler_state.h"
#include "vm/compiler/compiler_timings.h"
#include "vm/cpu.h"
namespace dart {
DECLARE_FLAG(bool, enable_simd_inline);
// Quick access to the current isolate and zone.
#define IG (isolate_group())
#define Z (zone())
static void RefineUseTypes(Definition* instr) {
CompileType* new_type = instr->Type();
for (Value::Iterator it(instr->input_use_list()); !it.Done(); it.Advance()) {
it.Current()->RefineReachingType(new_type);
}
}
static bool ShouldInlineSimd() {
return FlowGraphCompiler::SupportsUnboxedSimd128();
}
static bool CanConvertInt64ToDouble() {
return FlowGraphCompiler::CanConvertInt64ToDouble();
}
static bool IsNumberCid(intptr_t cid) {
return (cid == kSmiCid) || (cid == kDoubleCid);
}
static bool ShouldSpecializeForDouble(const BinaryFeedback& binary_feedback) {
// Unboxed double operation can't handle case of two smis.
if (binary_feedback.IncludesOperands(kSmiCid)) {
return false;
}
// Check that the call site has seen only smis and doubles.
return binary_feedback.OperandsAreSmiOrDouble();
}
// Optimize instance calls using ICData.
void CallSpecializer::ApplyICData() {
VisitBlocks();
}
// Optimize instance calls using cid. This is called after optimizer
// converted instance calls to instructions. Any remaining
// instance calls are either megamorphic calls, cannot be optimized or
// have no runtime type feedback collected.
// Attempts to convert an instance call (IC call) using propagated class-ids,
// e.g., receiver class id, guarded-cid, or by guessing cid-s.
void CallSpecializer::ApplyClassIds() {
ASSERT(current_iterator_ == nullptr);
for (BlockIterator block_it = flow_graph_->reverse_postorder_iterator();
!block_it.Done(); block_it.Advance()) {
thread()->CheckForSafepoint();
ForwardInstructionIterator it(block_it.Current());
current_iterator_ = ⁢
for (; !it.Done(); it.Advance()) {
Instruction* instr = it.Current();
if (instr->IsInstanceCall()) {
InstanceCallInstr* call = instr->AsInstanceCall();
if (call->HasICData()) {
if (TryCreateICData(call)) {
VisitInstanceCall(call);
}
}
} else if (auto static_call = instr->AsStaticCall()) {
// If TFA devirtualized instance calls to static calls we also want to
// process them here.
VisitStaticCall(static_call);
} else if (instr->IsPolymorphicInstanceCall()) {
SpecializePolymorphicInstanceCall(instr->AsPolymorphicInstanceCall());
}
}
current_iterator_ = nullptr;
}
}
bool CallSpecializer::TryCreateICData(InstanceCallInstr* call) {
ASSERT(call->HasICData());
if (call->Targets().length() > 0) {
// This occurs when an instance call has too many checks, will be converted
// to megamorphic call.
return false;
}
const intptr_t receiver_index = call->FirstArgIndex();
GrowableArray<intptr_t> class_ids(call->ic_data()->NumArgsTested());
ASSERT(call->ic_data()->NumArgsTested() <=
call->ArgumentCountWithoutTypeArgs());
for (intptr_t i = 0; i < call->ic_data()->NumArgsTested(); i++) {
class_ids.Add(call->ArgumentValueAt(receiver_index + i)->Type()->ToCid());
}
const Token::Kind op_kind = call->token_kind();
if (FLAG_guess_icdata_cid && !CompilerState::Current().is_aot()) {
if (Token::IsRelationalOperator(op_kind) ||
Token::IsEqualityOperator(op_kind) ||
Token::IsBinaryOperator(op_kind)) {
// Guess cid: if one of the inputs is a number assume that the other
// is a number of same type, unless the interface target tells us this
// is impossible.
if (call->CanReceiverBeSmiBasedOnInterfaceTarget(zone())) {
const intptr_t cid_0 = class_ids[0];
const intptr_t cid_1 = class_ids[1];
if ((cid_0 == kDynamicCid) && (IsNumberCid(cid_1))) {
class_ids[0] = cid_1;
} else if (IsNumberCid(cid_0) && (cid_1 == kDynamicCid)) {
class_ids[1] = cid_0;
}
}
}
}
bool all_cids_known = true;
for (intptr_t i = 0; i < class_ids.length(); i++) {
if (class_ids[i] == kDynamicCid) {
// Not all cid-s known.
all_cids_known = false;
break;
}
}
if (all_cids_known) {
const intptr_t receiver_cid = class_ids[0];
if (receiver_cid == kSentinelCid) {
// Unreachable call.
return false;
}
const Class& receiver_class =
Class::Handle(Z, IG->class_table()->At(receiver_cid));
if (!receiver_class.is_finalized()) {
// Do not eagerly finalize classes. ResolveDynamicForReceiverClass can
// cause class finalization, since callee's receiver class may not be
// finalized yet.
return false;
}
const Function& function = Function::Handle(
Z, call->ResolveForReceiverClass(receiver_class, /*allow_add=*/false));
if (function.IsNull()) {
return false;
}
ASSERT(!function.IsInvokeFieldDispatcher());
// Update the CallTargets attached to the instruction with our speculative
// target. The next round of CallSpecializer::VisitInstanceCall will make
// use of this.
call->SetTargets(CallTargets::CreateMonomorphic(Z, class_ids[0], function));
if (class_ids.length() == 2) {
call->SetBinaryFeedback(
BinaryFeedback::CreateMonomorphic(Z, class_ids[0], class_ids[1]));
}
return true;
}
return false;
}
void CallSpecializer::SpecializePolymorphicInstanceCall(
PolymorphicInstanceCallInstr* call) {
if (!FLAG_polymorphic_with_deopt) {
// Specialization adds receiver checks which can lead to deoptimization.
return;
}
const intptr_t receiver_cid = call->Receiver()->Type()->ToCid();
if (receiver_cid == kDynamicCid) {
return; // No information about receiver was inferred.
}
const ICData& ic_data = *call->ic_data();
const CallTargets* targets =
FlowGraphCompiler::ResolveCallTargetsForReceiverCid(
receiver_cid, String::Handle(zone(), ic_data.target_name()),
Array::Handle(zone(), ic_data.arguments_descriptor()));
if (targets == nullptr) {
// No specialization.
return;
}
ASSERT(targets->HasSingleTarget());
const Function& target = targets->FirstTarget();
StaticCallInstr* specialized =
StaticCallInstr::FromCall(Z, call, target, targets->AggregateCallCount());
call->ReplaceWith(specialized, current_iterator());
}
void CallSpecializer::ReplaceCallWithResult(Definition* call,
Instruction* replacement,
Definition* result) {
ASSERT(!call->HasMoveArguments());
if (result == nullptr) {
ASSERT(replacement->IsDefinition());
call->ReplaceWith(replacement->AsDefinition(), current_iterator());
} else {
call->ReplaceWithResult(replacement, result, current_iterator());
}
}
void CallSpecializer::ReplaceCall(Definition* call, Definition* replacement) {
ReplaceCallWithResult(call, replacement, nullptr);
}
void CallSpecializer::AddCheckSmi(Definition* to_check,
intptr_t deopt_id,
Environment* deopt_environment,
Instruction* insert_before) {
// TODO(alexmarkov): check reaching type instead of definition type
if (to_check->Type()->ToCid() != kSmiCid) {
InsertBefore(insert_before,
new (Z) CheckSmiInstr(new (Z) Value(to_check), deopt_id,
insert_before->source()),
deopt_environment, FlowGraph::kEffect);
}
}
void CallSpecializer::AddCheckClass(Definition* to_check,
const Cids& cids,
intptr_t deopt_id,
Environment* deopt_environment,
Instruction* insert_before) {
// Type propagation has not run yet, we cannot eliminate the check.
Instruction* check = flow_graph_->CreateCheckClass(to_check, cids, deopt_id,
insert_before->source());
InsertBefore(insert_before, check, deopt_environment, FlowGraph::kEffect);
}
void CallSpecializer::AddChecksForArgNr(InstanceCallInstr* call,
Definition* argument,
int argument_number) {
const Cids* cids =
Cids::CreateForArgument(zone(), call->BinaryFeedback(), argument_number);
AddCheckClass(argument, *cids, call->deopt_id(), call->env(), call);
}
void CallSpecializer::AddCheckNull(Value* to_check,
const String& function_name,
intptr_t deopt_id,
Environment* deopt_environment,
Instruction* insert_before) {
if (to_check->Type()->is_nullable()) {
CheckNullInstr* check_null =
new (Z) CheckNullInstr(to_check->CopyWithType(Z), function_name,
deopt_id, insert_before->source());
if (FLAG_trace_strong_mode_types) {
THR_Print("[Strong mode] Inserted %s\n", check_null->ToCString());
}
InsertBefore(insert_before, check_null, deopt_environment,
FlowGraph::kEffect);
}
}
// Return true if d is a string of length one (a constant or result from
// from string-from-char-code instruction.
static bool IsLengthOneString(Definition* d) {
if (d->IsConstant()) {
const Object& obj = d->AsConstant()->value();
if (obj.IsString()) {
return String::Cast(obj).Length() == 1;
} else {
return false;
}
} else {
return d->IsOneByteStringFromCharCode();
}
}
// Returns true if the string comparison was converted into char-code
// comparison. Conversion is only possible for strings of length one.
// E.g., detect str[x] == "x"; and use an integer comparison of char-codes.
bool CallSpecializer::TryStringLengthOneEquality(InstanceCallInstr* call,
Token::Kind op_kind) {
ASSERT(call->BinaryFeedback().OperandsAre(kOneByteStringCid));
// Check that left and right are length one strings (either string constants
// or results of string-from-char-code.
Definition* left = call->ArgumentAt(0);
Definition* right = call->ArgumentAt(1);
Value* left_val = nullptr;
Definition* to_remove_left = nullptr;
if (IsLengthOneString(right)) {
// Swap, since we know that both arguments are strings
Definition* temp = left;
left = right;
right = temp;
}
if (IsLengthOneString(left)) {
// Optimize if left is a string with length one (either constant or
// result of string-from-char-code.
if (left->IsConstant()) {
ConstantInstr* left_const = left->AsConstant();
const String& str = String::Cast(left_const->value());
ASSERT(str.Length() == 1);
ConstantInstr* char_code_left = flow_graph()->GetConstant(
Smi::ZoneHandle(Z, Smi::New(static_cast<intptr_t>(str.CharAt(0)))));
left_val = new (Z) Value(char_code_left);
} else if (left->IsOneByteStringFromCharCode()) {
// Use input of string-from-charcode as left value.
OneByteStringFromCharCodeInstr* instr =
left->AsOneByteStringFromCharCode();
left_val = new (Z) Value(instr->char_code()->definition());
to_remove_left = instr;
} else {
// IsLengthOneString(left) should have been false.
UNREACHABLE();
}
Definition* to_remove_right = nullptr;
Value* right_val = nullptr;
if (right->IsOneByteStringFromCharCode()) {
// Skip string-from-char-code, and use its input as right value.
OneByteStringFromCharCodeInstr* right_instr =
right->AsOneByteStringFromCharCode();
right_val = new (Z) Value(right_instr->char_code()->definition());
to_remove_right = right_instr;
} else {
AddChecksForArgNr(call, right, /* arg_number = */ 1);
// String-to-char-code instructions returns -1 (illegal charcode) if
// string is not of length one.
StringToCharCodeInstr* char_code_right = new (Z)
StringToCharCodeInstr(new (Z) Value(right), kOneByteStringCid);
InsertBefore(call, char_code_right, call->env(), FlowGraph::kValue);
right_val = new (Z) Value(char_code_right);
}
// Comparing char-codes instead of strings.
EqualityCompareInstr* comp = new (Z) EqualityCompareInstr(
call->source(), op_kind, left_val, right_val, kSmiCid, call->deopt_id(),
/*null_aware=*/false);
ReplaceCall(call, comp);
// Remove dead instructions.
if ((to_remove_left != nullptr) &&
(to_remove_left->input_use_list() == nullptr)) {
to_remove_left->ReplaceUsesWith(flow_graph()->constant_null());
to_remove_left->RemoveFromGraph();
}
if ((to_remove_right != nullptr) &&
(to_remove_right->input_use_list() == nullptr)) {
to_remove_right->ReplaceUsesWith(flow_graph()->constant_null());
to_remove_right->RemoveFromGraph();
}
return true;
}
return false;
}
static bool SmiFitsInDouble() {
return compiler::target::kSmiBits < 53;
}
bool CallSpecializer::TryReplaceWithEqualityOp(InstanceCallInstr* call,
Token::Kind op_kind) {
const BinaryFeedback& binary_feedback = call->BinaryFeedback();
ASSERT(call->type_args_len() == 0);
ASSERT(call->ArgumentCount() == 2);
Definition* left = call->ArgumentAt(0);
Definition* right = call->ArgumentAt(1);
intptr_t cid = kIllegalCid;
if (binary_feedback.OperandsAre(kOneByteStringCid)) {
return TryStringLengthOneEquality(call, op_kind);
} else if (binary_feedback.OperandsAre(kSmiCid)) {
InsertBefore(call,
new (Z) CheckSmiInstr(new (Z) Value(left), call->deopt_id(),
call->source()),
call->env(), FlowGraph::kEffect);
InsertBefore(call,
new (Z) CheckSmiInstr(new (Z) Value(right), call->deopt_id(),
call->source()),
call->env(), FlowGraph::kEffect);
cid = kSmiCid;
} else if (binary_feedback.OperandsAreSmiOrMint()) {
cid = kMintCid;
left =
UnboxInstr::Create(kUnboxedInt64, new (Z) Value(left), call->deopt_id(),
UnboxInstr::ValueMode::kCheckType);
InsertBefore(call, left, call->env(), FlowGraph::kValue);
right =
UnboxInstr::Create(kUnboxedInt64, new (Z) Value(right),
call->deopt_id(), UnboxInstr::ValueMode::kCheckType);
InsertBefore(call, right, call->env(), FlowGraph::kValue);
} else if (binary_feedback.OperandsAreSmiOrDouble()) {
// Use double comparison.
if (SmiFitsInDouble()) {
cid = kDoubleCid;
} else {
if (binary_feedback.IncludesOperands(kSmiCid)) {
// We cannot use double comparison on two smis. Need polymorphic
// call.
return false;
} else {
InsertBefore(
call,
new (Z) CheckEitherNonSmiInstr(
new (Z) Value(left), new (Z) Value(right), call->deopt_id()),
call->env(), FlowGraph::kEffect);
cid = kDoubleCid;
}
}
left =
UnboxInstr::Create(kUnboxedDouble, new (Z) Value(left),
call->deopt_id(), UnboxInstr::ValueMode::kCheckType);
InsertBefore(call, left, call->env(), FlowGraph::kValue);
right =
UnboxInstr::Create(kUnboxedDouble, new (Z) Value(right),
call->deopt_id(), UnboxInstr::ValueMode::kCheckType);
InsertBefore(call, right, call->env(), FlowGraph::kValue);
} else {
// Check if ICDData contains checks with Smi/Null combinations. In that case
// we can still emit the optimized Smi equality operation but need to add
// checks for null or Smi.
if (binary_feedback.OperandsAreSmiOrNull()) {
AddChecksForArgNr(call, left, /* arg_number = */ 0);
AddChecksForArgNr(call, right, /* arg_number = */ 1);
cid = kSmiCid;
} else {
// Shortcut for equality with null.
// TODO(vegorov): this optimization is not speculative and should
// be hoisted out of this function.
ConstantInstr* right_const = right->AsConstant();
ConstantInstr* left_const = left->AsConstant();
if ((right_const != nullptr && right_const->value().IsNull()) ||
(left_const != nullptr && left_const->value().IsNull())) {
StrictCompareInstr* comp = new (Z)
StrictCompareInstr(call->source(), Token::kEQ_STRICT,
new (Z) Value(left), new (Z) Value(right),
/* number_check = */ false, DeoptId::kNone);
ReplaceCall(call, comp);
return true;
}
return false;
}
}
ASSERT(cid != kIllegalCid);
EqualityCompareInstr* comp = new (Z) EqualityCompareInstr(
call->source(), op_kind, new (Z) Value(left), new (Z) Value(right), cid,
call->deopt_id(), /*null_aware=*/false);
ReplaceCall(call, comp);
return true;
}
bool CallSpecializer::TryReplaceWithRelationalOp(InstanceCallInstr* call,
Token::Kind op_kind) {
ASSERT(call->type_args_len() == 0);
ASSERT(call->ArgumentCount() == 2);
const BinaryFeedback& binary_feedback = call->BinaryFeedback();
Definition* left = call->ArgumentAt(0);
Definition* right = call->ArgumentAt(1);
intptr_t cid = kIllegalCid;
if (binary_feedback.OperandsAre(kSmiCid)) {
InsertBefore(call,
new (Z) CheckSmiInstr(new (Z) Value(left), call->deopt_id(),
call->source()),
call->env(), FlowGraph::kEffect);
InsertBefore(call,
new (Z) CheckSmiInstr(new (Z) Value(right), call->deopt_id(),
call->source()),
call->env(), FlowGraph::kEffect);
cid = kSmiCid;
} else if (binary_feedback.OperandsAreSmiOrMint()) {
left =
UnboxInstr::Create(kUnboxedInt64, new (Z) Value(left), call->deopt_id(),
UnboxInstr::ValueMode::kCheckType);
InsertBefore(call, left, call->env(), FlowGraph::kValue);
right =
UnboxInstr::Create(kUnboxedInt64, new (Z) Value(right),
call->deopt_id(), UnboxInstr::ValueMode::kCheckType);
InsertBefore(call, right, call->env(), FlowGraph::kValue);
cid = kMintCid;
} else if (binary_feedback.OperandsAreSmiOrDouble()) {
// Use double comparison.
if (SmiFitsInDouble()) {
cid = kDoubleCid;
} else {
if (binary_feedback.IncludesOperands(kSmiCid)) {
// We cannot use double comparison on two smis. Need polymorphic
// call.
return false;
} else {
InsertBefore(
call,
new (Z) CheckEitherNonSmiInstr(
new (Z) Value(left), new (Z) Value(right), call->deopt_id()),
call->env(), FlowGraph::kEffect);
cid = kDoubleCid;
}
}
left =
UnboxInstr::Create(kUnboxedDouble, new (Z) Value(left),
call->deopt_id(), UnboxInstr::ValueMode::kCheckType);
InsertBefore(call, left, call->env(), FlowGraph::kValue);
right =
UnboxInstr::Create(kUnboxedDouble, new (Z) Value(right),
call->deopt_id(), UnboxInstr::ValueMode::kCheckType);
InsertBefore(call, right, call->env(), FlowGraph::kValue);
} else {
return false;
}
ASSERT(cid != kIllegalCid);
RelationalOpInstr* comp =
new (Z) RelationalOpInstr(call->source(), op_kind, new (Z) Value(left),
new (Z) Value(right), cid, call->deopt_id());
ReplaceCall(call, comp);
return true;
}
bool CallSpecializer::TryReplaceWithBinaryOp(InstanceCallInstr* call,
Token::Kind op_kind) {
intptr_t operands_type = kIllegalCid;
ASSERT(call->HasICData());
const BinaryFeedback& binary_feedback = call->BinaryFeedback();
switch (op_kind) {
case Token::kADD:
case Token::kSUB:
case Token::kMUL:
if (binary_feedback.OperandsAre(kSmiCid)) {
// Don't generate smi code if the IC data is marked because
// of an overflow.
operands_type =
call->ic_data()->HasDeoptReason(ICData::kDeoptBinarySmiOp)
? kMintCid
: kSmiCid;
} else if (binary_feedback.OperandsAreSmiOrMint()) {
// Don't generate mint code if the IC data is marked because of an
// overflow.
if (call->ic_data()->HasDeoptReason(ICData::kDeoptBinaryInt64Op))
return false;
operands_type = kMintCid;
} else if (ShouldSpecializeForDouble(binary_feedback)) {
operands_type = kDoubleCid;
} else if (binary_feedback.OperandsAre(kFloat32x4Cid)) {
operands_type = kFloat32x4Cid;
} else if (binary_feedback.OperandsAre(kInt32x4Cid)) {
ASSERT(op_kind != Token::kMUL); // Int32x4 doesn't have a multiply op.
operands_type = kInt32x4Cid;
} else if (binary_feedback.OperandsAre(kFloat64x2Cid)) {
operands_type = kFloat64x2Cid;
} else {
return false;
}
break;
case Token::kDIV:
if (ShouldSpecializeForDouble(binary_feedback) ||
binary_feedback.OperandsAre(kSmiCid)) {
operands_type = kDoubleCid;
} else if (binary_feedback.OperandsAre(kFloat32x4Cid)) {
operands_type = kFloat32x4Cid;
} else if (binary_feedback.OperandsAre(kFloat64x2Cid)) {
operands_type = kFloat64x2Cid;
} else {
return false;
}
break;
case Token::kBIT_AND:
case Token::kBIT_OR:
case Token::kBIT_XOR:
if (binary_feedback.OperandsAre(kSmiCid)) {
operands_type = kSmiCid;
} else if (binary_feedback.OperandsAreSmiOrMint()) {
operands_type = kMintCid;
} else if (binary_feedback.OperandsAre(kInt32x4Cid)) {
operands_type = kInt32x4Cid;
} else {
return false;
}
break;
case Token::kSHL:
case Token::kSHR:
case Token::kUSHR:
if (binary_feedback.OperandsAre(kSmiCid)) {
// Left shift may overflow from smi into mint.
// Don't generate smi code if the IC data is marked because
// of an overflow.
if (call->ic_data()->HasDeoptReason(ICData::kDeoptBinaryInt64Op)) {
return false;
}
operands_type =
call->ic_data()->HasDeoptReason(ICData::kDeoptBinarySmiOp)
? kMintCid
: kSmiCid;
} else if (binary_feedback.OperandsAreSmiOrMint() &&
binary_feedback.ArgumentIs(kSmiCid)) {
// Don't generate mint code if the IC data is marked because of an
// overflow.
if (call->ic_data()->HasDeoptReason(ICData::kDeoptBinaryInt64Op)) {
return false;
}
// Check for smi/mint << smi or smi/mint >> smi.
operands_type = kMintCid;
} else {
return false;
}
break;
case Token::kMOD:
case Token::kTRUNCDIV:
if (binary_feedback.OperandsAre(kSmiCid)) {
if (call->ic_data()->HasDeoptReason(ICData::kDeoptBinarySmiOp)) {
return false;
}
operands_type = kSmiCid;
} else {
return false;
}
break;
default:
UNREACHABLE();
}
ASSERT(call->type_args_len() == 0);
ASSERT(call->ArgumentCount() == 2);
Definition* left = call->ArgumentAt(0);
Definition* right = call->ArgumentAt(1);
if (operands_type == kDoubleCid) {
// Check that either left or right are not a smi. Result of a
// binary operation with two smis is a smi not a double, except '/' which
// returns a double for two smis.
if (op_kind != Token::kDIV) {
InsertBefore(
call,
new (Z) CheckEitherNonSmiInstr(
new (Z) Value(left), new (Z) Value(right), call->deopt_id()),
call->env(), FlowGraph::kEffect);
}
left =
UnboxInstr::Create(kUnboxedDouble, new (Z) Value(left),
call->deopt_id(), UnboxInstr::ValueMode::kCheckType);
InsertBefore(call, left, call->env(), FlowGraph::kValue);
right =
UnboxInstr::Create(kUnboxedDouble, new (Z) Value(right),
call->deopt_id(), UnboxInstr::ValueMode::kCheckType);
InsertBefore(call, right, call->env(), FlowGraph::kValue);
BinaryDoubleOpInstr* double_bin_op = new (Z)
BinaryDoubleOpInstr(op_kind, new (Z) Value(left), new (Z) Value(right),
call->deopt_id(), call->source());
ReplaceCall(call, double_bin_op);
} else if (operands_type == kMintCid) {
if ((op_kind == Token::kSHL) || (op_kind == Token::kSHR) ||
(op_kind == Token::kUSHR)) {
// left is unboxed, right is tagged.
left = UnboxInstr::Create(kUnboxedInt64, new (Z) Value(left),
call->deopt_id(),
UnboxInstr::ValueMode::kCheckType);
InsertBefore(call, left, call->env(), FlowGraph::kValue);
SpeculativeShiftInt64OpInstr* shift_op = new (Z)
SpeculativeShiftInt64OpInstr(op_kind, new (Z) Value(left),
new (Z) Value(right), call->deopt_id());
ReplaceCall(call, shift_op);
} else {
left = UnboxInstr::Create(kUnboxedInt64, new (Z) Value(left),
call->deopt_id(),
UnboxInstr::ValueMode::kCheckType);
InsertBefore(call, left, call->env(), FlowGraph::kValue);
right = UnboxInstr::Create(kUnboxedInt64, new (Z) Value(right),
call->deopt_id(),
UnboxInstr::ValueMode::kCheckType);
InsertBefore(call, right, call->env(), FlowGraph::kValue);
BinaryInt64OpInstr* bin_op = new (Z) BinaryInt64OpInstr(
op_kind, new (Z) Value(left), new (Z) Value(right), call->deopt_id());
ReplaceCall(call, bin_op);
}
} else if ((operands_type == kFloat32x4Cid) ||
(operands_type == kInt32x4Cid) ||
(operands_type == kFloat64x2Cid)) {
return InlineSimdBinaryOp(call, operands_type, op_kind);
} else if (op_kind == Token::kMOD) {
ASSERT(operands_type == kSmiCid);
if (right->IsConstant()) {
const Object& obj = right->AsConstant()->value();
if (obj.IsSmi() && Utils::IsPowerOfTwo(Smi::Cast(obj).Value())) {
// Insert smi check and attach a copy of the original environment
// because the smi operation can still deoptimize.
InsertBefore(call,
new (Z) CheckSmiInstr(new (Z) Value(left),
call->deopt_id(), call->source()),
call->env(), FlowGraph::kEffect);
ConstantInstr* constant = flow_graph()->GetConstant(
Smi::Handle(Z, Smi::New(Smi::Cast(obj).Value() - 1)));
BinarySmiOpInstr* bin_op =
new (Z) BinarySmiOpInstr(Token::kBIT_AND, new (Z) Value(left),
new (Z) Value(constant), call->deopt_id());
ReplaceCall(call, bin_op);
return true;
}
}
// Insert two smi checks and attach a copy of the original
// environment because the smi operation can still deoptimize.
AddCheckSmi(left, call->deopt_id(), call->env(), call);
AddCheckSmi(right, call->deopt_id(), call->env(), call);
BinarySmiOpInstr* bin_op = new (Z) BinarySmiOpInstr(
op_kind, new (Z) Value(left), new (Z) Value(right), call->deopt_id());
ReplaceCall(call, bin_op);
} else {
ASSERT(operands_type == kSmiCid);
// Insert two smi checks and attach a copy of the original
// environment because the smi operation can still deoptimize.
AddCheckSmi(left, call->deopt_id(), call->env(), call);
AddCheckSmi(right, call->deopt_id(), call->env(), call);
if (left->IsConstant() &&
((op_kind == Token::kADD) || (op_kind == Token::kMUL))) {
// Constant should be on the right side.
Definition* temp = left;
left = right;
right = temp;
}
BinarySmiOpInstr* bin_op = new (Z) BinarySmiOpInstr(
op_kind, new (Z) Value(left), new (Z) Value(right), call->deopt_id());
ReplaceCall(call, bin_op);
}
return true;
}
bool CallSpecializer::TryReplaceWithUnaryOp(InstanceCallInstr* call,
Token::Kind op_kind) {
ASSERT(call->type_args_len() == 0);
ASSERT(call->ArgumentCount() == 1);
Definition* input = call->ArgumentAt(0);
Definition* unary_op = nullptr;
if (call->Targets().ReceiverIs(kSmiCid)) {
InsertBefore(call,
new (Z) CheckSmiInstr(new (Z) Value(input), call->deopt_id(),
call->source()),
call->env(), FlowGraph::kEffect);
unary_op = new (Z)
UnarySmiOpInstr(op_kind, new (Z) Value(input), call->deopt_id());
} else if ((op_kind == Token::kBIT_NOT) &&
call->Targets().ReceiverIsSmiOrMint()) {
input =
UnboxInstr::Create(kUnboxedInt64, new (Z) Value(input),
call->deopt_id(), UnboxInstr::ValueMode::kCheckType);
InsertBefore(call, input, call->env(), FlowGraph::kValue);
unary_op = new (Z)
UnaryInt64OpInstr(op_kind, new (Z) Value(input), call->deopt_id());
} else if (call->Targets().ReceiverIs(kDoubleCid) &&
(op_kind == Token::kNEGATE)) {
AddReceiverCheck(call);
input =
UnboxInstr::Create(kUnboxedDouble, new (Z) Value(input),
call->deopt_id(), UnboxInstr::ValueMode::kCheckType);
InsertBefore(call, input, call->env(), FlowGraph::kValue);
unary_op = new (Z) UnaryDoubleOpInstr(Token::kNEGATE, new (Z) Value(input),
call->deopt_id());
} else {
return false;
}
ASSERT(unary_op != nullptr);
ReplaceCall(call, unary_op);
return true;
}
bool CallSpecializer::TryInlineImplicitInstanceGetter(InstanceCallInstr* call) {
const CallTargets& targets = call->Targets();
ASSERT(targets.HasSingleTarget());
// Inline implicit instance getter.
Field& field = Field::ZoneHandle(Z, targets.FirstTarget().accessor_field());
ASSERT(!field.IsNull());
if (field.needs_load_guard()) {
return false;
}
if (should_clone_fields_) {
field = field.CloneFromOriginal();
}
switch (flow_graph()->CheckForInstanceCall(
call, UntaggedFunction::kImplicitGetter)) {
case FlowGraph::ToCheck::kCheckNull:
AddCheckNull(call->Receiver(), call->function_name(), call->deopt_id(),
call->env(), call);
break;
case FlowGraph::ToCheck::kCheckCid:
if (CompilerState::Current().is_aot()) {
return false; // AOT cannot class check
}
AddReceiverCheck(call);
break;
case FlowGraph::ToCheck::kNoCheck:
break;
}
InlineImplicitInstanceGetter(call, field);
return true;
}
void CallSpecializer::InlineImplicitInstanceGetter(Definition* call,
const Field& field) {
ASSERT(field.is_instance());
Definition* receiver = call->ArgumentAt(0);
const bool calls_initializer = field.NeedsInitializationCheckOnLoad();
const Slot& slot = Slot::Get(field, &flow_graph()->parsed_function());
LoadFieldInstr* load = new (Z) LoadFieldInstr(
new (Z) Value(receiver), slot, call->source(), calls_initializer,
calls_initializer ? call->deopt_id() : DeoptId::kNone);
// Note that this is a case of LoadField -> InstanceCall lazy deopt.
// Which means that we don't need to remove arguments from the environment
// because normal getter call expects receiver pushed (unlike the case
// of LoadField -> LoadField deoptimization handled by
// FlowGraph::AttachEnvironment).
if (!calls_initializer) {
// If we don't call initializer then we don't need an environment.
call->RemoveEnvironment();
}
ReplaceCall(call, load);
if (load->slot().type().ToNullableCid() != kDynamicCid) {
// Reset value types if we know concrete cid.
for (Value::Iterator it(load->input_use_list()); !it.Done(); it.Advance()) {
it.Current()->SetReachingType(nullptr);
}
}
}
bool CallSpecializer::TryInlineInstanceSetter(InstanceCallInstr* instr) {
const CallTargets& targets = instr->Targets();
if (!targets.HasSingleTarget()) {
// Polymorphic sites are inlined like normal method calls by conventional
// inlining.
return false;
}
const Function& target = targets.FirstTarget();
if (target.kind() != UntaggedFunction::kImplicitSetter) {
// Non-implicit setter are inlined like normal method calls.
return false;
}
if (!CompilerState::Current().is_aot() && !target.WasCompiled()) {
return false;
}
Field& field = Field::ZoneHandle(Z, target.accessor_field());
ASSERT(!field.IsNull());
if (should_clone_fields_) {
field = field.CloneFromOriginal();
}
if (field.is_late() && field.is_final()) {
return false;
}
switch (flow_graph()->CheckForInstanceCall(
instr, UntaggedFunction::kImplicitSetter)) {
case FlowGraph::ToCheck::kCheckNull:
AddCheckNull(instr->Receiver(), instr->function_name(), instr->deopt_id(),
instr->env(), instr);
break;
case FlowGraph::ToCheck::kCheckCid:
if (CompilerState::Current().is_aot()) {
return false; // AOT cannot class check
}
AddReceiverCheck(instr);
break;
case FlowGraph::ToCheck::kNoCheck:
break;
}
// True if we can use unchecked entry into the setter.
bool is_unchecked_call = false;
if (!CompilerState::Current().is_aot()) {
if (targets.IsMonomorphic() && targets.MonomorphicExactness().IsExact()) {
if (targets.MonomorphicExactness().IsTriviallyExact()) {
flow_graph()->AddExactnessGuard(instr,
targets.MonomorphicReceiverCid());
}
is_unchecked_call = true;
}
}
if (IG->use_field_guards()) {
if (field.guarded_cid() != kDynamicCid) {
InsertSpeculativeBefore(
instr,
new (Z) GuardFieldClassInstr(new (Z) Value(instr->ArgumentAt(1)),
field, instr->deopt_id()),
instr->env(), FlowGraph::kEffect);
}
if (field.needs_length_check()) {
InsertSpeculativeBefore(
instr,
new (Z) GuardFieldLengthInstr(new (Z) Value(instr->ArgumentAt(1)),
field, instr->deopt_id()),
instr->env(), FlowGraph::kEffect);
}
if (field.static_type_exactness_state().NeedsFieldGuard()) {
InsertSpeculativeBefore(
instr,
new (Z) GuardFieldTypeInstr(new (Z) Value(instr->ArgumentAt(1)),
field, instr->deopt_id()),
instr->env(), FlowGraph::kEffect);
}
}
// Build an AssertAssignable if necessary.
const AbstractType& dst_type = AbstractType::ZoneHandle(zone(), field.type());
if (!dst_type.IsTopTypeForSubtyping()) {
// Compute if we need to type check the value. Always type check if
// at a dynamic invocation.
bool needs_check = true;
if (!instr->interface_target().IsNull()) {
if (field.is_covariant()) {
// Always type check covariant fields.
needs_check = true;
} else if (field.is_generic_covariant_impl()) {
// If field is generic covariant then we don't need to check it
// if the invocation was marked as unchecked (e.g. receiver of
// the invocation is also the receiver of the surrounding method).
// Note: we can't use flow_graph()->IsReceiver() for this optimization
// because strong mode only gives static guarantees at the AST level
// not at the SSA level.
needs_check = !(is_unchecked_call ||
(instr->entry_kind() == Code::EntryKind::kUnchecked));
} else {
// The rest of the stores are checked statically (we are not at
// a dynamic invocation).
needs_check = false;
}
}
if (needs_check) {
Definition* instantiator_type_args = flow_graph_->constant_null();
Definition* function_type_args = flow_graph_->constant_null();
if (!dst_type.IsInstantiated()) {
const Class& owner = Class::Handle(Z, field.Owner());
if (owner.NumTypeArguments() > 0) {
instantiator_type_args = new (Z) LoadFieldInstr(
new (Z) Value(instr->ArgumentAt(0)),
Slot::GetTypeArgumentsSlotFor(thread(), owner), instr->source());
InsertSpeculativeBefore(instr, instantiator_type_args, instr->env(),
FlowGraph::kValue);
}
}
auto assert_assignable = new (Z) AssertAssignableInstr(
instr->source(), new (Z) Value(instr->ArgumentAt(1)),
new (Z) Value(flow_graph_->GetConstant(dst_type)),
new (Z) Value(instantiator_type_args),
new (Z) Value(function_type_args),
String::ZoneHandle(zone(), field.name()), instr->deopt_id());
InsertSpeculativeBefore(instr, assert_assignable, instr->env(),
FlowGraph::kEffect);
}
}
// Field guard was detached.
ASSERT(instr->FirstArgIndex() == 0);
StoreFieldInstr* store = new (Z)
StoreFieldInstr(field, new (Z) Value(instr->ArgumentAt(0)),
new (Z) Value(instr->ArgumentAt(1)), kEmitStoreBarrier,
instr->source(), &flow_graph()->parsed_function());
// Discard the environment from the original instruction because the store
// can't deoptimize.
instr->RemoveEnvironment();
ReplaceCallWithResult(instr, store, flow_graph()->constant_null());
return true;
}
bool CallSpecializer::InlineSimdBinaryOp(InstanceCallInstr* call,
intptr_t cid,
Token::Kind op_kind) {
if (!ShouldInlineSimd()) {
return false;
}
ASSERT(call->type_args_len() == 0);
ASSERT(call->ArgumentCount() == 2);
Definition* const left = call->ArgumentAt(0);
Definition* const right = call->ArgumentAt(1);
// Type check left and right.
AddChecksForArgNr(call, left, /* arg_number = */ 0);
AddChecksForArgNr(call, right, /* arg_number = */ 1);
// Replace call.
SimdOpInstr* op = SimdOpInstr::Create(
SimdOpInstr::KindForOperator(cid, op_kind), new (Z) Value(left),
new (Z) Value(right), call->deopt_id());
ReplaceCall(call, op);
return true;
}
// Only unique implicit instance getters can be currently handled.
bool CallSpecializer::TryInlineInstanceGetter(InstanceCallInstr* call) {
const CallTargets& targets = call->Targets();
if (!targets.HasSingleTarget()) {
// Polymorphic sites are inlined like normal methods by conventional
// inlining in FlowGraphInliner.