/
deoptimizer.cc
4113 lines (3623 loc) Β· 153 KB
/
deoptimizer.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/deoptimizer/deoptimizer.h"
#include <memory>
#include "src/ast/prettyprinter.h"
#include "src/builtins/accessors.h"
#include "src/codegen/assembler-inl.h"
#include "src/codegen/callable.h"
#include "src/codegen/macro-assembler.h"
#include "src/codegen/register-configuration.h"
#include "src/diagnostics/disasm.h"
#include "src/execution/frames-inl.h"
#include "src/execution/pointer-authentication.h"
#include "src/execution/v8threads.h"
#include "src/handles/global-handles.h"
#include "src/heap/heap-inl.h"
#include "src/init/v8.h"
#include "src/interpreter/interpreter.h"
#include "src/logging/counters.h"
#include "src/logging/log.h"
#include "src/objects/debug-objects-inl.h"
#include "src/objects/heap-number-inl.h"
#include "src/objects/smi.h"
#include "src/tracing/trace-event.h"
// Has to be the last include (doesn't have include guards)
#include "src/objects/object-macros.h"
namespace v8 {
namespace internal {
// {FrameWriter} offers a stack writer abstraction for writing
// FrameDescriptions. The main service the class provides is managing
// {top_offset_}, i.e. the offset of the next slot to write to.
class FrameWriter {
public:
static const int NO_INPUT_INDEX = -1;
FrameWriter(Deoptimizer* deoptimizer, FrameDescription* frame,
CodeTracer::Scope* trace_scope)
: deoptimizer_(deoptimizer),
frame_(frame),
trace_scope_(trace_scope),
top_offset_(frame->GetFrameSize()) {}
void PushRawValue(intptr_t value, const char* debug_hint) {
PushValue(value);
if (trace_scope_ != nullptr) {
DebugPrintOutputValue(value, debug_hint);
}
}
void PushRawObject(Object obj, const char* debug_hint) {
intptr_t value = obj.ptr();
PushValue(value);
if (trace_scope_ != nullptr) {
DebugPrintOutputObject(obj, top_offset_, debug_hint);
}
}
void PushCallerPc(intptr_t pc) {
top_offset_ -= kPCOnStackSize;
frame_->SetCallerPc(top_offset_, pc);
DebugPrintOutputValue(pc, "caller's pc\n");
}
void PushCallerFp(intptr_t fp) {
top_offset_ -= kFPOnStackSize;
frame_->SetCallerFp(top_offset_, fp);
DebugPrintOutputValue(fp, "caller's fp\n");
}
void PushCallerConstantPool(intptr_t cp) {
top_offset_ -= kSystemPointerSize;
frame_->SetCallerConstantPool(top_offset_, cp);
DebugPrintOutputValue(cp, "caller's constant_pool\n");
}
void PushTranslatedValue(const TranslatedFrame::iterator& iterator,
const char* debug_hint = "") {
Object obj = iterator->GetRawValue();
PushRawObject(obj, debug_hint);
if (trace_scope_) {
PrintF(trace_scope_->file(), " (input #%d)\n", iterator.input_index());
}
deoptimizer_->QueueValueForMaterialization(output_address(top_offset_), obj,
iterator);
}
unsigned top_offset() const { return top_offset_; }
private:
void PushValue(intptr_t value) {
CHECK_GE(top_offset_, 0);
top_offset_ -= kSystemPointerSize;
frame_->SetFrameSlot(top_offset_, value);
}
Address output_address(unsigned output_offset) {
Address output_address =
static_cast<Address>(frame_->GetTop()) + output_offset;
return output_address;
}
void DebugPrintOutputValue(intptr_t value, const char* debug_hint = "") {
if (trace_scope_ != nullptr) {
PrintF(trace_scope_->file(),
" " V8PRIxPTR_FMT ": [top + %3d] <- " V8PRIxPTR_FMT " ; %s",
output_address(top_offset_), top_offset_, value, debug_hint);
}
}
void DebugPrintOutputObject(Object obj, unsigned output_offset,
const char* debug_hint = "") {
if (trace_scope_ != nullptr) {
PrintF(trace_scope_->file(), " " V8PRIxPTR_FMT ": [top + %3d] <- ",
output_address(output_offset), output_offset);
if (obj.IsSmi()) {
PrintF(trace_scope_->file(), V8PRIxPTR_FMT " <Smi %d>", obj.ptr(),
Smi::cast(obj).value());
} else {
obj.ShortPrint(trace_scope_->file());
}
PrintF(trace_scope_->file(), " ; %s", debug_hint);
}
}
Deoptimizer* deoptimizer_;
FrameDescription* frame_;
CodeTracer::Scope* trace_scope_;
unsigned top_offset_;
};
DeoptimizerData::DeoptimizerData(Heap* heap) : heap_(heap), current_(nullptr) {
Code* start = &deopt_entry_code_[0];
Code* end = &deopt_entry_code_[DeoptimizerData::kLastDeoptimizeKind + 1];
heap_->RegisterStrongRoots(FullObjectSlot(start), FullObjectSlot(end));
}
DeoptimizerData::~DeoptimizerData() {
Code* start = &deopt_entry_code_[0];
heap_->UnregisterStrongRoots(FullObjectSlot(start));
}
Code DeoptimizerData::deopt_entry_code(DeoptimizeKind kind) {
return deopt_entry_code_[static_cast<int>(kind)];
}
void DeoptimizerData::set_deopt_entry_code(DeoptimizeKind kind, Code code) {
deopt_entry_code_[static_cast<int>(kind)] = code;
}
Code Deoptimizer::FindDeoptimizingCode(Address addr) {
if (function_.IsHeapObject()) {
// Search all deoptimizing code in the native context of the function.
Isolate* isolate = isolate_;
NativeContext native_context = function_.context().native_context();
Object element = native_context.DeoptimizedCodeListHead();
while (!element.IsUndefined(isolate)) {
Code code = Code::cast(element);
CHECK(code.kind() == Code::OPTIMIZED_FUNCTION);
if (code.contains(addr)) return code;
element = code.next_code_link();
}
}
return Code();
}
// We rely on this function not causing a GC. It is called from generated code
// without having a real stack frame in place.
Deoptimizer* Deoptimizer::New(Address raw_function, DeoptimizeKind kind,
unsigned bailout_id, Address from,
int fp_to_sp_delta, Isolate* isolate) {
JSFunction function = JSFunction::cast(Object(raw_function));
Deoptimizer* deoptimizer = new Deoptimizer(isolate, function, kind,
bailout_id, from, fp_to_sp_delta);
CHECK_NULL(isolate->deoptimizer_data()->current_);
isolate->deoptimizer_data()->current_ = deoptimizer;
return deoptimizer;
}
Deoptimizer* Deoptimizer::Grab(Isolate* isolate) {
Deoptimizer* result = isolate->deoptimizer_data()->current_;
CHECK_NOT_NULL(result);
result->DeleteFrameDescriptions();
isolate->deoptimizer_data()->current_ = nullptr;
return result;
}
DeoptimizedFrameInfo* Deoptimizer::DebuggerInspectableFrame(
JavaScriptFrame* frame, int jsframe_index, Isolate* isolate) {
CHECK(frame->is_optimized());
TranslatedState translated_values(frame);
translated_values.Prepare(frame->fp());
TranslatedState::iterator frame_it = translated_values.end();
int counter = jsframe_index;
for (auto it = translated_values.begin(); it != translated_values.end();
it++) {
if (it->kind() == TranslatedFrame::kInterpretedFunction ||
it->kind() == TranslatedFrame::kJavaScriptBuiltinContinuation ||
it->kind() ==
TranslatedFrame::kJavaScriptBuiltinContinuationWithCatch) {
if (counter == 0) {
frame_it = it;
break;
}
counter--;
}
}
CHECK(frame_it != translated_values.end());
// We only include kJavaScriptBuiltinContinuation frames above to get the
// counting right.
CHECK_EQ(frame_it->kind(), TranslatedFrame::kInterpretedFunction);
DeoptimizedFrameInfo* info =
new DeoptimizedFrameInfo(&translated_values, frame_it, isolate);
return info;
}
namespace {
class ActivationsFinder : public ThreadVisitor {
public:
explicit ActivationsFinder(std::set<Code>* codes, Code topmost_optimized_code,
bool safe_to_deopt_topmost_optimized_code)
: codes_(codes) {
#ifdef DEBUG
topmost_ = topmost_optimized_code;
safe_to_deopt_ = safe_to_deopt_topmost_optimized_code;
#endif
}
// Find the frames with activations of codes marked for deoptimization, search
// for the trampoline to the deoptimizer call respective to each code, and use
// it to replace the current pc on the stack.
void VisitThread(Isolate* isolate, ThreadLocalTop* top) override {
for (StackFrameIterator it(isolate, top); !it.done(); it.Advance()) {
if (it.frame()->type() == StackFrame::OPTIMIZED) {
Code code = it.frame()->LookupCode();
if (code.kind() == Code::OPTIMIZED_FUNCTION &&
code.marked_for_deoptimization()) {
codes_->erase(code);
// Obtain the trampoline to the deoptimizer call.
SafepointEntry safepoint = code.GetSafepointEntry(it.frame()->pc());
int trampoline_pc = safepoint.trampoline_pc();
DCHECK_IMPLIES(code == topmost_, safe_to_deopt_);
CHECK_GE(trampoline_pc, 0);
// Replace the current pc on the stack with the trampoline.
// TODO(v8:10026): avoid replacing a signed pointer.
Address* pc_addr = it.frame()->pc_address();
Address new_pc = code.raw_instruction_start() + trampoline_pc;
PointerAuthentication::ReplacePC(pc_addr, new_pc, kSystemPointerSize);
}
}
}
}
private:
std::set<Code>* codes_;
#ifdef DEBUG
Code topmost_;
bool safe_to_deopt_;
#endif
};
} // namespace
// Move marked code from the optimized code list to the deoptimized code list,
// and replace pc on the stack for codes marked for deoptimization.
void Deoptimizer::DeoptimizeMarkedCodeForContext(NativeContext native_context) {
DisallowHeapAllocation no_allocation;
Isolate* isolate = native_context.GetIsolate();
Code topmost_optimized_code;
bool safe_to_deopt_topmost_optimized_code = false;
#ifdef DEBUG
// Make sure all activations of optimized code can deopt at their current PC.
// The topmost optimized code has special handling because it cannot be
// deoptimized due to weak object dependency.
for (StackFrameIterator it(isolate, isolate->thread_local_top()); !it.done();
it.Advance()) {
StackFrame::Type type = it.frame()->type();
if (type == StackFrame::OPTIMIZED) {
Code code = it.frame()->LookupCode();
JSFunction function =
static_cast<OptimizedFrame*>(it.frame())->function();
if (FLAG_trace_deopt) {
CodeTracer::Scope scope(isolate->GetCodeTracer());
PrintF(scope.file(), "[deoptimizer found activation of function: ");
function.PrintName(scope.file());
PrintF(scope.file(), " / %" V8PRIxPTR "]\n", function.ptr());
}
SafepointEntry safepoint = code.GetSafepointEntry(it.frame()->pc());
// Turbofan deopt is checked when we are patching addresses on stack.
bool safe_if_deopt_triggered = safepoint.has_deoptimization_index();
bool is_builtin_code = code.kind() == Code::BUILTIN;
DCHECK(topmost_optimized_code.is_null() || safe_if_deopt_triggered ||
is_builtin_code);
if (topmost_optimized_code.is_null()) {
topmost_optimized_code = code;
safe_to_deopt_topmost_optimized_code = safe_if_deopt_triggered;
}
}
}
#endif
// We will use this set to mark those Code objects that are marked for
// deoptimization and have not been found in stack frames.
std::set<Code> codes;
// Move marked code from the optimized code list to the deoptimized code list.
// Walk over all optimized code objects in this native context.
Code prev;
Object element = native_context.OptimizedCodeListHead();
while (!element.IsUndefined(isolate)) {
Code code = Code::cast(element);
CHECK_EQ(code.kind(), Code::OPTIMIZED_FUNCTION);
Object next = code.next_code_link();
if (code.marked_for_deoptimization()) {
codes.insert(code);
if (!prev.is_null()) {
// Skip this code in the optimized code list.
prev.set_next_code_link(next);
} else {
// There was no previous node, the next node is the new head.
native_context.SetOptimizedCodeListHead(next);
}
// Move the code to the _deoptimized_ code list.
code.set_next_code_link(native_context.DeoptimizedCodeListHead());
native_context.SetDeoptimizedCodeListHead(code);
} else {
// Not marked; preserve this element.
prev = code;
}
element = next;
}
ActivationsFinder visitor(&codes, topmost_optimized_code,
safe_to_deopt_topmost_optimized_code);
// Iterate over the stack of this thread.
visitor.VisitThread(isolate, isolate->thread_local_top());
// In addition to iterate over the stack of this thread, we also
// need to consider all the other threads as they may also use
// the code currently beings deoptimized.
isolate->thread_manager()->IterateArchivedThreads(&visitor);
// If there's no activation of a code in any stack then we can remove its
// deoptimization data. We do this to ensure that code objects that are
// unlinked don't transitively keep objects alive unnecessarily.
for (Code code : codes) {
isolate->heap()->InvalidateCodeDeoptimizationData(code);
}
native_context.GetOSROptimizedCodeCache().EvictMarkedCode(
native_context.GetIsolate());
}
void Deoptimizer::DeoptimizeAll(Isolate* isolate) {
RuntimeCallTimerScope runtimeTimer(isolate,
RuntimeCallCounterId::kDeoptimizeCode);
TimerEventScope<TimerEventDeoptimizeCode> timer(isolate);
TRACE_EVENT0("v8", "V8.DeoptimizeCode");
if (FLAG_trace_deopt) {
CodeTracer::Scope scope(isolate->GetCodeTracer());
PrintF(scope.file(), "[deoptimize all code in all contexts]\n");
}
isolate->AbortConcurrentOptimization(BlockingBehavior::kBlock);
DisallowHeapAllocation no_allocation;
// For all contexts, mark all code, then deoptimize.
Object context = isolate->heap()->native_contexts_list();
while (!context.IsUndefined(isolate)) {
NativeContext native_context = NativeContext::cast(context);
MarkAllCodeForContext(native_context);
OSROptimizedCodeCache::Clear(native_context);
DeoptimizeMarkedCodeForContext(native_context);
context = native_context.next_context_link();
}
}
void Deoptimizer::DeoptimizeMarkedCode(Isolate* isolate) {
RuntimeCallTimerScope runtimeTimer(isolate,
RuntimeCallCounterId::kDeoptimizeCode);
TimerEventScope<TimerEventDeoptimizeCode> timer(isolate);
TRACE_EVENT0("v8", "V8.DeoptimizeCode");
if (FLAG_trace_deopt) {
CodeTracer::Scope scope(isolate->GetCodeTracer());
PrintF(scope.file(), "[deoptimize marked code in all contexts]\n");
}
DisallowHeapAllocation no_allocation;
// For all contexts, deoptimize code already marked.
Object context = isolate->heap()->native_contexts_list();
while (!context.IsUndefined(isolate)) {
NativeContext native_context = NativeContext::cast(context);
DeoptimizeMarkedCodeForContext(native_context);
context = native_context.next_context_link();
}
}
void Deoptimizer::MarkAllCodeForContext(NativeContext native_context) {
Object element = native_context.OptimizedCodeListHead();
Isolate* isolate = native_context.GetIsolate();
while (!element.IsUndefined(isolate)) {
Code code = Code::cast(element);
CHECK_EQ(code.kind(), Code::OPTIMIZED_FUNCTION);
code.set_marked_for_deoptimization(true);
element = code.next_code_link();
}
}
void Deoptimizer::DeoptimizeFunction(JSFunction function, Code code) {
Isolate* isolate = function.GetIsolate();
RuntimeCallTimerScope runtimeTimer(isolate,
RuntimeCallCounterId::kDeoptimizeCode);
TimerEventScope<TimerEventDeoptimizeCode> timer(isolate);
TRACE_EVENT0("v8", "V8.DeoptimizeCode");
function.ResetIfBytecodeFlushed();
if (code.is_null()) code = function.code();
if (code.kind() == Code::OPTIMIZED_FUNCTION) {
// Mark the code for deoptimization and unlink any functions that also
// refer to that code. The code cannot be shared across native contexts,
// so we only need to search one.
code.set_marked_for_deoptimization(true);
// The code in the function's optimized code feedback vector slot might
// be different from the code on the function - evict it if necessary.
function.feedback_vector().EvictOptimizedCodeMarkedForDeoptimization(
function.shared(), "unlinking code marked for deopt");
if (!code.deopt_already_counted()) {
code.set_deopt_already_counted(true);
}
DeoptimizeMarkedCodeForContext(function.context().native_context());
// TODO(mythria): Ideally EvictMarkCode should compact the cache without
// having to explicitly call this. We don't do this currently because
// compacting causes GC and DeoptimizeMarkedCodeForContext uses raw
// pointers. Update DeoptimizeMarkedCodeForContext to use handles and remove
// this call from here.
OSROptimizedCodeCache::Compact(
Handle<NativeContext>(function.context().native_context(), isolate));
}
}
void Deoptimizer::ComputeOutputFrames(Deoptimizer* deoptimizer) {
deoptimizer->DoComputeOutputFrames();
}
const char* Deoptimizer::MessageFor(DeoptimizeKind kind) {
switch (kind) {
case DeoptimizeKind::kEager:
return "eager";
case DeoptimizeKind::kSoft:
return "soft";
case DeoptimizeKind::kLazy:
return "lazy";
}
FATAL("Unsupported deopt kind");
return nullptr;
}
namespace {
uint16_t InternalFormalParameterCountWithReceiver(SharedFunctionInfo sfi) {
static constexpr int kTheReceiver = 1;
return sfi.internal_formal_parameter_count() + kTheReceiver;
}
} // namespace
Deoptimizer::Deoptimizer(Isolate* isolate, JSFunction function,
DeoptimizeKind kind, unsigned bailout_id, Address from,
int fp_to_sp_delta)
: isolate_(isolate),
function_(function),
bailout_id_(bailout_id),
deopt_kind_(kind),
from_(from),
fp_to_sp_delta_(fp_to_sp_delta),
deoptimizing_throw_(false),
catch_handler_data_(-1),
catch_handler_pc_offset_(-1),
input_(nullptr),
output_count_(0),
jsframe_count_(0),
output_(nullptr),
caller_frame_top_(0),
caller_fp_(0),
caller_pc_(0),
caller_constant_pool_(0),
input_frame_context_(0),
stack_fp_(0),
trace_scope_(nullptr) {
if (isolate->deoptimizer_lazy_throw()) {
isolate->set_deoptimizer_lazy_throw(false);
deoptimizing_throw_ = true;
}
DCHECK_NE(from, kNullAddress);
compiled_code_ = FindOptimizedCode();
DCHECK(!compiled_code_.is_null());
DCHECK(function.IsJSFunction());
trace_scope_ = FLAG_trace_deopt
? new CodeTracer::Scope(isolate->GetCodeTracer())
: nullptr;
#ifdef DEBUG
DCHECK(AllowHeapAllocation::IsAllowed());
disallow_heap_allocation_ = new DisallowHeapAllocation();
#endif // DEBUG
if ((compiled_code_.kind() != Code::OPTIMIZED_FUNCTION ||
!compiled_code_.deopt_already_counted()) &&
deopt_kind_ == DeoptimizeKind::kSoft) {
isolate->counters()->soft_deopts_executed()->Increment();
}
if (compiled_code_.kind() == Code::OPTIMIZED_FUNCTION) {
compiled_code_.set_deopt_already_counted(true);
HandleScope scope(isolate_);
PROFILE(isolate_, CodeDeoptEvent(handle(compiled_code_, isolate_), kind,
from_, fp_to_sp_delta_));
}
unsigned size = ComputeInputFrameSize();
const int parameter_count =
InternalFormalParameterCountWithReceiver(function.shared());
input_ = new (size) FrameDescription(size, parameter_count);
if (kSupportsFixedDeoptExitSizes) {
DCHECK_EQ(bailout_id_, kMaxUInt32);
// Calculate bailout id from return address.
DCHECK_GT(kNonLazyDeoptExitSize, 0);
DCHECK_GT(kLazyDeoptExitSize, 0);
DeoptimizationData deopt_data =
DeoptimizationData::cast(compiled_code_.deoptimization_data());
Address deopt_start = compiled_code_.raw_instruction_start() +
deopt_data.DeoptExitStart().value();
int non_lazy_deopt_count = deopt_data.NonLazyDeoptCount().value();
Address lazy_deopt_start =
deopt_start + non_lazy_deopt_count * kNonLazyDeoptExitSize;
// The deoptimization exits are sorted so that lazy deopt exits appear last.
static_assert(DeoptimizeKind::kLazy > DeoptimizeKind::kEager,
"lazy deopts are expected to be emitted last");
static_assert(DeoptimizeKind::kLazy > DeoptimizeKind::kSoft,
"lazy deopts are expected to be emitted last");
// from_ is the value of the link register after the call to the
// deoptimizer, so for the last lazy deopt, from_ points to the first
// non-lazy deopt, so we use <=.
if (from_ <= lazy_deopt_start) {
int offset =
static_cast<int>(from_ - kNonLazyDeoptExitSize - deopt_start);
DCHECK_EQ(0, offset % kNonLazyDeoptExitSize);
bailout_id_ = offset / kNonLazyDeoptExitSize;
} else {
int offset =
static_cast<int>(from_ - kLazyDeoptExitSize - lazy_deopt_start);
DCHECK_EQ(0, offset % kLazyDeoptExitSize);
bailout_id_ = non_lazy_deopt_count + (offset / kLazyDeoptExitSize);
}
}
}
Code Deoptimizer::FindOptimizedCode() {
Code compiled_code = FindDeoptimizingCode(from_);
return !compiled_code.is_null() ? compiled_code
: isolate_->FindCodeObject(from_);
}
void Deoptimizer::PrintFunctionName() {
if (function_.IsHeapObject() && function_.IsJSFunction()) {
function_.ShortPrint(trace_scope_->file());
} else {
PrintF(trace_scope_->file(), "%s",
Code::Kind2String(compiled_code_.kind()));
}
}
Handle<JSFunction> Deoptimizer::function() const {
return Handle<JSFunction>(function_, isolate());
}
Handle<Code> Deoptimizer::compiled_code() const {
return Handle<Code>(compiled_code_, isolate());
}
Deoptimizer::~Deoptimizer() {
DCHECK(input_ == nullptr && output_ == nullptr);
DCHECK_NULL(disallow_heap_allocation_);
delete trace_scope_;
}
void Deoptimizer::DeleteFrameDescriptions() {
delete input_;
for (int i = 0; i < output_count_; ++i) {
if (output_[i] != input_) delete output_[i];
}
delete[] output_;
input_ = nullptr;
output_ = nullptr;
#ifdef DEBUG
DCHECK(!AllowHeapAllocation::IsAllowed());
DCHECK_NOT_NULL(disallow_heap_allocation_);
delete disallow_heap_allocation_;
disallow_heap_allocation_ = nullptr;
#endif // DEBUG
}
Address Deoptimizer::GetDeoptimizationEntry(Isolate* isolate,
DeoptimizeKind kind) {
DeoptimizerData* data = isolate->deoptimizer_data();
CHECK_LE(kind, DeoptimizerData::kLastDeoptimizeKind);
CHECK(!data->deopt_entry_code(kind).is_null());
return data->deopt_entry_code(kind).raw_instruction_start();
}
bool Deoptimizer::IsDeoptimizationEntry(Isolate* isolate, Address addr,
DeoptimizeKind type) {
DeoptimizerData* data = isolate->deoptimizer_data();
CHECK_LE(type, DeoptimizerData::kLastDeoptimizeKind);
Code code = data->deopt_entry_code(type);
if (code.is_null()) return false;
return addr == code.raw_instruction_start();
}
bool Deoptimizer::IsDeoptimizationEntry(Isolate* isolate, Address addr,
DeoptimizeKind* type) {
if (IsDeoptimizationEntry(isolate, addr, DeoptimizeKind::kEager)) {
*type = DeoptimizeKind::kEager;
return true;
}
if (IsDeoptimizationEntry(isolate, addr, DeoptimizeKind::kSoft)) {
*type = DeoptimizeKind::kSoft;
return true;
}
if (IsDeoptimizationEntry(isolate, addr, DeoptimizeKind::kLazy)) {
*type = DeoptimizeKind::kLazy;
return true;
}
return false;
}
int Deoptimizer::GetDeoptimizedCodeCount(Isolate* isolate) {
int length = 0;
// Count all entries in the deoptimizing code list of every context.
Object context = isolate->heap()->native_contexts_list();
while (!context.IsUndefined(isolate)) {
NativeContext native_context = NativeContext::cast(context);
Object element = native_context.DeoptimizedCodeListHead();
while (!element.IsUndefined(isolate)) {
Code code = Code::cast(element);
DCHECK(code.kind() == Code::OPTIMIZED_FUNCTION);
if (!code.marked_for_deoptimization()) {
length++;
}
element = code.next_code_link();
}
context = Context::cast(context).next_context_link();
}
return length;
}
namespace {
int LookupCatchHandler(TranslatedFrame* translated_frame, int* data_out) {
switch (translated_frame->kind()) {
case TranslatedFrame::kInterpretedFunction: {
int bytecode_offset = translated_frame->node_id().ToInt();
HandlerTable table(
translated_frame->raw_shared_info().GetBytecodeArray());
return table.LookupRange(bytecode_offset, data_out, nullptr);
}
case TranslatedFrame::kJavaScriptBuiltinContinuationWithCatch: {
return 0;
}
default:
break;
}
return -1;
}
} // namespace
// We rely on this function not causing a GC. It is called from generated code
// without having a real stack frame in place.
void Deoptimizer::DoComputeOutputFrames() {
// When we call this function, the return address of the previous frame has
// been removed from the stack by GenerateDeoptimizationEntries() so the stack
// is not iterable by the SafeStackFrameIterator.
#if V8_TARGET_ARCH_STORES_RETURN_ADDRESS_ON_STACK
DCHECK_EQ(0, isolate()->isolate_data()->stack_is_iterable());
#endif
base::ElapsedTimer timer;
// Determine basic deoptimization information. The optimized frame is
// described by the input data.
DeoptimizationData input_data =
DeoptimizationData::cast(compiled_code_.deoptimization_data());
{
// Read caller's PC, caller's FP and caller's constant pool values
// from input frame. Compute caller's frame top address.
Register fp_reg = JavaScriptFrame::fp_register();
stack_fp_ = input_->GetRegister(fp_reg.code());
caller_frame_top_ = stack_fp_ + ComputeInputFrameAboveFpFixedSize();
Address fp_address = input_->GetFramePointerAddress();
caller_fp_ = Memory<intptr_t>(fp_address);
caller_pc_ =
Memory<intptr_t>(fp_address + CommonFrameConstants::kCallerPCOffset);
// Sign caller_pc_ with caller_frame_top_ to be consistent with everything
// else here.
uint64_t sp = stack_fp_ + StandardFrameConstants::kCallerSPOffset;
// TODO(v8:10026): avoid replacing a signed pointer.
PointerAuthentication::ReplaceContext(
reinterpret_cast<Address*>(&caller_pc_), sp, caller_frame_top_);
input_frame_context_ = Memory<intptr_t>(
fp_address + CommonFrameConstants::kContextOrFrameTypeOffset);
if (FLAG_enable_embedded_constant_pool) {
caller_constant_pool_ = Memory<intptr_t>(
fp_address + CommonFrameConstants::kConstantPoolOffset);
}
}
StackGuard* const stack_guard = isolate()->stack_guard();
CHECK_GT(static_cast<uintptr_t>(caller_frame_top_),
stack_guard->real_jslimit());
if (trace_scope_ != nullptr) {
timer.Start();
PrintF(trace_scope_->file(), "[deoptimizing (DEOPT %s): begin ",
MessageFor(deopt_kind_));
PrintFunctionName();
PrintF(trace_scope_->file(),
" (opt #%d) @%d, FP to SP delta: %d, caller sp: " V8PRIxPTR_FMT
"]\n",
input_data.OptimizationId().value(), bailout_id_, fp_to_sp_delta_,
caller_frame_top_);
if (deopt_kind_ == DeoptimizeKind::kEager ||
deopt_kind_ == DeoptimizeKind::kSoft) {
compiled_code_.PrintDeoptLocation(
trace_scope_->file(), " ;;; deoptimize at ", from_);
}
}
BailoutId node_id = input_data.BytecodeOffset(bailout_id_);
ByteArray translations = input_data.TranslationByteArray();
unsigned translation_index = input_data.TranslationIndex(bailout_id_).value();
TranslationIterator state_iterator(translations, translation_index);
translated_state_.Init(
isolate_, input_->GetFramePointerAddress(), &state_iterator,
input_data.LiteralArray(), input_->GetRegisterValues(),
trace_scope_ == nullptr ? nullptr : trace_scope_->file(),
function_.IsHeapObject()
? function_.shared().internal_formal_parameter_count()
: 0);
// Do the input frame to output frame(s) translation.
size_t count = translated_state_.frames().size();
// If we are supposed to go to the catch handler, find the catching frame
// for the catch and make sure we only deoptimize upto that frame.
if (deoptimizing_throw_) {
size_t catch_handler_frame_index = count;
for (size_t i = count; i-- > 0;) {
catch_handler_pc_offset_ = LookupCatchHandler(
&(translated_state_.frames()[i]), &catch_handler_data_);
if (catch_handler_pc_offset_ >= 0) {
catch_handler_frame_index = i;
break;
}
}
CHECK_LT(catch_handler_frame_index, count);
count = catch_handler_frame_index + 1;
}
DCHECK_NULL(output_);
output_ = new FrameDescription*[count];
for (size_t i = 0; i < count; ++i) {
output_[i] = nullptr;
}
output_count_ = static_cast<int>(count);
// Translate each output frame.
int frame_index = 0; // output_frame_index
size_t total_output_frame_size = 0;
for (size_t i = 0; i < count; ++i, ++frame_index) {
// Read the ast node id, function, and frame height for this output frame.
TranslatedFrame* translated_frame = &(translated_state_.frames()[i]);
bool handle_exception = deoptimizing_throw_ && i == count - 1;
switch (translated_frame->kind()) {
case TranslatedFrame::kInterpretedFunction:
DoComputeInterpretedFrame(translated_frame, frame_index,
handle_exception);
jsframe_count_++;
break;
case TranslatedFrame::kArgumentsAdaptor:
DoComputeArgumentsAdaptorFrame(translated_frame, frame_index);
break;
case TranslatedFrame::kConstructStub:
DoComputeConstructStubFrame(translated_frame, frame_index);
break;
case TranslatedFrame::kBuiltinContinuation:
DoComputeBuiltinContinuation(translated_frame, frame_index,
BuiltinContinuationMode::STUB);
break;
case TranslatedFrame::kJavaScriptBuiltinContinuation:
DoComputeBuiltinContinuation(translated_frame, frame_index,
BuiltinContinuationMode::JAVASCRIPT);
break;
case TranslatedFrame::kJavaScriptBuiltinContinuationWithCatch:
DoComputeBuiltinContinuation(
translated_frame, frame_index,
handle_exception
? BuiltinContinuationMode::JAVASCRIPT_HANDLE_EXCEPTION
: BuiltinContinuationMode::JAVASCRIPT_WITH_CATCH);
break;
case TranslatedFrame::kInvalid:
FATAL("invalid frame");
break;
}
total_output_frame_size += output_[frame_index]->GetFrameSize();
}
FrameDescription* topmost = output_[count - 1];
topmost->GetRegisterValues()->SetRegister(kRootRegister.code(),
isolate()->isolate_root());
// Print some helpful diagnostic information.
if (trace_scope_ != nullptr) {
double ms = timer.Elapsed().InMillisecondsF();
int index = output_count_ - 1; // Index of the topmost frame.
PrintF(trace_scope_->file(), "[deoptimizing (%s): end ",
MessageFor(deopt_kind_));
PrintFunctionName();
PrintF(trace_scope_->file(),
" @%d => node=%d, pc=" V8PRIxPTR_FMT ", caller sp=" V8PRIxPTR_FMT
", took %0.3f ms]\n",
bailout_id_, node_id.ToInt(), output_[index]->GetPc(),
caller_frame_top_, ms);
}
// The following invariant is fairly tricky to guarantee, since the size of
// an optimized frame and its deoptimized counterparts usually differs. We
// thus need to consider the case in which deoptimized frames are larger than
// the optimized frame in stack checks in optimized code. We do this by
// applying an offset to stack checks (see kArchStackPointerGreaterThan in the
// code generator).
// Note that we explicitly allow deopts to exceed the limit by a certain
// number of slack bytes.
CHECK_GT(
static_cast<uintptr_t>(caller_frame_top_) - total_output_frame_size,
stack_guard->real_jslimit() - kStackLimitSlackForDeoptimizationInBytes);
}
void Deoptimizer::DoComputeInterpretedFrame(TranslatedFrame* translated_frame,
int frame_index,
bool goto_catch_handler) {
SharedFunctionInfo shared = translated_frame->raw_shared_info();
TranslatedFrame::iterator value_iterator = translated_frame->begin();
const bool is_bottommost = (0 == frame_index);
const bool is_topmost = (output_count_ - 1 == frame_index);
const int real_bytecode_offset = translated_frame->node_id().ToInt();
const int bytecode_offset =
goto_catch_handler ? catch_handler_pc_offset_ : real_bytecode_offset;
const int parameters_count = InternalFormalParameterCountWithReceiver(shared);
const int locals_count = translated_frame->height();
InterpretedFrameInfo frame_info =
InterpretedFrameInfo::Precise(parameters_count, locals_count, is_topmost);
const uint32_t output_frame_size = frame_info.frame_size_in_bytes();
TranslatedFrame::iterator function_iterator = value_iterator++;
if (trace_scope_ != nullptr) {
PrintF(trace_scope_->file(), " translating interpreted frame ");
std::unique_ptr<char[]> name = shared.DebugName().ToCString();
PrintF(trace_scope_->file(), "%s", name.get());
PrintF(trace_scope_->file(),
" => bytecode_offset=%d, variable_frame_size=%d, frame_size=%d%s\n",
real_bytecode_offset, frame_info.frame_size_in_bytes_without_fixed(),
output_frame_size, goto_catch_handler ? " (throw)" : "");
}
// Allocate and store the output frame description.
FrameDescription* output_frame = new (output_frame_size)
FrameDescription(output_frame_size, parameters_count);
FrameWriter frame_writer(this, output_frame, trace_scope_);
CHECK(frame_index >= 0 && frame_index < output_count_);
CHECK_NULL(output_[frame_index]);
output_[frame_index] = output_frame;
// The top address of the frame is computed from the previous frame's top and
// this frame's size.
const intptr_t top_address =
is_bottommost ? caller_frame_top_ - output_frame_size
: output_[frame_index - 1]->GetTop() - output_frame_size;
output_frame->SetTop(top_address);
// Compute the incoming parameter translation.
ReadOnlyRoots roots(isolate());
if (ShouldPadArguments(parameters_count)) {
frame_writer.PushRawObject(roots.the_hole_value(), "padding\n");
}
for (int i = 0; i < parameters_count; ++i, ++value_iterator) {
frame_writer.PushTranslatedValue(value_iterator, "stack parameter");
}
DCHECK_EQ(output_frame->GetLastArgumentSlotOffset(),
frame_writer.top_offset());
if (trace_scope_ != nullptr) {
PrintF(trace_scope_->file(), " -------------------------\n");
}
// There are no translation commands for the caller's pc and fp, the
// context, the function and the bytecode offset. Synthesize
// their values and set them up
// explicitly.
//
// The caller's pc for the bottommost output frame is the same as in the
// input frame. For all subsequent output frames, it can be read from the
// previous one. This frame's pc can be computed from the non-optimized
// function code and AST id of the bailout.
const intptr_t caller_pc =
is_bottommost ? caller_pc_ : output_[frame_index - 1]->GetPc();
frame_writer.PushCallerPc(caller_pc);
// The caller's frame pointer for the bottommost output frame is the same
// as in the input frame. For all subsequent output frames, it can be
// read from the previous one. Also compute and set this frame's frame
// pointer.
const intptr_t caller_fp =
is_bottommost ? caller_fp_ : output_[frame_index - 1]->GetFp();
frame_writer.PushCallerFp(caller_fp);
const intptr_t fp_value = top_address + frame_writer.top_offset();
output_frame->SetFp(fp_value);
if (is_topmost) {
Register fp_reg = InterpretedFrame::fp_register();
output_frame->SetRegister(fp_reg.code(), fp_value);
}
if (FLAG_enable_embedded_constant_pool) {
// For the bottommost output frame the constant pool pointer can be gotten
// from the input frame. For subsequent output frames, it can be read from
// the previous frame.
const intptr_t caller_cp =
is_bottommost ? caller_constant_pool_
: output_[frame_index - 1]->GetConstantPool();
frame_writer.PushCallerConstantPool(caller_cp);
}
// For the bottommost output frame the context can be gotten from the input
// frame. For all subsequent output frames it can be gotten from the function
// so long as we don't inline functions that need local contexts.
// When deoptimizing into a catch block, we need to take the context
// from a register that was specified in the handler table.
TranslatedFrame::iterator context_pos = value_iterator++;
if (goto_catch_handler) {
// Skip to the translated value of the register specified
// in the handler table.
for (int i = 0; i < catch_handler_data_ + 1; ++i) {
context_pos++;
}
}
// Read the context from the translations.
Object context = context_pos->GetRawValue();
output_frame->SetContext(static_cast<intptr_t>(context.ptr()));
frame_writer.PushTranslatedValue(context_pos, "context");
// The function was mentioned explicitly in the BEGIN_FRAME.
frame_writer.PushTranslatedValue(function_iterator, "function");
// Set the bytecode array pointer.
Object bytecode_array = shared.HasBreakInfo()
? shared.GetDebugInfo().DebugBytecodeArray()
: shared.GetBytecodeArray();
frame_writer.PushRawObject(bytecode_array, "bytecode array\n");
// The bytecode offset was mentioned explicitly in the BEGIN_FRAME.
const int raw_bytecode_offset =
BytecodeArray::kHeaderSize - kHeapObjectTag + bytecode_offset;
Smi smi_bytecode_offset = Smi::FromInt(raw_bytecode_offset);
frame_writer.PushRawObject(smi_bytecode_offset, "bytecode offset\n");
if (trace_scope_ != nullptr) {
PrintF(trace_scope_->file(), " -------------------------\n");
}