-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Expand file tree
/
Copy pathaot_call_specializer.cc
More file actions
1202 lines (1064 loc) · 43.8 KB
/
aot_call_specializer.cc
File metadata and controls
1202 lines (1064 loc) · 43.8 KB
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) 2013, 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/aot/aot_call_specializer.h"
#include <utility>
#include "vm/bit_vector.h"
#include "vm/compiler/aot/precompiler.h"
#include "vm/compiler/backend/branch_optimizer.h"
#include "vm/compiler/backend/flow_graph_compiler.h"
#include "vm/compiler/backend/il.h"
#include "vm/compiler/backend/il_printer.h"
#include "vm/compiler/backend/inliner.h"
#include "vm/compiler/backend/range_analysis.h"
#include "vm/compiler/cha.h"
#include "vm/compiler/compiler_state.h"
#include "vm/compiler/frontend/flow_graph_builder.h"
#include "vm/compiler/jit/compiler.h"
#include "vm/compiler/jit/jit_call_specializer.h"
#include "vm/cpu.h"
#include "vm/dart_entry.h"
#include "vm/exceptions.h"
#include "vm/hash_map.h"
#include "vm/object.h"
#include "vm/object_store.h"
#include "vm/parser.h"
#include "vm/resolver.h"
#include "vm/scopes.h"
#include "vm/stack_frame.h"
#include "vm/symbols.h"
namespace dart {
DEFINE_FLAG(int,
max_exhaustive_polymorphic_checks,
5,
"If a call receiver is known to be of at most this many classes, "
"generate exhaustive class tests instead of a megamorphic call");
// Quick access to the current isolate and zone.
#define IG (isolate_group())
#define Z (zone())
#ifdef DART_PRECOMPILER
// Returns named function that is a unique dynamic target, i.e.,
// - the target is identified by its name alone, since it occurs only once.
// - target's class has no subclasses, and neither is subclassed, i.e.,
// the receiver type can be only the function's class.
// Returns Function::null() if there is no unique dynamic target for
// given 'fname'. 'fname' must be a symbol.
static void GetUniqueDynamicTarget(IsolateGroup* isolate_group,
const String& fname,
Object* function) {
UniqueFunctionsMap functions_map(
isolate_group->object_store()->unique_dynamic_targets());
ASSERT(fname.IsSymbol());
*function = functions_map.GetOrNull(fname);
ASSERT(functions_map.Release().ptr() ==
isolate_group->object_store()->unique_dynamic_targets());
}
AotCallSpecializer::AotCallSpecializer(
Precompiler* precompiler,
FlowGraph* flow_graph,
SpeculativeInliningPolicy* speculative_policy)
: CallSpecializer(flow_graph,
speculative_policy,
/* should_clone_fields=*/false),
precompiler_(precompiler),
has_unique_no_such_method_(false) {
Function& target_function = Function::Handle();
if (isolate_group()->object_store()->unique_dynamic_targets() !=
Array::null()) {
GetUniqueDynamicTarget(isolate_group(), Symbols::NoSuchMethod(),
&target_function);
has_unique_no_such_method_ = !target_function.IsNull();
}
}
bool AotCallSpecializer::TryCreateICDataForUniqueTarget(
InstanceCallInstr* call) {
if (isolate_group()->object_store()->unique_dynamic_targets() ==
Array::null()) {
return false;
}
// Check if the target is unique.
Function& target_function = Function::Handle(Z);
GetUniqueDynamicTarget(isolate_group(), call->function_name(),
&target_function);
if (target_function.IsNull()) {
return false;
}
// Calls passing named arguments and calls to a function taking named
// arguments must be resolved/checked at runtime.
// Calls passing a type argument vector and calls to a generic function must
// be resolved/checked at runtime.
if (target_function.HasOptionalNamedParameters() ||
target_function.IsGeneric() ||
!target_function.AreValidArgumentCounts(
call->type_args_len(), call->ArgumentCountWithoutTypeArgs(),
call->argument_names().IsNull() ? 0 : call->argument_names().Length(),
/* error_message = */ NULL)) {
return false;
}
const Class& cls = Class::Handle(Z, target_function.Owner());
intptr_t implementor_cid = kIllegalCid;
if (!CHA::HasSingleConcreteImplementation(cls, &implementor_cid)) {
return false;
}
call->SetTargets(
CallTargets::CreateMonomorphic(Z, implementor_cid, target_function));
ASSERT(call->Targets().IsMonomorphic());
// If we know that the only noSuchMethod is Object.noSuchMethod then
// this call is guaranteed to either succeed or throw.
if (has_unique_no_such_method_) {
call->set_has_unique_selector(true);
// Add redefinition of the receiver to prevent code motion across
// this call.
const intptr_t receiver_index = call->FirstArgIndex();
RedefinitionInstr* redefinition = new (Z)
RedefinitionInstr(new (Z) Value(call->ArgumentAt(receiver_index)));
flow_graph()->AllocateSSAIndex(redefinition);
redefinition->InsertAfter(call);
// Replace all uses of the receiver dominated by this call.
FlowGraph::RenameDominatedUses(call->ArgumentAt(receiver_index),
redefinition, redefinition);
if (!redefinition->HasUses()) {
redefinition->RemoveFromGraph();
}
}
return true;
}
bool AotCallSpecializer::TryCreateICData(InstanceCallInstr* call) {
if (TryCreateICDataForUniqueTarget(call)) {
return true;
}
return CallSpecializer::TryCreateICData(call);
}
bool AotCallSpecializer::RecognizeRuntimeTypeGetter(InstanceCallInstr* call) {
if ((precompiler_ == NULL) || !precompiler_->get_runtime_type_is_unique()) {
return false;
}
if (call->function_name().ptr() != Symbols::GetRuntimeType().ptr()) {
return false;
}
// There is only a single function Object.get:runtimeType that can be invoked
// by this call. Convert dynamic invocation to a static one.
const Class& cls = Class::Handle(Z, IG->object_store()->object_class());
const Function& function =
Function::Handle(Z, call->ResolveForReceiverClass(cls));
ASSERT(!function.IsNull());
const Function& target = Function::ZoneHandle(Z, function.ptr());
StaticCallInstr* static_call =
StaticCallInstr::FromCall(Z, call, target, call->CallCount());
// Since the result is either a Type or a FunctionType, we cannot pin it.
call->ReplaceWith(static_call, current_iterator());
return true;
}
static bool IsGetRuntimeType(Definition* defn) {
StaticCallInstr* call = defn->AsStaticCall();
return (call != NULL) && (call->function().recognized_kind() ==
MethodRecognizer::kObjectRuntimeType);
}
// Recognize a.runtimeType == b.runtimeType and fold it into
// Object._haveSameRuntimeType(a, b).
// Note: this optimization is not speculative.
bool AotCallSpecializer::TryReplaceWithHaveSameRuntimeType(
TemplateDartCall<0>* call) {
ASSERT((call->IsInstanceCall() &&
(call->AsInstanceCall()->ic_data()->NumArgsTested() == 2)) ||
call->IsStaticCall());
ASSERT(call->type_args_len() == 0);
ASSERT(call->ArgumentCount() == 2);
Definition* left = call->ArgumentAt(0);
Definition* right = call->ArgumentAt(1);
if (IsGetRuntimeType(left) && left->input_use_list()->IsSingleUse() &&
IsGetRuntimeType(right) && right->input_use_list()->IsSingleUse()) {
const Class& cls = Class::Handle(Z, IG->object_store()->object_class());
const Function& have_same_runtime_type = Function::ZoneHandle(
Z,
cls.LookupStaticFunctionAllowPrivate(Symbols::HaveSameRuntimeType()));
ASSERT(!have_same_runtime_type.IsNull());
InputsArray args(Z, 2);
args.Add(left->ArgumentValueAt(0)->CopyWithType(Z));
args.Add(right->ArgumentValueAt(0)->CopyWithType(Z));
const intptr_t kTypeArgsLen = 0;
StaticCallInstr* static_call = new (Z)
StaticCallInstr(call->source(), have_same_runtime_type, kTypeArgsLen,
Object::null_array(), // argument_names
std::move(args), call->deopt_id(), call->CallCount(),
ICData::kOptimized);
static_call->SetResultType(Z, CompileType::FromCid(kBoolCid));
ReplaceCall(call, static_call);
// ReplaceCall moved environment from 'call' to 'static_call'.
// Update arguments of 'static_call' in the environment.
Environment* env = static_call->env();
env->ValueAt(env->Length() - 2)
->BindToEnvironment(static_call->ArgumentAt(0));
env->ValueAt(env->Length() - 1)
->BindToEnvironment(static_call->ArgumentAt(1));
return true;
}
return false;
}
bool AotCallSpecializer::TryInlineFieldAccess(InstanceCallInstr* call) {
const Token::Kind op_kind = call->token_kind();
if ((op_kind == Token::kGET) && TryInlineInstanceGetter(call)) {
return true;
}
if ((op_kind == Token::kSET) && TryInlineInstanceSetter(call)) {
return true;
}
return false;
}
bool AotCallSpecializer::TryInlineFieldAccess(StaticCallInstr* call) {
if (call->function().IsImplicitGetterFunction()) {
Field& field = Field::ZoneHandle(call->function().accessor_field());
if (field.is_late()) {
// TODO(dartbug.com/40447): Inline implicit getters for late fields.
return false;
}
if (should_clone_fields_) {
field = field.CloneFromOriginal();
}
InlineImplicitInstanceGetter(call, field);
return true;
}
return false;
}
bool AotCallSpecializer::IsSupportedIntOperandForStaticDoubleOp(
CompileType* operand_type) {
if (operand_type->IsNullableInt()) {
if (operand_type->ToNullableCid() == kSmiCid) {
return true;
}
if (FlowGraphCompiler::CanConvertInt64ToDouble()) {
return true;
}
}
return false;
}
Value* AotCallSpecializer::PrepareStaticOpInput(Value* input,
intptr_t cid,
Instruction* call) {
ASSERT((cid == kDoubleCid) || (cid == kMintCid));
if (input->Type()->is_nullable()) {
const String& function_name =
(call->IsInstanceCall()
? call->AsInstanceCall()->function_name()
: String::ZoneHandle(Z, call->AsStaticCall()->function().name()));
AddCheckNull(input, function_name, call->deopt_id(), call->env(), call);
}
input = input->CopyWithType(Z);
if (cid == kDoubleCid && input->Type()->IsNullableInt()) {
Definition* conversion = NULL;
if (input->Type()->ToNullableCid() == kSmiCid) {
conversion = new (Z) SmiToDoubleInstr(input, call->source());
} else if (FlowGraphCompiler::CanConvertInt64ToDouble()) {
conversion = new (Z) Int64ToDoubleInstr(input, DeoptId::kNone,
Instruction::kNotSpeculative);
} else {
UNREACHABLE();
}
if (FLAG_trace_strong_mode_types) {
THR_Print("[Strong mode] Inserted %s\n", conversion->ToCString());
}
InsertBefore(call, conversion, /* env = */ NULL, FlowGraph::kValue);
return new (Z) Value(conversion);
}
return input;
}
CompileType AotCallSpecializer::BuildStrengthenedReceiverType(Value* input,
intptr_t cid) {
CompileType* old_type = input->Type();
CompileType* refined_type = old_type;
CompileType type = CompileType::None();
if (cid == kSmiCid) {
type = CompileType::NullableSmi();
refined_type = CompileType::ComputeRefinedType(old_type, &type);
} else if (cid == kMintCid) {
type = CompileType::NullableMint();
refined_type = CompileType::ComputeRefinedType(old_type, &type);
} else if (cid == kIntegerCid && !input->Type()->IsNullableInt()) {
type = CompileType::NullableInt();
refined_type = CompileType::ComputeRefinedType(old_type, &type);
} else if (cid == kDoubleCid && !input->Type()->IsNullableDouble()) {
type = CompileType::NullableDouble();
refined_type = CompileType::ComputeRefinedType(old_type, &type);
}
if (refined_type != old_type) {
return *refined_type;
}
return CompileType::None();
}
// After replacing a call with a specialized instruction, make sure to
// update types at all uses, as specialized instruction can provide a more
// specific type.
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);
}
}
bool AotCallSpecializer::TryOptimizeInstanceCallUsingStaticTypes(
InstanceCallInstr* instr) {
const Token::Kind op_kind = instr->token_kind();
return TryOptimizeIntegerOperation(instr, op_kind) ||
TryOptimizeDoubleOperation(instr, op_kind);
}
bool AotCallSpecializer::TryOptimizeStaticCallUsingStaticTypes(
StaticCallInstr* instr) {
const String& name = String::Handle(Z, instr->function().name());
const Token::Kind op_kind = MethodTokenRecognizer::RecognizeTokenKind(name);
if (op_kind == Token::kEQ && TryReplaceWithHaveSameRuntimeType(instr)) {
return true;
}
// We only specialize instance methods for int/double operations.
const auto& target = instr->function();
if (!target.IsDynamicFunction()) {
return false;
}
// For de-virtualized instance calls, we strengthen the type here manually
// because it might not be attached to the receiver.
// See http://dartbug.com/35179 for preserving the receiver type information.
const Class& owner = Class::Handle(Z, target.Owner());
const intptr_t cid = owner.id();
if (cid == kSmiCid || cid == kMintCid || cid == kIntegerCid ||
cid == kDoubleCid) {
// Sometimes TFA de-virtualizes instance calls to static calls. In such
// cases the VM might have a looser type on the receiver, so we explicitly
// tighten it (this is safe since it was proven that the receiver is either
// null or will end up with that target).
const intptr_t receiver_index = instr->FirstArgIndex();
const intptr_t argument_count = instr->ArgumentCountWithoutTypeArgs();
if (argument_count >= 1) {
auto receiver_value = instr->ArgumentValueAt(receiver_index);
auto receiver = receiver_value->definition();
auto type = BuildStrengthenedReceiverType(receiver_value, cid);
if (!type.IsNone()) {
auto redefinition =
flow_graph()->EnsureRedefinition(instr->previous(), receiver, type);
if (redefinition != nullptr) {
RefineUseTypes(redefinition);
}
}
}
}
return TryOptimizeIntegerOperation(instr, op_kind) ||
TryOptimizeDoubleOperation(instr, op_kind);
}
// Modulo against a constant power-of-two can be optimized into a mask.
// x % y -> x & (|y| - 1) for smi masks only
Definition* AotCallSpecializer::TryOptimizeMod(TemplateDartCall<0>* instr,
Token::Kind op_kind,
Value* left_value,
Value* right_value) {
if (!right_value->BindsToConstant()) {
return nullptr;
}
const Object& rhs = right_value->BoundConstant();
const int64_t value = Integer::Cast(rhs).AsInt64Value(); // smi and mint
if (value == kMinInt64) {
return nullptr; // non-smi mask
}
const int64_t modulus = Utils::Abs(value);
if (!Utils::IsPowerOfTwo(modulus) || !compiler::target::IsSmi(modulus - 1)) {
return nullptr;
}
left_value = PrepareStaticOpInput(left_value, kMintCid, instr);
#if defined(TARGET_ARCH_ARM)
Definition* right_definition = new (Z) UnboxedConstantInstr(
Smi::ZoneHandle(Z, Smi::New(modulus - 1)), kUnboxedInt32);
InsertBefore(instr, right_definition, /*env=*/NULL, FlowGraph::kValue);
right_definition = new (Z)
IntConverterInstr(kUnboxedInt32, kUnboxedInt64,
new (Z) Value(right_definition), DeoptId::kNone);
#else
Definition* right_definition = new (Z) UnboxedConstantInstr(
Smi::ZoneHandle(Z, Smi::New(modulus - 1)), kUnboxedInt64);
#endif
if (modulus == 1) return right_definition;
InsertBefore(instr, right_definition, /*env=*/NULL, FlowGraph::kValue);
right_value = new (Z) Value(right_definition);
return new (Z)
BinaryInt64OpInstr(Token::kBIT_AND, left_value, right_value,
DeoptId::kNone, Instruction::kNotSpeculative);
}
bool AotCallSpecializer::TryOptimizeIntegerOperation(TemplateDartCall<0>* instr,
Token::Kind op_kind) {
if (instr->type_args_len() != 0) {
// Arithmetic operations don't have type arguments.
return false;
}
Definition* replacement = NULL;
if (instr->ArgumentCount() == 2) {
Value* left_value = instr->ArgumentValueAt(0);
Value* right_value = instr->ArgumentValueAt(1);
CompileType* left_type = left_value->Type();
CompileType* right_type = right_value->Type();
bool has_nullable_int_args =
left_type->IsNullableInt() && right_type->IsNullableInt();
if (auto* call = instr->AsInstanceCall()) {
if (!call->CanReceiverBeSmiBasedOnInterfaceTarget(zone())) {
has_nullable_int_args = false;
}
}
// We only support binary operations if both operands are nullable integers
// or when we can use a cheap strict comparison operation.
if (!has_nullable_int_args) {
return false;
}
switch (op_kind) {
case Token::kEQ:
case Token::kNE: {
// If both arguments are nullable Smi or one of the arguments is
// a null or Smi and the other argument is nullable then emit
// StrictCompare (all arguments are going to be boxed anyway).
// Otherwise prefer EqualityCompare to avoid redundant boxing.
const bool left_is_null_or_smi =
left_type->IsNull() || left_type->IsNullableSmi();
const bool right_is_null_or_smi =
right_type->IsNull() || right_type->IsNullableSmi();
const bool both_are_nullable_smis =
left_type->IsNullableSmi() && right_type->IsNullableSmi();
const bool either_can_be_null =
left_type->is_nullable() || right_type->is_nullable();
if (both_are_nullable_smis ||
((left_is_null_or_smi || right_is_null_or_smi) &&
either_can_be_null)) {
replacement = new (Z) StrictCompareInstr(
instr->source(),
(op_kind == Token::kEQ) ? Token::kEQ_STRICT : Token::kNE_STRICT,
left_value->CopyWithType(Z), right_value->CopyWithType(Z),
/*needs_number_check=*/false, DeoptId::kNone);
} else {
replacement = new (Z) EqualityCompareInstr(
instr->source(), op_kind, left_value->CopyWithType(Z),
right_value->CopyWithType(Z), kMintCid, DeoptId::kNone,
/*null_aware=*/either_can_be_null, Instruction::kNotSpeculative);
}
break;
}
case Token::kLT:
case Token::kLTE:
case Token::kGT:
case Token::kGTE:
left_value = PrepareStaticOpInput(left_value, kMintCid, instr);
right_value = PrepareStaticOpInput(right_value, kMintCid, instr);
replacement = new (Z) RelationalOpInstr(
instr->source(), op_kind, left_value, right_value, kMintCid,
DeoptId::kNone, Instruction::kNotSpeculative);
break;
case Token::kMOD:
replacement = TryOptimizeMod(instr, op_kind, left_value, right_value);
if (replacement != nullptr) break;
FALL_THROUGH;
case Token::kTRUNCDIV:
#if !defined(TARGET_ARCH_IS_64_BIT)
// TODO(ajcbik): 32-bit archs too?
break;
#else
FALL_THROUGH;
#endif
case Token::kSHL:
FALL_THROUGH;
case Token::kSHR:
FALL_THROUGH;
case Token::kUSHR:
FALL_THROUGH;
case Token::kBIT_OR:
FALL_THROUGH;
case Token::kBIT_XOR:
FALL_THROUGH;
case Token::kBIT_AND:
FALL_THROUGH;
case Token::kADD:
FALL_THROUGH;
case Token::kSUB:
FALL_THROUGH;
case Token::kMUL: {
if (op_kind == Token::kSHL || op_kind == Token::kSHR ||
op_kind == Token::kUSHR) {
left_value = PrepareStaticOpInput(left_value, kMintCid, instr);
right_value = PrepareStaticOpInput(right_value, kMintCid, instr);
replacement = new (Z) ShiftInt64OpInstr(op_kind, left_value,
right_value, DeoptId::kNone);
} else {
left_value = PrepareStaticOpInput(left_value, kMintCid, instr);
right_value = PrepareStaticOpInput(right_value, kMintCid, instr);
replacement = new (Z)
BinaryInt64OpInstr(op_kind, left_value, right_value,
DeoptId::kNone, Instruction::kNotSpeculative);
}
break;
}
default:
break;
}
} else if (instr->ArgumentCount() == 1) {
Value* left_value = instr->ArgumentValueAt(0);
CompileType* left_type = left_value->Type();
// We only support unary operations on nullable integers.
if (!left_type->IsNullableInt()) {
return false;
}
if (op_kind == Token::kNEGATE || op_kind == Token::kBIT_NOT) {
left_value = PrepareStaticOpInput(left_value, kMintCid, instr);
replacement = new (Z) UnaryInt64OpInstr(
op_kind, left_value, DeoptId::kNone, Instruction::kNotSpeculative);
}
}
if (replacement != nullptr && !replacement->ComputeCanDeoptimize()) {
if (FLAG_trace_strong_mode_types) {
THR_Print("[Strong mode] Optimization: replacing %s with %s\n",
instr->ToCString(), replacement->ToCString());
}
ReplaceCall(instr, replacement);
RefineUseTypes(replacement);
return true;
}
return false;
}
bool AotCallSpecializer::TryOptimizeDoubleOperation(TemplateDartCall<0>* instr,
Token::Kind op_kind) {
if (instr->type_args_len() != 0) {
// Arithmetic operations don't have type arguments.
return false;
}
if (!FlowGraphCompiler::SupportsUnboxedDoubles()) {
return false;
}
Definition* replacement = NULL;
if (instr->ArgumentCount() == 2) {
Value* left_value = instr->ArgumentValueAt(0);
Value* right_value = instr->ArgumentValueAt(1);
CompileType* left_type = left_value->Type();
CompileType* right_type = right_value->Type();
if (!left_type->IsNullableDouble() &&
!IsSupportedIntOperandForStaticDoubleOp(left_type)) {
return false;
}
if (!right_type->IsNullableDouble() &&
!IsSupportedIntOperandForStaticDoubleOp(right_type)) {
return false;
}
switch (op_kind) {
case Token::kEQ:
FALL_THROUGH;
case Token::kNE: {
// TODO(dartbug.com/32166): Support EQ, NE for nullable doubles.
// (requires null-aware comparison instruction).
if (!left_type->is_nullable() && !right_type->is_nullable()) {
left_value = PrepareStaticOpInput(left_value, kDoubleCid, instr);
right_value = PrepareStaticOpInput(right_value, kDoubleCid, instr);
replacement = new (Z) EqualityCompareInstr(
instr->source(), op_kind, left_value, right_value, kDoubleCid,
DeoptId::kNone, /*null_aware=*/false,
Instruction::kNotSpeculative);
break;
}
break;
}
case Token::kLT:
FALL_THROUGH;
case Token::kLTE:
FALL_THROUGH;
case Token::kGT:
FALL_THROUGH;
case Token::kGTE: {
left_value = PrepareStaticOpInput(left_value, kDoubleCid, instr);
right_value = PrepareStaticOpInput(right_value, kDoubleCid, instr);
replacement = new (Z) RelationalOpInstr(
instr->source(), op_kind, left_value, right_value, kDoubleCid,
DeoptId::kNone, Instruction::kNotSpeculative);
break;
}
case Token::kADD:
FALL_THROUGH;
case Token::kSUB:
FALL_THROUGH;
case Token::kMUL:
FALL_THROUGH;
case Token::kDIV: {
left_value = PrepareStaticOpInput(left_value, kDoubleCid, instr);
right_value = PrepareStaticOpInput(right_value, kDoubleCid, instr);
replacement = new (Z) BinaryDoubleOpInstr(
op_kind, left_value, right_value, DeoptId::kNone, instr->source(),
Instruction::kNotSpeculative);
break;
}
case Token::kBIT_OR:
FALL_THROUGH;
case Token::kBIT_XOR:
FALL_THROUGH;
case Token::kBIT_AND:
FALL_THROUGH;
case Token::kMOD:
FALL_THROUGH;
case Token::kTRUNCDIV:
FALL_THROUGH;
default:
break;
}
} else if (instr->ArgumentCount() == 1) {
Value* left_value = instr->ArgumentValueAt(0);
CompileType* left_type = left_value->Type();
// We only support unary operations on nullable doubles.
if (!left_type->IsNullableDouble()) {
return false;
}
if (op_kind == Token::kNEGATE) {
left_value = PrepareStaticOpInput(left_value, kDoubleCid, instr);
replacement = new (Z)
UnaryDoubleOpInstr(Token::kNEGATE, left_value, instr->deopt_id(),
Instruction::kNotSpeculative);
}
}
if (replacement != NULL && !replacement->ComputeCanDeoptimize()) {
if (FLAG_trace_strong_mode_types) {
THR_Print("[Strong mode] Optimization: replacing %s with %s\n",
instr->ToCString(), replacement->ToCString());
}
ReplaceCall(instr, replacement);
RefineUseTypes(replacement);
return true;
}
return false;
}
// Tries to optimize instance call by replacing it with a faster instruction
// (e.g, binary op, field load, ..).
// TODO(dartbug.com/30635) Evaluate how much this can be shared with
// JitCallSpecializer.
void AotCallSpecializer::VisitInstanceCall(InstanceCallInstr* instr) {
// Type test is special as it always gets converted into inlined code.
const Token::Kind op_kind = instr->token_kind();
if (Token::IsTypeTestOperator(op_kind)) {
ReplaceWithInstanceOf(instr);
return;
}
if (TryInlineFieldAccess(instr)) {
return;
}
if (RecognizeRuntimeTypeGetter(instr)) {
return;
}
if ((op_kind == Token::kEQ) && TryReplaceWithHaveSameRuntimeType(instr)) {
return;
}
const CallTargets& targets = instr->Targets();
const intptr_t receiver_idx = instr->FirstArgIndex();
if (TryOptimizeInstanceCallUsingStaticTypes(instr)) {
return;
}
bool has_one_target = targets.HasSingleTarget();
if (has_one_target) {
// Check if the single target is a polymorphic target, if it is,
// we don't have one target.
const Function& target = targets.FirstTarget();
has_one_target = !target.is_polymorphic_target();
}
if (has_one_target) {
const Function& target = targets.FirstTarget();
UntaggedFunction::Kind function_kind = target.kind();
if (flow_graph()->CheckForInstanceCall(instr, function_kind) ==
FlowGraph::ToCheck::kNoCheck) {
StaticCallInstr* call = StaticCallInstr::FromCall(
Z, instr, target, targets.AggregateCallCount());
instr->ReplaceWith(call, current_iterator());
return;
}
}
// No IC data checks. Try resolve target using the propagated cid.
const intptr_t receiver_cid =
instr->ArgumentValueAt(receiver_idx)->Type()->ToCid();
if (receiver_cid != kDynamicCid && receiver_cid != kSentinelCid) {
const Class& receiver_class =
Class::Handle(Z, isolate_group()->class_table()->At(receiver_cid));
const Function& function =
Function::Handle(Z, instr->ResolveForReceiverClass(receiver_class));
if (!function.IsNull()) {
const Function& target = Function::ZoneHandle(Z, function.ptr());
StaticCallInstr* call =
StaticCallInstr::FromCall(Z, instr, target, instr->CallCount());
instr->ReplaceWith(call, current_iterator());
return;
}
}
// Check for x == y, where x has type T?, there are no subtypes of T, and
// T does not override ==. Replace with StrictCompare.
if (instr->token_kind() == Token::kEQ || instr->token_kind() == Token::kNE) {
GrowableArray<intptr_t> class_ids(6);
if (instr->ArgumentValueAt(receiver_idx)->Type()->Specialize(&class_ids)) {
bool is_object_eq = true;
for (intptr_t i = 0; i < class_ids.length(); i++) {
const intptr_t cid = class_ids[i];
// Skip sentinel cid. It may appear in the unreachable code after
// inlining a method which doesn't return.
if (cid == kSentinelCid) continue;
const Class& cls =
Class::Handle(Z, isolate_group()->class_table()->At(cid));
const Function& target =
Function::Handle(Z, instr->ResolveForReceiverClass(cls));
if (target.recognized_kind() != MethodRecognizer::kObjectEquals) {
is_object_eq = false;
break;
}
}
if (is_object_eq) {
auto* replacement = new (Z) StrictCompareInstr(
instr->source(),
(instr->token_kind() == Token::kEQ) ? Token::kEQ_STRICT
: Token::kNE_STRICT,
instr->ArgumentValueAt(0)->CopyWithType(Z),
instr->ArgumentValueAt(1)->CopyWithType(Z),
/*needs_number_check=*/false, DeoptId::kNone);
ReplaceCall(instr, replacement);
RefineUseTypes(replacement);
return;
}
}
}
Definition* callee_receiver = instr->ArgumentAt(receiver_idx);
const Function& function = flow_graph()->function();
Class& receiver_class = Class::Handle(Z);
if (function.IsDynamicFunction() &&
flow_graph()->IsReceiver(callee_receiver)) {
// Call receiver is method receiver.
receiver_class = function.Owner();
} else {
// Check if we have an non-nullable compile type for the receiver.
CompileType* type = instr->ArgumentAt(receiver_idx)->Type();
if (type->ToAbstractType()->IsType() &&
!type->ToAbstractType()->IsDynamicType() && !type->is_nullable()) {
receiver_class = type->ToAbstractType()->type_class();
if (receiver_class.is_implemented()) {
receiver_class = Class::null();
}
}
}
if (!receiver_class.IsNull()) {
GrowableArray<intptr_t> class_ids(6);
if (thread()->compiler_state().cha().ConcreteSubclasses(receiver_class,
&class_ids)) {
// First check if all subclasses end up calling the same method.
// If this is the case we will replace instance call with a direct
// static call.
// Otherwise we will try to create ICData that contains all possible
// targets with appropriate checks.
Function& single_target = Function::Handle(Z);
ICData& ic_data = ICData::Handle(Z);
const Array& args_desc_array =
Array::Handle(Z, instr->GetArgumentsDescriptor());
Function& target = Function::Handle(Z);
Class& cls = Class::Handle(Z);
for (intptr_t i = 0; i < class_ids.length(); i++) {
const intptr_t cid = class_ids[i];
cls = isolate_group()->class_table()->At(cid);
target = instr->ResolveForReceiverClass(cls);
ASSERT(target.IsNull() || !target.IsInvokeFieldDispatcher());
if (target.IsNull()) {
single_target = Function::null();
ic_data = ICData::null();
break;
} else if (ic_data.IsNull()) {
// First we are trying to compute a single target for all subclasses.
if (single_target.IsNull()) {
ASSERT(i == 0);
single_target = target.ptr();
continue;
} else if (single_target.ptr() == target.ptr()) {
continue;
}
// The call does not resolve to a single target within the hierarchy.
// If we have too many subclasses abort the optimization.
if (class_ids.length() > FLAG_max_exhaustive_polymorphic_checks) {
single_target = Function::null();
break;
}
// Create an ICData and map all previously seen classes (< i) to
// the computed single_target.
ic_data = ICData::New(function, instr->function_name(),
args_desc_array, DeoptId::kNone,
/* args_tested = */ 1, ICData::kOptimized);
for (intptr_t j = 0; j < i; j++) {
ic_data.AddReceiverCheck(class_ids[j], single_target);
}
single_target = Function::null();
}
ASSERT(ic_data.ptr() != ICData::null());
ASSERT(single_target.ptr() == Function::null());
ic_data.AddReceiverCheck(cid, target);
}
if (single_target.ptr() != Function::null()) {
// If this is a getter or setter invocation try inlining it right away
// instead of replacing it with a static call.
if ((op_kind == Token::kGET) || (op_kind == Token::kSET)) {
// Create fake IC data with the resolved target.
const ICData& ic_data = ICData::Handle(
ICData::New(flow_graph()->function(), instr->function_name(),
args_desc_array, DeoptId::kNone,
/* args_tested = */ 1, ICData::kOptimized));
cls = single_target.Owner();
ic_data.AddReceiverCheck(cls.id(), single_target);
instr->set_ic_data(&ic_data);
if (TryInlineFieldAccess(instr)) {
return;
}
}
// We have computed that there is only a single target for this call
// within the whole hierarchy. Replace InstanceCall with StaticCall.
const Function& target = Function::ZoneHandle(Z, single_target.ptr());
StaticCallInstr* call =
StaticCallInstr::FromCall(Z, instr, target, instr->CallCount());
instr->ReplaceWith(call, current_iterator());
return;
} else if ((ic_data.ptr() != ICData::null()) &&
!ic_data.NumberOfChecksIs(0)) {
const CallTargets* targets = CallTargets::Create(Z, ic_data);
ASSERT(!targets->is_empty());
PolymorphicInstanceCallInstr* call =
PolymorphicInstanceCallInstr::FromCall(Z, instr, *targets,
/* complete = */ true);
instr->ReplaceWith(call, current_iterator());
return;
}
}
// Detect if o.m(...) is a call through a getter and expand it
// into o.get:m().call(...).
if (TryExpandCallThroughGetter(receiver_class, instr)) {
return;
}
}
// More than one target. Generate generic polymorphic call without
// deoptimization.
if (targets.length() > 0) {
ASSERT(!FLAG_polymorphic_with_deopt);
// OK to use checks with PolymorphicInstanceCallInstr since no
// deoptimization is allowed.
PolymorphicInstanceCallInstr* call =
PolymorphicInstanceCallInstr::FromCall(Z, instr, targets,
/* complete = */ false);
instr->ReplaceWith(call, current_iterator());
return;
}
}
void AotCallSpecializer::VisitStaticCall(StaticCallInstr* instr) {
if (TryInlineFieldAccess(instr)) {
return;
}
CallSpecializer::VisitStaticCall(instr);
}
bool AotCallSpecializer::TryExpandCallThroughGetter(const Class& receiver_class,
InstanceCallInstr* call) {
// If it's an accessor call it can't be a call through getter.
if (call->token_kind() == Token::kGET || call->token_kind() == Token::kSET) {
return false;
}
// Ignore callsites like f.call() for now. Those need to be handled
// specially if f is a closure.
if (call->function_name().ptr() == Symbols::call().ptr()) {
return false;
}
Function& target = Function::Handle(Z);
const String& getter_name =
String::ZoneHandle(Z, Symbols::FromGet(thread(), call->function_name()));
const Array& args_desc_array = Array::Handle(
Z,
ArgumentsDescriptor::NewBoxed(/*type_args_len=*/0, /*num_arguments=*/1));
ArgumentsDescriptor args_desc(args_desc_array);
target = Resolver::ResolveDynamicForReceiverClass(
receiver_class, getter_name, args_desc, /*allow_add=*/false);
if (target.ptr() == Function::null() || target.IsMethodExtractor()) {
return false;
}
// We found a getter with the same name as the method this
// call tries to invoke. This implies call through getter
// because methods can't override getters. Build
// o.get:m().call(...) sequence and replace o.m(...) invocation.
const intptr_t receiver_idx = call->type_args_len() > 0 ? 1 : 0;
InputsArray get_arguments(Z, 1);
get_arguments.Add(call->ArgumentValueAt(receiver_idx)->CopyWithType(Z));
InstanceCallInstr* invoke_get = new (Z) InstanceCallInstr(
call->source(), getter_name, Token::kGET, std::move(get_arguments),
/*type_args_len=*/0,
/*argument_names=*/Object::empty_array(),
/*checked_argument_count=*/1,
thread()->compiler_state().GetNextDeoptId());
// Arguments to the .call() are the same as arguments to the
// original call (including type arguments), but receiver
// is replaced with the result of the get.
InputsArray call_arguments(Z, call->ArgumentCount());
if (call->type_args_len() > 0) {
call_arguments.Add(call->ArgumentValueAt(0)->CopyWithType(Z));
}
call_arguments.Add(new (Z) Value(invoke_get));
for (intptr_t i = receiver_idx + 1; i < call->ArgumentCount(); i++) {
call_arguments.Add(call->ArgumentValueAt(i)->CopyWithType(Z));
}