-
Notifications
You must be signed in to change notification settings - Fork 30.5k
/
Copy pathlithium-codegen-arm64.cc
6125 lines (5085 loc) Β· 208 KB
/
lithium-codegen-arm64.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 2013 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/v8.h"
#include "src/arm64/lithium-codegen-arm64.h"
#include "src/arm64/lithium-gap-resolver-arm64.h"
#include "src/base/bits.h"
#include "src/code-factory.h"
#include "src/code-stubs.h"
#include "src/cpu-profiler.h"
#include "src/hydrogen-osr.h"
#include "src/ic/ic.h"
#include "src/ic/stub-cache.h"
namespace v8 {
namespace internal {
class SafepointGenerator final : public CallWrapper {
public:
SafepointGenerator(LCodeGen* codegen,
LPointerMap* pointers,
Safepoint::DeoptMode mode)
: codegen_(codegen),
pointers_(pointers),
deopt_mode_(mode) { }
virtual ~SafepointGenerator() { }
virtual void BeforeCall(int call_size) const { }
virtual void AfterCall() const {
codegen_->RecordSafepoint(pointers_, deopt_mode_);
}
private:
LCodeGen* codegen_;
LPointerMap* pointers_;
Safepoint::DeoptMode deopt_mode_;
};
#define __ masm()->
// Emit code to branch if the given condition holds.
// The code generated here doesn't modify the flags and they must have
// been set by some prior instructions.
//
// The EmitInverted function simply inverts the condition.
class BranchOnCondition : public BranchGenerator {
public:
BranchOnCondition(LCodeGen* codegen, Condition cond)
: BranchGenerator(codegen),
cond_(cond) { }
virtual void Emit(Label* label) const {
__ B(cond_, label);
}
virtual void EmitInverted(Label* label) const {
if (cond_ != al) {
__ B(NegateCondition(cond_), label);
}
}
private:
Condition cond_;
};
// Emit code to compare lhs and rhs and branch if the condition holds.
// This uses MacroAssembler's CompareAndBranch function so it will handle
// converting the comparison to Cbz/Cbnz if the right-hand side is 0.
//
// EmitInverted still compares the two operands but inverts the condition.
class CompareAndBranch : public BranchGenerator {
public:
CompareAndBranch(LCodeGen* codegen,
Condition cond,
const Register& lhs,
const Operand& rhs)
: BranchGenerator(codegen),
cond_(cond),
lhs_(lhs),
rhs_(rhs) { }
virtual void Emit(Label* label) const {
__ CompareAndBranch(lhs_, rhs_, cond_, label);
}
virtual void EmitInverted(Label* label) const {
__ CompareAndBranch(lhs_, rhs_, NegateCondition(cond_), label);
}
private:
Condition cond_;
const Register& lhs_;
const Operand& rhs_;
};
// Test the input with the given mask and branch if the condition holds.
// If the condition is 'eq' or 'ne' this will use MacroAssembler's
// TestAndBranchIfAllClear and TestAndBranchIfAnySet so it will handle the
// conversion to Tbz/Tbnz when possible.
class TestAndBranch : public BranchGenerator {
public:
TestAndBranch(LCodeGen* codegen,
Condition cond,
const Register& value,
uint64_t mask)
: BranchGenerator(codegen),
cond_(cond),
value_(value),
mask_(mask) { }
virtual void Emit(Label* label) const {
switch (cond_) {
case eq:
__ TestAndBranchIfAllClear(value_, mask_, label);
break;
case ne:
__ TestAndBranchIfAnySet(value_, mask_, label);
break;
default:
__ Tst(value_, mask_);
__ B(cond_, label);
}
}
virtual void EmitInverted(Label* label) const {
// The inverse of "all clear" is "any set" and vice versa.
switch (cond_) {
case eq:
__ TestAndBranchIfAnySet(value_, mask_, label);
break;
case ne:
__ TestAndBranchIfAllClear(value_, mask_, label);
break;
default:
__ Tst(value_, mask_);
__ B(NegateCondition(cond_), label);
}
}
private:
Condition cond_;
const Register& value_;
uint64_t mask_;
};
// Test the input and branch if it is non-zero and not a NaN.
class BranchIfNonZeroNumber : public BranchGenerator {
public:
BranchIfNonZeroNumber(LCodeGen* codegen, const FPRegister& value,
const FPRegister& scratch)
: BranchGenerator(codegen), value_(value), scratch_(scratch) { }
virtual void Emit(Label* label) const {
__ Fabs(scratch_, value_);
// Compare with 0.0. Because scratch_ is positive, the result can be one of
// nZCv (equal), nzCv (greater) or nzCV (unordered).
__ Fcmp(scratch_, 0.0);
__ B(gt, label);
}
virtual void EmitInverted(Label* label) const {
__ Fabs(scratch_, value_);
__ Fcmp(scratch_, 0.0);
__ B(le, label);
}
private:
const FPRegister& value_;
const FPRegister& scratch_;
};
// Test the input and branch if it is a heap number.
class BranchIfHeapNumber : public BranchGenerator {
public:
BranchIfHeapNumber(LCodeGen* codegen, const Register& value)
: BranchGenerator(codegen), value_(value) { }
virtual void Emit(Label* label) const {
__ JumpIfHeapNumber(value_, label);
}
virtual void EmitInverted(Label* label) const {
__ JumpIfNotHeapNumber(value_, label);
}
private:
const Register& value_;
};
// Test the input and branch if it is the specified root value.
class BranchIfRoot : public BranchGenerator {
public:
BranchIfRoot(LCodeGen* codegen, const Register& value,
Heap::RootListIndex index)
: BranchGenerator(codegen), value_(value), index_(index) { }
virtual void Emit(Label* label) const {
__ JumpIfRoot(value_, index_, label);
}
virtual void EmitInverted(Label* label) const {
__ JumpIfNotRoot(value_, index_, label);
}
private:
const Register& value_;
const Heap::RootListIndex index_;
};
void LCodeGen::WriteTranslation(LEnvironment* environment,
Translation* translation) {
if (environment == NULL) return;
// The translation includes one command per value in the environment.
int translation_size = environment->translation_size();
WriteTranslation(environment->outer(), translation);
WriteTranslationFrame(environment, translation);
int object_index = 0;
int dematerialized_index = 0;
for (int i = 0; i < translation_size; ++i) {
LOperand* value = environment->values()->at(i);
AddToTranslation(
environment, translation, value, environment->HasTaggedValueAt(i),
environment->HasUint32ValueAt(i), &object_index, &dematerialized_index);
}
}
void LCodeGen::AddToTranslation(LEnvironment* environment,
Translation* translation,
LOperand* op,
bool is_tagged,
bool is_uint32,
int* object_index_pointer,
int* dematerialized_index_pointer) {
if (op == LEnvironment::materialization_marker()) {
int object_index = (*object_index_pointer)++;
if (environment->ObjectIsDuplicateAt(object_index)) {
int dupe_of = environment->ObjectDuplicateOfAt(object_index);
translation->DuplicateObject(dupe_of);
return;
}
int object_length = environment->ObjectLengthAt(object_index);
if (environment->ObjectIsArgumentsAt(object_index)) {
translation->BeginArgumentsObject(object_length);
} else {
translation->BeginCapturedObject(object_length);
}
int dematerialized_index = *dematerialized_index_pointer;
int env_offset = environment->translation_size() + dematerialized_index;
*dematerialized_index_pointer += object_length;
for (int i = 0; i < object_length; ++i) {
LOperand* value = environment->values()->at(env_offset + i);
AddToTranslation(environment,
translation,
value,
environment->HasTaggedValueAt(env_offset + i),
environment->HasUint32ValueAt(env_offset + i),
object_index_pointer,
dematerialized_index_pointer);
}
return;
}
if (op->IsStackSlot()) {
if (is_tagged) {
translation->StoreStackSlot(op->index());
} else if (is_uint32) {
translation->StoreUint32StackSlot(op->index());
} else {
translation->StoreInt32StackSlot(op->index());
}
} else if (op->IsDoubleStackSlot()) {
translation->StoreDoubleStackSlot(op->index());
} else if (op->IsRegister()) {
Register reg = ToRegister(op);
if (is_tagged) {
translation->StoreRegister(reg);
} else if (is_uint32) {
translation->StoreUint32Register(reg);
} else {
translation->StoreInt32Register(reg);
}
} else if (op->IsDoubleRegister()) {
DoubleRegister reg = ToDoubleRegister(op);
translation->StoreDoubleRegister(reg);
} else if (op->IsConstantOperand()) {
HConstant* constant = chunk()->LookupConstant(LConstantOperand::cast(op));
int src_index = DefineDeoptimizationLiteral(constant->handle(isolate()));
translation->StoreLiteral(src_index);
} else {
UNREACHABLE();
}
}
void LCodeGen::RegisterEnvironmentForDeoptimization(LEnvironment* environment,
Safepoint::DeoptMode mode) {
environment->set_has_been_used();
if (!environment->HasBeenRegistered()) {
int frame_count = 0;
int jsframe_count = 0;
for (LEnvironment* e = environment; e != NULL; e = e->outer()) {
++frame_count;
if (e->frame_type() == JS_FUNCTION) {
++jsframe_count;
}
}
Translation translation(&translations_, frame_count, jsframe_count, zone());
WriteTranslation(environment, &translation);
int deoptimization_index = deoptimizations_.length();
int pc_offset = masm()->pc_offset();
environment->Register(deoptimization_index,
translation.index(),
(mode == Safepoint::kLazyDeopt) ? pc_offset : -1);
deoptimizations_.Add(environment, zone());
}
}
void LCodeGen::CallCode(Handle<Code> code,
RelocInfo::Mode mode,
LInstruction* instr) {
CallCodeGeneric(code, mode, instr, RECORD_SIMPLE_SAFEPOINT);
}
void LCodeGen::CallCodeGeneric(Handle<Code> code,
RelocInfo::Mode mode,
LInstruction* instr,
SafepointMode safepoint_mode) {
DCHECK(instr != NULL);
Assembler::BlockPoolsScope scope(masm_);
__ Call(code, mode);
RecordSafepointWithLazyDeopt(instr, safepoint_mode);
if ((code->kind() == Code::BINARY_OP_IC) ||
(code->kind() == Code::COMPARE_IC)) {
// Signal that we don't inline smi code before these stubs in the
// optimizing code generator.
InlineSmiCheckInfo::EmitNotInlined(masm());
}
}
void LCodeGen::DoCallFunction(LCallFunction* instr) {
DCHECK(ToRegister(instr->context()).is(cp));
DCHECK(ToRegister(instr->function()).Is(x1));
DCHECK(ToRegister(instr->result()).Is(x0));
int arity = instr->arity();
CallFunctionFlags flags = instr->hydrogen()->function_flags();
if (instr->hydrogen()->HasVectorAndSlot()) {
Register slot_register = ToRegister(instr->temp_slot());
Register vector_register = ToRegister(instr->temp_vector());
DCHECK(slot_register.is(x3));
DCHECK(vector_register.is(x2));
AllowDeferredHandleDereference vector_structure_check;
Handle<TypeFeedbackVector> vector = instr->hydrogen()->feedback_vector();
int index = vector->GetIndex(instr->hydrogen()->slot());
__ Mov(vector_register, vector);
__ Mov(slot_register, Operand(Smi::FromInt(index)));
CallICState::CallType call_type =
(flags & CALL_AS_METHOD) ? CallICState::METHOD : CallICState::FUNCTION;
Handle<Code> ic =
CodeFactory::CallICInOptimizedCode(isolate(), arity, call_type).code();
CallCode(ic, RelocInfo::CODE_TARGET, instr);
} else {
CallFunctionStub stub(isolate(), arity, flags);
CallCode(stub.GetCode(), RelocInfo::CODE_TARGET, instr);
}
RecordPushedArgumentsDelta(instr->hydrogen()->argument_delta());
}
void LCodeGen::DoCallNew(LCallNew* instr) {
DCHECK(ToRegister(instr->context()).is(cp));
DCHECK(instr->IsMarkedAsCall());
DCHECK(ToRegister(instr->constructor()).is(x1));
__ Mov(x0, instr->arity());
// No cell in x2 for construct type feedback in optimized code.
__ LoadRoot(x2, Heap::kUndefinedValueRootIndex);
CallConstructStub stub(isolate(), NO_CALL_CONSTRUCTOR_FLAGS);
CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
RecordPushedArgumentsDelta(instr->hydrogen()->argument_delta());
DCHECK(ToRegister(instr->result()).is(x0));
}
void LCodeGen::DoCallNewArray(LCallNewArray* instr) {
DCHECK(instr->IsMarkedAsCall());
DCHECK(ToRegister(instr->context()).is(cp));
DCHECK(ToRegister(instr->constructor()).is(x1));
__ Mov(x0, Operand(instr->arity()));
if (instr->arity() == 1) {
// We only need the allocation site for the case we have a length argument.
// The case may bail out to the runtime, which will determine the correct
// elements kind with the site.
__ Mov(x2, instr->hydrogen()->site());
} else {
__ LoadRoot(x2, Heap::kUndefinedValueRootIndex);
}
ElementsKind kind = instr->hydrogen()->elements_kind();
AllocationSiteOverrideMode override_mode =
(AllocationSite::GetMode(kind) == TRACK_ALLOCATION_SITE)
? DISABLE_ALLOCATION_SITES
: DONT_OVERRIDE;
if (instr->arity() == 0) {
ArrayNoArgumentConstructorStub stub(isolate(), kind, override_mode);
CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
} else if (instr->arity() == 1) {
Label done;
if (IsFastPackedElementsKind(kind)) {
Label packed_case;
// We might need to create a holey array; look at the first argument.
__ Peek(x10, 0);
__ Cbz(x10, &packed_case);
ElementsKind holey_kind = GetHoleyElementsKind(kind);
ArraySingleArgumentConstructorStub stub(isolate(),
holey_kind,
override_mode);
CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
__ B(&done);
__ Bind(&packed_case);
}
ArraySingleArgumentConstructorStub stub(isolate(), kind, override_mode);
CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
__ Bind(&done);
} else {
ArrayNArgumentsConstructorStub stub(isolate(), kind, override_mode);
CallCode(stub.GetCode(), RelocInfo::CONSTRUCT_CALL, instr);
}
RecordPushedArgumentsDelta(instr->hydrogen()->argument_delta());
DCHECK(ToRegister(instr->result()).is(x0));
}
void LCodeGen::CallRuntime(const Runtime::Function* function,
int num_arguments,
LInstruction* instr,
SaveFPRegsMode save_doubles) {
DCHECK(instr != NULL);
__ CallRuntime(function, num_arguments, save_doubles);
RecordSafepointWithLazyDeopt(instr, RECORD_SIMPLE_SAFEPOINT);
}
void LCodeGen::LoadContextFromDeferred(LOperand* context) {
if (context->IsRegister()) {
__ Mov(cp, ToRegister(context));
} else if (context->IsStackSlot()) {
__ Ldr(cp, ToMemOperand(context, kMustUseFramePointer));
} else if (context->IsConstantOperand()) {
HConstant* constant =
chunk_->LookupConstant(LConstantOperand::cast(context));
__ LoadHeapObject(cp,
Handle<HeapObject>::cast(constant->handle(isolate())));
} else {
UNREACHABLE();
}
}
void LCodeGen::CallRuntimeFromDeferred(Runtime::FunctionId id,
int argc,
LInstruction* instr,
LOperand* context) {
LoadContextFromDeferred(context);
__ CallRuntimeSaveDoubles(id);
RecordSafepointWithRegisters(
instr->pointer_map(), argc, Safepoint::kNoLazyDeopt);
}
void LCodeGen::RecordAndWritePosition(int position) {
if (position == RelocInfo::kNoPosition) return;
masm()->positions_recorder()->RecordPosition(position);
masm()->positions_recorder()->WriteRecordedPositions();
}
void LCodeGen::RecordSafepointWithLazyDeopt(LInstruction* instr,
SafepointMode safepoint_mode) {
if (safepoint_mode == RECORD_SIMPLE_SAFEPOINT) {
RecordSafepoint(instr->pointer_map(), Safepoint::kLazyDeopt);
} else {
DCHECK(safepoint_mode == RECORD_SAFEPOINT_WITH_REGISTERS_AND_NO_ARGUMENTS);
RecordSafepointWithRegisters(
instr->pointer_map(), 0, Safepoint::kLazyDeopt);
}
}
void LCodeGen::RecordSafepoint(LPointerMap* pointers,
Safepoint::Kind kind,
int arguments,
Safepoint::DeoptMode deopt_mode) {
DCHECK(expected_safepoint_kind_ == kind);
const ZoneList<LOperand*>* operands = pointers->GetNormalizedOperands();
Safepoint safepoint = safepoints_.DefineSafepoint(
masm(), kind, arguments, deopt_mode);
for (int i = 0; i < operands->length(); i++) {
LOperand* pointer = operands->at(i);
if (pointer->IsStackSlot()) {
safepoint.DefinePointerSlot(pointer->index(), zone());
} else if (pointer->IsRegister() && (kind & Safepoint::kWithRegisters)) {
safepoint.DefinePointerRegister(ToRegister(pointer), zone());
}
}
}
void LCodeGen::RecordSafepoint(LPointerMap* pointers,
Safepoint::DeoptMode deopt_mode) {
RecordSafepoint(pointers, Safepoint::kSimple, 0, deopt_mode);
}
void LCodeGen::RecordSafepoint(Safepoint::DeoptMode deopt_mode) {
LPointerMap empty_pointers(zone());
RecordSafepoint(&empty_pointers, deopt_mode);
}
void LCodeGen::RecordSafepointWithRegisters(LPointerMap* pointers,
int arguments,
Safepoint::DeoptMode deopt_mode) {
RecordSafepoint(pointers, Safepoint::kWithRegisters, arguments, deopt_mode);
}
bool LCodeGen::GenerateCode() {
LPhase phase("Z_Code generation", chunk());
DCHECK(is_unused());
status_ = GENERATING;
// Open a frame scope to indicate that there is a frame on the stack. The
// NONE indicates that the scope shouldn't actually generate code to set up
// the frame (that is done in GeneratePrologue).
FrameScope frame_scope(masm_, StackFrame::NONE);
return GeneratePrologue() && GenerateBody() && GenerateDeferredCode() &&
GenerateJumpTable() && GenerateSafepointTable();
}
void LCodeGen::SaveCallerDoubles() {
DCHECK(info()->saves_caller_doubles());
DCHECK(NeedsEagerFrame());
Comment(";;; Save clobbered callee double registers");
BitVector* doubles = chunk()->allocated_double_registers();
BitVector::Iterator iterator(doubles);
int count = 0;
while (!iterator.Done()) {
// TODO(all): Is this supposed to save just the callee-saved doubles? It
// looks like it's saving all of them.
FPRegister value = FPRegister::FromAllocationIndex(iterator.Current());
__ Poke(value, count * kDoubleSize);
iterator.Advance();
count++;
}
}
void LCodeGen::RestoreCallerDoubles() {
DCHECK(info()->saves_caller_doubles());
DCHECK(NeedsEagerFrame());
Comment(";;; Restore clobbered callee double registers");
BitVector* doubles = chunk()->allocated_double_registers();
BitVector::Iterator iterator(doubles);
int count = 0;
while (!iterator.Done()) {
// TODO(all): Is this supposed to restore just the callee-saved doubles? It
// looks like it's restoring all of them.
FPRegister value = FPRegister::FromAllocationIndex(iterator.Current());
__ Peek(value, count * kDoubleSize);
iterator.Advance();
count++;
}
}
bool LCodeGen::GeneratePrologue() {
DCHECK(is_generating());
if (info()->IsOptimizing()) {
ProfileEntryHookStub::MaybeCallEntryHook(masm_);
// TODO(all): Add support for stop_t FLAG in DEBUG mode.
// Sloppy mode functions and builtins need to replace the receiver with the
// global proxy when called as functions (without an explicit receiver
// object).
if (is_sloppy(info_->language_mode()) && info()->MayUseThis() &&
!info()->is_native() && info()->scope()->has_this_declaration()) {
Label ok;
int receiver_offset = info_->scope()->num_parameters() * kXRegSize;
__ Peek(x10, receiver_offset);
__ JumpIfNotRoot(x10, Heap::kUndefinedValueRootIndex, &ok);
__ Ldr(x10, GlobalObjectMemOperand());
__ Ldr(x10, FieldMemOperand(x10, GlobalObject::kGlobalProxyOffset));
__ Poke(x10, receiver_offset);
__ Bind(&ok);
}
}
DCHECK(__ StackPointer().Is(jssp));
info()->set_prologue_offset(masm_->pc_offset());
if (NeedsEagerFrame()) {
if (info()->IsStub()) {
__ StubPrologue();
} else {
__ Prologue(info()->IsCodePreAgingActive());
}
frame_is_built_ = true;
info_->AddNoFrameRange(0, masm_->pc_offset());
}
// Reserve space for the stack slots needed by the code.
int slots = GetStackSlotCount();
if (slots > 0) {
__ Claim(slots, kPointerSize);
}
if (info()->saves_caller_doubles()) {
SaveCallerDoubles();
}
// Allocate a local context if needed.
int heap_slots = info()->num_heap_slots() - Context::MIN_CONTEXT_SLOTS;
if (heap_slots > 0) {
Comment(";;; Allocate local context");
bool need_write_barrier = true;
// Argument to NewContext is the function, which is in x1.
DCHECK(!info()->scope()->is_script_scope());
if (heap_slots <= FastNewContextStub::kMaximumSlots) {
FastNewContextStub stub(isolate(), heap_slots);
__ CallStub(&stub);
// Result of FastNewContextStub is always in new space.
need_write_barrier = false;
} else {
__ Push(x1);
__ CallRuntime(Runtime::kNewFunctionContext, 1);
}
RecordSafepoint(Safepoint::kNoLazyDeopt);
// Context is returned in x0. It replaces the context passed to us. It's
// saved in the stack and kept live in cp.
__ Mov(cp, x0);
__ Str(x0, MemOperand(fp, StandardFrameConstants::kContextOffset));
// Copy any necessary parameters into the context.
int num_parameters = scope()->num_parameters();
int first_parameter = scope()->has_this_declaration() ? -1 : 0;
for (int i = first_parameter; i < num_parameters; i++) {
Variable* var = (i == -1) ? scope()->receiver() : scope()->parameter(i);
if (var->IsContextSlot()) {
Register value = x0;
Register scratch = x3;
int parameter_offset = StandardFrameConstants::kCallerSPOffset +
(num_parameters - 1 - i) * kPointerSize;
// Load parameter from stack.
__ Ldr(value, MemOperand(fp, parameter_offset));
// Store it in the context.
MemOperand target = ContextMemOperand(cp, var->index());
__ Str(value, target);
// Update the write barrier. This clobbers value and scratch.
if (need_write_barrier) {
__ RecordWriteContextSlot(cp, static_cast<int>(target.offset()),
value, scratch, GetLinkRegisterState(),
kSaveFPRegs);
} else if (FLAG_debug_code) {
Label done;
__ JumpIfInNewSpace(cp, &done);
__ Abort(kExpectedNewSpaceObject);
__ bind(&done);
}
}
}
Comment(";;; End allocate local context");
}
// Trace the call.
if (FLAG_trace && info()->IsOptimizing()) {
// We have not executed any compiled code yet, so cp still holds the
// incoming context.
__ CallRuntime(Runtime::kTraceEnter, 0);
}
return !is_aborted();
}
void LCodeGen::GenerateOsrPrologue() {
// Generate the OSR entry prologue at the first unknown OSR value, or if there
// are none, at the OSR entrypoint instruction.
if (osr_pc_offset_ >= 0) return;
osr_pc_offset_ = masm()->pc_offset();
// Adjust the frame size, subsuming the unoptimized frame into the
// optimized frame.
int slots = GetStackSlotCount() - graph()->osr()->UnoptimizedFrameSlots();
DCHECK(slots >= 0);
__ Claim(slots);
}
void LCodeGen::GenerateBodyInstructionPre(LInstruction* instr) {
if (instr->IsCall()) {
EnsureSpaceForLazyDeopt(Deoptimizer::patch_size());
}
if (!instr->IsLazyBailout() && !instr->IsGap()) {
safepoints_.BumpLastLazySafepointIndex();
}
}
bool LCodeGen::GenerateDeferredCode() {
DCHECK(is_generating());
if (deferred_.length() > 0) {
for (int i = 0; !is_aborted() && (i < deferred_.length()); i++) {
LDeferredCode* code = deferred_[i];
HValue* value =
instructions_->at(code->instruction_index())->hydrogen_value();
RecordAndWritePosition(
chunk()->graph()->SourcePositionToScriptPosition(value->position()));
Comment(";;; <@%d,#%d> "
"-------------------- Deferred %s --------------------",
code->instruction_index(),
code->instr()->hydrogen_value()->id(),
code->instr()->Mnemonic());
__ Bind(code->entry());
if (NeedsDeferredFrame()) {
Comment(";;; Build frame");
DCHECK(!frame_is_built_);
DCHECK(info()->IsStub());
frame_is_built_ = true;
__ Push(lr, fp, cp);
__ Mov(fp, Smi::FromInt(StackFrame::STUB));
__ Push(fp);
__ Add(fp, __ StackPointer(),
StandardFrameConstants::kFixedFrameSizeFromFp);
Comment(";;; Deferred code");
}
code->Generate();
if (NeedsDeferredFrame()) {
Comment(";;; Destroy frame");
DCHECK(frame_is_built_);
__ Pop(xzr, cp, fp, lr);
frame_is_built_ = false;
}
__ B(code->exit());
}
}
// Force constant pool emission at the end of the deferred code to make
// sure that no constant pools are emitted after deferred code because
// deferred code generation is the last step which generates code. The two
// following steps will only output data used by crakshaft.
masm()->CheckConstPool(true, false);
return !is_aborted();
}
bool LCodeGen::GenerateJumpTable() {
Label needs_frame, call_deopt_entry;
if (jump_table_.length() > 0) {
Comment(";;; -------------------- Jump table --------------------");
Address base = jump_table_[0]->address;
UseScratchRegisterScope temps(masm());
Register entry_offset = temps.AcquireX();
int length = jump_table_.length();
for (int i = 0; i < length; i++) {
Deoptimizer::JumpTableEntry* table_entry = jump_table_[i];
__ Bind(&table_entry->label);
Address entry = table_entry->address;
DeoptComment(table_entry->deopt_info);
// Second-level deopt table entries are contiguous and small, so instead
// of loading the full, absolute address of each one, load the base
// address and add an immediate offset.
__ Mov(entry_offset, entry - base);
if (table_entry->needs_frame) {
DCHECK(!info()->saves_caller_doubles());
Comment(";;; call deopt with frame");
// Save lr before Bl, fp will be adjusted in the needs_frame code.
__ Push(lr, fp);
// Reuse the existing needs_frame code.
__ Bl(&needs_frame);
} else {
// There is nothing special to do, so just continue to the second-level
// table.
__ Bl(&call_deopt_entry);
}
info()->LogDeoptCallPosition(masm()->pc_offset(),
table_entry->deopt_info.inlining_id);
masm()->CheckConstPool(false, false);
}
if (needs_frame.is_linked()) {
// This variant of deopt can only be used with stubs. Since we don't
// have a function pointer to install in the stack frame that we're
// building, install a special marker there instead.
DCHECK(info()->IsStub());
Comment(";;; needs_frame common code");
UseScratchRegisterScope temps(masm());
Register stub_marker = temps.AcquireX();
__ Bind(&needs_frame);
__ Mov(stub_marker, Smi::FromInt(StackFrame::STUB));
__ Push(cp, stub_marker);
__ Add(fp, __ StackPointer(), 2 * kPointerSize);
}
// Generate common code for calling the second-level deopt table.
__ Bind(&call_deopt_entry);
if (info()->saves_caller_doubles()) {
DCHECK(info()->IsStub());
RestoreCallerDoubles();
}
Register deopt_entry = temps.AcquireX();
__ Mov(deopt_entry, Operand(reinterpret_cast<uint64_t>(base),
RelocInfo::RUNTIME_ENTRY));
__ Add(deopt_entry, deopt_entry, entry_offset);
__ Br(deopt_entry);
}
// Force constant pool emission at the end of the deopt jump table to make
// sure that no constant pools are emitted after.
masm()->CheckConstPool(true, false);
// The deoptimization jump table is the last part of the instruction
// sequence. Mark the generated code as done unless we bailed out.
if (!is_aborted()) status_ = DONE;
return !is_aborted();
}
bool LCodeGen::GenerateSafepointTable() {
DCHECK(is_done());
// We do not know how much data will be emitted for the safepoint table, so
// force emission of the veneer pool.
masm()->CheckVeneerPool(true, true);
safepoints_.Emit(masm(), GetStackSlotCount());
return !is_aborted();
}
void LCodeGen::FinishCode(Handle<Code> code) {
DCHECK(is_done());
code->set_stack_slots(GetStackSlotCount());
code->set_safepoint_table_offset(safepoints_.GetCodeOffset());
PopulateDeoptimizationData(code);
}
void LCodeGen::PopulateDeoptimizationData(Handle<Code> code) {
int length = deoptimizations_.length();
if (length == 0) return;
Handle<DeoptimizationInputData> data =
DeoptimizationInputData::New(isolate(), length, TENURED);
Handle<ByteArray> translations =
translations_.CreateByteArray(isolate()->factory());
data->SetTranslationByteArray(*translations);
data->SetInlinedFunctionCount(Smi::FromInt(inlined_function_count_));
data->SetOptimizationId(Smi::FromInt(info_->optimization_id()));
if (info_->IsOptimizing()) {
// Reference to shared function info does not change between phases.
AllowDeferredHandleDereference allow_handle_dereference;
data->SetSharedFunctionInfo(*info_->shared_info());
} else {
data->SetSharedFunctionInfo(Smi::FromInt(0));
}
data->SetWeakCellCache(Smi::FromInt(0));
Handle<FixedArray> literals =
factory()->NewFixedArray(deoptimization_literals_.length(), TENURED);
{ AllowDeferredHandleDereference copy_handles;
for (int i = 0; i < deoptimization_literals_.length(); i++) {
literals->set(i, *deoptimization_literals_[i]);
}
data->SetLiteralArray(*literals);
}
data->SetOsrAstId(Smi::FromInt(info_->osr_ast_id().ToInt()));
data->SetOsrPcOffset(Smi::FromInt(osr_pc_offset_));
// Populate the deoptimization entries.
for (int i = 0; i < length; i++) {
LEnvironment* env = deoptimizations_[i];
data->SetAstId(i, env->ast_id());
data->SetTranslationIndex(i, Smi::FromInt(env->translation_index()));
data->SetArgumentsStackHeight(i,
Smi::FromInt(env->arguments_stack_height()));
data->SetPc(i, Smi::FromInt(env->pc_offset()));
}
code->set_deoptimization_data(*data);
}
void LCodeGen::PopulateDeoptimizationLiteralsWithInlinedFunctions() {
DCHECK_EQ(0, deoptimization_literals_.length());
for (auto function : chunk()->inlined_functions()) {
DefineDeoptimizationLiteral(function);
}
inlined_function_count_ = deoptimization_literals_.length();
}
void LCodeGen::DeoptimizeBranch(
LInstruction* instr, Deoptimizer::DeoptReason deopt_reason,
BranchType branch_type, Register reg, int bit,
Deoptimizer::BailoutType* override_bailout_type) {
LEnvironment* environment = instr->environment();
RegisterEnvironmentForDeoptimization(environment, Safepoint::kNoLazyDeopt);
Deoptimizer::BailoutType bailout_type =
info()->IsStub() ? Deoptimizer::LAZY : Deoptimizer::EAGER;
if (override_bailout_type != NULL) {
bailout_type = *override_bailout_type;
}
DCHECK(environment->HasBeenRegistered());
DCHECK(info()->IsOptimizing() || info()->IsStub());
int id = environment->deoptimization_index();
Address entry =
Deoptimizer::GetDeoptimizationEntry(isolate(), id, bailout_type);
if (entry == NULL) {
Abort(kBailoutWasNotPrepared);
}
if (FLAG_deopt_every_n_times != 0 && !info()->IsStub()) {
Label not_zero;
ExternalReference count = ExternalReference::stress_deopt_count(isolate());
__ Push(x0, x1, x2);
__ Mrs(x2, NZCV);
__ Mov(x0, count);
__ Ldr(w1, MemOperand(x0));
__ Subs(x1, x1, 1);
__ B(gt, ¬_zero);
__ Mov(w1, FLAG_deopt_every_n_times);
__ Str(w1, MemOperand(x0));
__ Pop(x2, x1, x0);
DCHECK(frame_is_built_);
__ Call(entry, RelocInfo::RUNTIME_ENTRY);