-
-
Notifications
You must be signed in to change notification settings - Fork 35.4k
Expand file tree
/
Copy pathmaglev-graph-builder.h
More file actions
3368 lines (2987 loc) Β· 136 KB
/
maglev-graph-builder.h
File metadata and controls
3368 lines (2987 loc) Β· 136 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 2022 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.
#ifndef V8_MAGLEV_MAGLEV_GRAPH_BUILDER_H_
#define V8_MAGLEV_MAGLEV_GRAPH_BUILDER_H_
#include <cmath>
#include <iomanip>
#include <map>
#include <optional>
#include <type_traits>
#include <utility>
#include "src/base/hashing.h"
#include "src/base/logging.h"
#include "src/base/vector.h"
#include "src/codegen/external-reference.h"
#include "src/codegen/source-position-table.h"
#include "src/common/globals.h"
#include "src/compiler-dispatcher/optimizing-compile-dispatcher.h"
#include "src/compiler/bytecode-analysis.h"
#include "src/compiler/bytecode-liveness-map.h"
#include "src/compiler/feedback-source.h"
#include "src/compiler/heap-refs.h"
#include "src/compiler/js-heap-broker.h"
#include "src/compiler/processed-feedback.h"
#include "src/deoptimizer/deoptimize-reason.h"
#include "src/flags/flags.h"
#include "src/interpreter/bytecode-array-iterator.h"
#include "src/interpreter/bytecode-decoder.h"
#include "src/interpreter/bytecode-register.h"
#include "src/interpreter/bytecodes.h"
#include "src/interpreter/interpreter-intrinsics.h"
#include "src/maglev/maglev-compilation-unit.h"
#include "src/maglev/maglev-graph-labeller.h"
#include "src/maglev/maglev-graph-printer.h"
#include "src/maglev/maglev-graph.h"
#include "src/maglev/maglev-interpreter-frame-state.h"
#include "src/maglev/maglev-ir.h"
#include "src/objects/arguments.h"
#include "src/objects/bytecode-array.h"
#include "src/objects/elements-kind.h"
#include "src/objects/string.h"
#include "src/utils/memcopy.h"
namespace v8 {
namespace internal {
namespace maglev {
class CallArguments;
class ReduceResult;
class V8_NODISCARD MaybeReduceResult {
public:
enum Kind {
kDoneWithValue = 0, // No need to mask while returning the pointer.
kDoneWithAbort,
kDoneWithoutValue,
kFail,
};
MaybeReduceResult() : payload_(kFail) {}
// NOLINTNEXTLINE
MaybeReduceResult(ValueNode* value) : payload_(value) {
DCHECK_NOT_NULL(value);
}
static MaybeReduceResult Fail() { return MaybeReduceResult(kFail); }
MaybeReduceResult(const MaybeReduceResult&) V8_NOEXCEPT = default;
MaybeReduceResult& operator=(const MaybeReduceResult&) V8_NOEXCEPT = default;
ValueNode* value() const {
DCHECK(HasValue());
return payload_.GetPointerWithKnownPayload(kDoneWithValue);
}
bool HasValue() const { return kind() == kDoneWithValue; }
// Either DoneWithValue, DoneWithoutValue or DoneWithAbort.
bool IsDone() const { return !IsFail(); }
// MaybeReduceResult failed.
bool IsFail() const { return kind() == kFail; }
// Done with a ValueNode.
bool IsDoneWithValue() const { return HasValue(); }
// Done without producing a ValueNode.
bool IsDoneWithoutValue() const { return kind() == kDoneWithoutValue; }
// Done with an abort (unconditional deopt, infinite loop in an inlined
// function, etc)
bool IsDoneWithAbort() const { return kind() == kDoneWithAbort; }
Kind kind() const { return payload_.GetPayload(); }
inline ReduceResult Checked();
base::PointerWithPayload<ValueNode, Kind, 3> GetPayload() const {
return payload_;
}
protected:
explicit MaybeReduceResult(Kind kind) : payload_(kind) {}
explicit MaybeReduceResult(
base::PointerWithPayload<ValueNode, Kind, 3> payload)
: payload_(payload) {}
base::PointerWithPayload<ValueNode, Kind, 3> payload_;
};
class V8_NODISCARD ReduceResult : public MaybeReduceResult {
public:
// NOLINTNEXTLINE
ReduceResult(ValueNode* value) : MaybeReduceResult(value) {}
explicit ReduceResult(const MaybeReduceResult& other)
: MaybeReduceResult(other.GetPayload()) {
CHECK(!IsFail());
}
static ReduceResult Done(ValueNode* value) { return ReduceResult(value); }
static ReduceResult Done() { return ReduceResult(kDoneWithoutValue); }
static ReduceResult DoneWithAbort() { return ReduceResult(kDoneWithAbort); }
bool IsFail() const { return false; }
ReduceResult Checked() { return *this; }
protected:
explicit ReduceResult(Kind kind) : MaybeReduceResult(kind) {}
};
inline ReduceResult MaybeReduceResult::Checked() { return ReduceResult(*this); }
#define RETURN_IF_DONE(result) \
do { \
auto res = (result); \
if (res.IsDone()) { \
return res.Checked(); \
} \
} while (false)
#define RETURN_IF_ABORT(result) \
do { \
if ((result).IsDoneWithAbort()) { \
return ReduceResult::DoneWithAbort(); \
} \
} while (false)
#define PROCESS_AND_RETURN_IF_DONE(result, value_processor) \
do { \
auto res = (result); \
if (res.IsDone()) { \
if (res.IsDoneWithValue()) { \
value_processor(res.value()); \
} \
return res.Checked(); \
} \
} while (false)
#define GET_VALUE_OR_ABORT(variable, result) \
do { \
MaybeReduceResult res = (result); \
if (res.IsDoneWithAbort()) { \
return ReduceResult::DoneWithAbort(); \
} \
DCHECK(res.IsDoneWithValue()); \
using T = std::remove_pointer_t<std::decay_t<decltype(variable)>>; \
variable = res.value()->Cast<T>(); \
} while (false)
enum class UseReprHintRecording { kRecord, kDoNotRecord };
NodeType StaticTypeForNode(compiler::JSHeapBroker* broker,
LocalIsolate* isolate, ValueNode* node);
struct CatchBlockDetails {
BasicBlockRef* ref = nullptr;
bool exception_handler_was_used = false;
bool block_already_exists = false;
int deopt_frame_distance = 0;
};
struct MaglevCallerDetails {
base::Vector<ValueNode*> arguments;
DeoptFrame* deopt_frame;
KnownNodeAspects* known_node_aspects;
LoopEffects* loop_effects;
ZoneUnorderedMap<KnownNodeAspects::LoadedContextSlotsKey, Node*>
unobserved_context_slot_stores;
CatchBlockDetails catch_block;
bool is_inside_loop;
bool is_eager_inline;
float call_frequency;
};
struct MaglevCallSiteInfo {
MaglevCallerDetails caller_details;
CallKnownJSFunction* generic_call_node;
compiler::FeedbackCellRef feedback_cell;
float score;
};
class MaglevGraphBuilder {
public:
class DeoptFrameScope;
class V8_NODISCARD LazyDeoptResultLocationScope {
public:
LazyDeoptResultLocationScope(MaglevGraphBuilder* builder,
interpreter::Register result_location,
int result_size);
~LazyDeoptResultLocationScope();
interpreter::Register result_location() { return result_location_; }
int result_size() const { return result_size_; }
private:
MaglevGraphBuilder* builder_;
LazyDeoptResultLocationScope* previous_;
interpreter::Register result_location_;
int result_size_;
};
explicit MaglevGraphBuilder(LocalIsolate* local_isolate,
MaglevCompilationUnit* compilation_unit,
Graph* graph,
MaglevCallerDetails* caller_details = nullptr);
void Build() {
DCHECK(!is_inline());
DCHECK_EQ(inlining_id_, SourcePosition::kNotInlined);
current_source_position_ = SourcePosition(
compilation_unit_->shared_function_info().StartPosition(),
inlining_id_);
StartPrologue();
for (int i = 0; i < parameter_count(); i++) {
// TODO(v8:7700): Consider creating InitialValue nodes lazily.
InitialValue* v = AddNewNode<InitialValue>(
{}, interpreter::Register::FromParameterIndex(i));
DCHECK_EQ(graph()->parameters().size(), static_cast<size_t>(i));
graph()->parameters().push_back(v);
SetArgument(i, v);
}
BuildRegisterFrameInitialization();
// Don't use the AddNewNode helper for the function entry stack check, so
// that we can set a custom deopt frame on it.
FunctionEntryStackCheck* function_entry_stack_check =
NodeBase::New<FunctionEntryStackCheck>(zone(), 0);
new (function_entry_stack_check->lazy_deopt_info()) LazyDeoptInfo(
zone(), GetDeoptFrameForEntryStackCheck(),
interpreter::Register::invalid_value(), 0, compiler::FeedbackSource());
AddInitializedNodeToGraph(function_entry_stack_check);
BuildMergeStates();
EndPrologue();
in_prologue_ = false;
compiler::ScopeInfoRef scope_info =
compilation_unit_->shared_function_info().scope_info(broker());
if (scope_info.HasOuterScopeInfo()) {
scope_info = scope_info.OuterScopeInfo(broker());
CHECK(scope_info.HasContext());
graph()->record_scope_info(GetContext(), scope_info);
}
if (compilation_unit_->is_osr()) {
OsrAnalyzePrequel();
}
BuildBody();
}
ReduceResult BuildInlineFunction(SourcePosition call_site_position,
ValueNode* context, ValueNode* function,
ValueNode* new_target);
void StartPrologue();
void SetArgument(int i, ValueNode* value);
void InitializeRegister(interpreter::Register reg, ValueNode* value);
ValueNode* GetArgument(int i);
ValueNode* GetInlinedArgument(int i);
void BuildRegisterFrameInitialization(ValueNode* context = nullptr,
ValueNode* closure = nullptr,
ValueNode* new_target = nullptr);
void BuildMergeStates();
BasicBlock* EndPrologue();
void PeelLoop();
void BuildLoopForPeeling();
void OsrAnalyzePrequel();
void BuildBody() {
while (!source_position_iterator_.done() &&
source_position_iterator_.code_offset() < entrypoint_) {
current_source_position_ = SourcePosition(
source_position_iterator_.source_position().ScriptOffset(),
inlining_id_);
source_position_iterator_.Advance();
}
for (iterator_.SetOffset(entrypoint_); !iterator_.done();
iterator_.Advance()) {
local_isolate_->heap()->Safepoint();
if (V8_UNLIKELY(
loop_headers_to_peel_.Contains(iterator_.current_offset()))) {
PeelLoop();
DCHECK_EQ(iterator_.current_bytecode(),
interpreter::Bytecode::kJumpLoop);
continue;
}
VisitSingleBytecode();
}
DCHECK_EQ(loop_effects_stack_.size(),
is_inline() && caller_details_->loop_effects ? 1 : 0);
}
SmiConstant* GetSmiConstant(int constant) const {
DCHECK(Smi::IsValid(constant));
auto it = graph_->smi().find(constant);
if (it == graph_->smi().end()) {
SmiConstant* node =
CreateNewConstantNode<SmiConstant>(0, Smi::FromInt(constant));
graph_->smi().emplace(constant, node);
return node;
}
return it->second;
}
TaggedIndexConstant* GetTaggedIndexConstant(int constant) {
DCHECK(TaggedIndex::IsValid(constant));
auto it = graph_->tagged_index().find(constant);
if (it == graph_->tagged_index().end()) {
TaggedIndexConstant* node = CreateNewConstantNode<TaggedIndexConstant>(
0, TaggedIndex::FromIntptr(constant));
graph_->tagged_index().emplace(constant, node);
return node;
}
return it->second;
}
Int32Constant* GetInt32Constant(int32_t constant) {
auto it = graph_->int32().find(constant);
if (it == graph_->int32().end()) {
Int32Constant* node = CreateNewConstantNode<Int32Constant>(0, constant);
graph_->int32().emplace(constant, node);
return node;
}
return it->second;
}
Uint32Constant* GetUint32Constant(int constant) {
auto it = graph_->uint32().find(constant);
if (it == graph_->uint32().end()) {
Uint32Constant* node = CreateNewConstantNode<Uint32Constant>(0, constant);
graph_->uint32().emplace(constant, node);
return node;
}
return it->second;
}
Float64Constant* GetFloat64Constant(double constant) {
return GetFloat64Constant(
Float64::FromBits(base::double_to_uint64(constant)));
}
Float64Constant* GetFloat64Constant(Float64 constant) {
auto it = graph_->float64().find(constant.get_bits());
if (it == graph_->float64().end()) {
Float64Constant* node =
CreateNewConstantNode<Float64Constant>(0, constant);
graph_->float64().emplace(constant.get_bits(), node);
return node;
}
return it->second;
}
ValueNode* GetNumberConstant(double constant);
static compiler::OptionalHeapObjectRef TryGetConstant(
compiler::JSHeapBroker* broker, LocalIsolate* isolate, ValueNode* node);
Graph* graph() const { return graph_; }
Zone* zone() const { return compilation_unit_->zone(); }
MaglevCompilationUnit* compilation_unit() const { return compilation_unit_; }
const InterpreterFrameState& current_interpreter_frame() const {
return current_interpreter_frame_;
}
MaglevCallerDetails* caller_details() const { return caller_details_; }
const DeoptFrameScope* current_deopt_scope() const {
return current_deopt_scope_;
}
compiler::JSHeapBroker* broker() const { return broker_; }
LocalIsolate* local_isolate() const { return local_isolate_; }
bool has_graph_labeller() const {
return compilation_unit_->has_graph_labeller();
}
MaglevGraphLabeller* graph_labeller() const {
return compilation_unit_->graph_labeller();
}
// True when this graph builder is building the subgraph of an inlined
// function.
bool is_inline() const { return caller_details_ != nullptr; }
int inlining_depth() const { return compilation_unit_->inlining_depth(); }
bool is_eager_inline() const {
DCHECK(is_inline());
DCHECK_IMPLIES(!caller_details_->is_eager_inline,
v8_flags.maglev_non_eager_inlining ||
v8_flags.turbolev_non_eager_inlining);
return caller_details_->is_eager_inline;
}
DeoptFrame GetLatestCheckpointedFrame();
bool need_checkpointed_loop_entry() {
return v8_flags.maglev_speculative_hoist_phi_untagging ||
v8_flags.maglev_licm;
}
bool TopLevelFunctionPassMaglevPrintFilter();
void RecordUseReprHint(Phi* phi, UseRepresentationSet reprs) {
phi->RecordUseReprHint(reprs);
}
void RecordUseReprHint(Phi* phi, UseRepresentation repr) {
RecordUseReprHint(phi, UseRepresentationSet{repr});
}
void RecordUseReprHintIfPhi(ValueNode* node, UseRepresentation repr) {
if (Phi* phi = node->TryCast<Phi>()) {
RecordUseReprHint(phi, repr);
}
}
void set_current_block(BasicBlock* block) { current_block_ = block; }
BasicBlock* FinishInlinedBlockForCaller(
ControlNode* control_node, ZoneVector<Node*> rem_nodes_in_call_block);
ZoneVector<Node*>& node_buffer() { return graph_->node_buffer(); }
uint32_t NewObjectId() { return graph_->NewObjectId(); }
bool is_turbolev() const { return is_turbolev_; }
bool is_non_eager_inlining_enabled() const {
if (is_turbolev()) {
return v8_flags.turbolev_non_eager_inlining;
}
return v8_flags.maglev_non_eager_inlining;
}
// Inlining configuration. For Maglev, we use the Maglev flags, and for
// Turbolev, we use the Turbofan flags.
int max_inlined_bytecode_size() {
if (is_turbolev()) {
return v8_flags.max_inlined_bytecode_size;
} else {
return v8_flags.max_maglev_inlined_bytecode_size;
}
}
int max_inlined_bytecode_size_small() {
if (is_turbolev()) {
return v8_flags.max_inlined_bytecode_size_small;
} else {
return v8_flags.max_maglev_inlined_bytecode_size_small;
}
}
float min_inlining_frequency() {
if (is_turbolev()) {
return v8_flags.min_inlining_frequency;
} else {
return v8_flags.min_maglev_inlining_frequency;
}
}
int max_inlined_bytecode_size_cumulative() {
if (is_turbolev()) {
return v8_flags.max_inlined_bytecode_size_cumulative;
} else {
return v8_flags.max_maglev_inlined_bytecode_size_cumulative;
}
}
DeoptFrame* AddInlinedArgumentsToDeoptFrame(DeoptFrame* deopt_frame,
const MaglevCompilationUnit* unit,
ValueNode* closure,
base::Vector<ValueNode*> args);
private:
// Helper class for building a subgraph with its own control flow, that is not
// attached to any bytecode.
//
// It does this by creating a fake dummy compilation unit and frame state, and
// wrapping up all the places where it pretends to be interpreted but isn't.
class MaglevSubGraphBuilder {
public:
class Variable;
class Label;
class LoopLabel;
MaglevSubGraphBuilder(MaglevGraphBuilder* builder, int variable_count);
LoopLabel BeginLoop(std::initializer_list<Variable*> loop_vars);
template <typename ControlNodeT, typename... Args>
void GotoIfTrue(Label* true_target,
std::initializer_list<ValueNode*> control_inputs,
Args&&... args);
template <typename ControlNodeT, typename... Args>
void GotoIfFalse(Label* false_target,
std::initializer_list<ValueNode*> control_inputs,
Args&&... args);
void GotoOrTrim(Label* label);
void Goto(Label* label);
void ReducePredecessorCount(Label* label, unsigned num = 1);
void EndLoop(LoopLabel* loop_label);
void Bind(Label* label);
V8_NODISCARD ReduceResult TrimPredecessorsAndBind(Label* label);
void set(Variable& var, ValueNode* value);
ValueNode* get(const Variable& var) const;
template <typename FCond, typename FTrue, typename FFalse>
ReduceResult Branch(std::initializer_list<Variable*> vars, FCond cond,
FTrue if_true, FFalse if_false);
void MergeIntoLabel(Label* label, BasicBlock* predecessor);
private:
class BorrowParentKnownNodeAspectsAndVOs;
void TakeKnownNodeAspectsAndVOsFromParent();
void MoveKnownNodeAspectsAndVOsToParent();
MaglevGraphBuilder* builder_;
MaglevCompilationUnit* compilation_unit_;
InterpreterFrameState pseudo_frame_;
};
// TODO(olivf): Currently identifying dead code relies on the fact that loops
// must be entered through the loop header by at least one of the
// predecessors. We might want to re-evaluate this in case we want to be able
// to OSR into nested loops while compiling the full continuation.
static constexpr bool kLoopsMustBeEnteredThroughHeader = true;
class CallSpeculationScope;
class SaveCallSpeculationScope;
bool CheckStaticType(ValueNode* node, NodeType type, NodeType* old = nullptr);
bool CheckType(ValueNode* node, NodeType type, NodeType* old = nullptr);
NodeType CheckTypes(ValueNode* node, std::initializer_list<NodeType> types);
bool EnsureType(ValueNode* node, NodeType type, NodeType* old = nullptr);
NodeType GetType(ValueNode* node);
NodeInfo* GetOrCreateInfoFor(ValueNode* node) {
return known_node_aspects().GetOrCreateInfoFor(node, broker(),
local_isolate());
}
// Returns true if we statically know that {lhs} and {rhs} have disjoint
// types.
bool HaveDisjointTypes(ValueNode* lhs, ValueNode* rhs);
bool HasDisjointType(ValueNode* lhs, NodeType rhs_type);
template <typename Function>
bool EnsureType(ValueNode* node, NodeType type, Function ensure_new_type);
bool MayBeNullOrUndefined(ValueNode* node);
void SetKnownValue(ValueNode* node, compiler::ObjectRef constant,
NodeType new_node_type);
bool ShouldEmitInterruptBudgetChecks() {
if (is_inline()) {
return false;
}
if (is_turbolev()) {
// As the top-tier compiler, Turboshaft doesn't need interrupt budget
// checks.
return false;
}
return v8_flags.force_emit_interrupt_budget_checks || v8_flags.turbofan;
}
bool ShouldEmitOsrInterruptBudgetChecks() {
if (!v8_flags.turbofan || !v8_flags.use_osr || !v8_flags.osr_from_maglev)
return false;
if (!graph_->is_osr() && !v8_flags.always_osr_from_maglev) {
return false;
}
// TODO(olivf) OSR from maglev requires lazy recompilation (see
// CompileOptimizedOSRFromMaglev for details). Without this we end up in
// deopt loops, e.g., in chromium content_unittests.
if (!OptimizingCompileDispatcher::Enabled()) {
return false;
}
// TODO(olivf) OSR'ing from inlined loops is something we might want, but
// can't with our current osr-from-maglev implementation. The reason is that
// we OSR up by first going down to the interpreter. For inlined loops this
// means we would deoptimize to the caller and then probably end up in the
// same maglev osr code again, before reaching the turbofan OSR code in the
// callee. The solution is to support osr from maglev without
// deoptimization.
return !(graph_->is_osr() && is_inline());
}
bool MaglevIsTopTier() const { return !v8_flags.turbofan && v8_flags.maglev; }
BasicBlock* CreateEdgeSplitBlock(BasicBlockRef& jump_targets,
BasicBlock* predecessor) {
if (v8_flags.trace_maglev_graph_building) {
std::cout << "== New empty block ==" << std::endl;
PrintVirtualObjects();
}
DCHECK_NULL(current_block_);
current_block_ = zone()->New<BasicBlock>(nullptr, zone());
BasicBlock* result = FinishBlock<Jump>({}, &jump_targets);
result->set_edge_split_block(predecessor);
#ifdef DEBUG
new_nodes_.clear();
#endif
return result;
}
void ProcessMergePointAtExceptionHandlerStart(int offset) {
DCHECK_EQ(current_allocation_block_, nullptr);
MergePointInterpreterFrameState& merge_state = *merge_states_[offset];
DCHECK_EQ(merge_state.predecessor_count(), 0);
// Copy state.
current_interpreter_frame_.CopyFrom(*compilation_unit_, merge_state);
// Expressions would have to be explicitly preserved across exceptions.
// However, at this point we do not know which ones might be used.
current_interpreter_frame_.known_node_aspects()
->ClearAvailableExpressions();
// Merges aren't simple fallthroughs, so we should reset the checkpoint
// validity.
ResetBuilderCachedState();
// Register exception phis.
if (has_graph_labeller()) {
for (Phi* phi : *merge_states_[offset]->phis()) {
graph_labeller()->RegisterNode(phi, compilation_unit_,
BytecodeOffset(offset),
current_source_position_);
if (v8_flags.trace_maglev_graph_building) {
std::cout << " " << phi << " "
<< PrintNodeLabel(graph_labeller(), phi) << ": "
<< PrintNode(graph_labeller(), phi) << std::endl;
}
}
}
}
void ProcessMergePoint(int offset, bool preserve_known_node_aspects) {
// First copy the merge state to be the current state.
MergePointInterpreterFrameState& merge_state = *merge_states_[offset];
current_interpreter_frame_.CopyFrom(*compilation_unit_, merge_state,
preserve_known_node_aspects, zone());
ProcessMergePointPredecessors(merge_state, jump_targets_[offset]);
}
// Splits incoming critical edges and labels predecessors.
void ProcessMergePointPredecessors(
MergePointInterpreterFrameState& merge_state,
BasicBlockRef& jump_targets) {
// TODO(olivf): Support allocation folding across control flow.
DCHECK_EQ(current_allocation_block_, nullptr);
// Merges aren't simple fallthroughs, so we should reset state which is
// cached directly on the builder instead of on the merge states.
ResetBuilderCachedState();
if (merge_state.is_loop()) {
DCHECK_EQ(merge_state.predecessors_so_far(),
merge_state.predecessor_count() - 1);
} else {
DCHECK_EQ(merge_state.predecessors_so_far(),
merge_state.predecessor_count());
}
if (merge_state.predecessor_count() == 1) return;
// Set up edge-split.
int predecessor_index = merge_state.predecessor_count() - 1;
if (merge_state.is_loop()) {
// For loops, the JumpLoop block hasn't been generated yet, and so isn't
// in the list of jump targets. IT's the last predecessor, so drop the
// index by one.
DCHECK(merge_state.is_unmerged_loop());
predecessor_index--;
}
BasicBlockRef* old_jump_targets = jump_targets.Reset();
while (old_jump_targets != nullptr) {
BasicBlock* predecessor = merge_state.predecessor_at(predecessor_index);
CHECK(predecessor);
ControlNode* control = predecessor->control_node();
if (control->Is<ConditionalControlNode>()) {
// CreateEmptyBlock automatically registers itself with the offset.
predecessor = CreateEdgeSplitBlock(jump_targets, predecessor);
// Set the old predecessor's (the conditional block) reference to
// point to the new empty predecessor block.
old_jump_targets =
old_jump_targets->SetToBlockAndReturnNext(predecessor);
merge_state.set_predecessor_at(predecessor_index, predecessor);
} else {
// Re-register the block in the offset's ref list.
old_jump_targets = old_jump_targets->MoveToRefList(&jump_targets);
}
// We only set the predecessor id after splitting critical edges, to make
// sure the edge split blocks pick up the correct predecessor index.
predecessor->set_predecessor_id(predecessor_index--);
}
DCHECK_EQ(predecessor_index, -1);
RegisterPhisWithGraphLabeller(merge_state);
}
void RegisterPhisWithGraphLabeller(
MergePointInterpreterFrameState& merge_state) {
if (!has_graph_labeller()) return;
for (Phi* phi : *merge_state.phis()) {
graph_labeller()->RegisterNode(phi);
if (v8_flags.trace_maglev_graph_building) {
std::cout << " " << phi << " "
<< PrintNodeLabel(graph_labeller(), phi) << ": "
<< PrintNode(graph_labeller(), phi) << std::endl;
}
}
}
// Return true if the given offset is a merge point, i.e. there are jumps
// targetting it.
bool IsOffsetAMergePoint(int offset) {
return merge_states_[offset] != nullptr;
}
ValueNode* GetContextAtDepth(ValueNode* context, size_t depth);
bool CheckContextExtensions(size_t depth);
// Called when a block is killed by an unconditional eager deopt.
ReduceResult EmitUnconditionalDeopt(DeoptimizeReason reason) {
current_block_->set_deferred(true);
// Create a block rather than calling finish, since we don't yet know the
// next block's offset before the loop skipping the rest of the bytecodes.
FinishBlock<Deopt>({}, reason);
return ReduceResult::DoneWithAbort();
}
void KillPeeledLoopTargets(int peelings) {
DCHECK_EQ(iterator_.current_bytecode(), interpreter::Bytecode::kJumpLoop);
int target = iterator_.GetJumpTargetOffset();
// Since we ended up not peeling we must kill all the doubly accounted
// jumps out of the loop.
interpreter::BytecodeArrayIterator iterator(bytecode().object());
for (iterator.SetOffset(target);
iterator.current_offset() < iterator_.current_offset();
iterator.Advance()) {
interpreter::Bytecode bc = iterator.current_bytecode();
DCHECK_NE(bc, interpreter::Bytecode::kJumpLoop);
int kill = -1;
if (interpreter::Bytecodes::IsJump(bc) &&
iterator.GetJumpTargetOffset() > iterator_.current_offset()) {
kill = iterator.GetJumpTargetOffset();
} else if (is_inline() && interpreter::Bytecodes::Returns(bc)) {
kill = inline_exit_offset();
}
if (kill != -1) {
if (merge_states_[kill]) {
for (int i = 0; i < peelings; ++i) {
merge_states_[kill]->MergeDead(*compilation_unit_);
}
}
UpdatePredecessorCount(kill, -peelings);
}
}
}
void MarkBytecodeDead() {
DCHECK_NULL(current_block_);
if (v8_flags.trace_maglev_graph_building) {
std::cout << "== Dead ==\n"
<< std::setw(4) << iterator_.current_offset() << " : ";
interpreter::BytecodeDecoder::Decode(std::cout,
iterator_.current_address());
std::cout << std::endl;
}
// If the current bytecode is a jump to elsewhere, then this jump is
// also dead and we should make sure to merge it as a dead predecessor.
interpreter::Bytecode bytecode = iterator_.current_bytecode();
if (interpreter::Bytecodes::IsForwardJump(bytecode)) {
// Jumps merge into their target, and conditional jumps also merge into
// the fallthrough.
MergeDeadIntoFrameState(iterator_.GetJumpTargetOffset());
if (interpreter::Bytecodes::IsConditionalJump(bytecode)) {
MergeDeadIntoFrameState(iterator_.next_offset());
}
} else if (bytecode == interpreter::Bytecode::kJumpLoop) {
// JumpLoop merges into its loop header, which has to be treated
// specially by the merge.
if (!in_peeled_iteration() || in_optimistic_peeling_iteration()) {
MergeDeadLoopIntoFrameState(iterator_.GetJumpTargetOffset());
}
} else if (interpreter::Bytecodes::IsSwitch(bytecode)) {
// Switches merge into their targets, and into the fallthrough.
for (auto offset : iterator_.GetJumpTableTargetOffsets()) {
MergeDeadIntoFrameState(offset.target_offset);
}
MergeDeadIntoFrameState(iterator_.next_offset());
} else if (!interpreter::Bytecodes::Returns(bytecode) &&
!interpreter::Bytecodes::UnconditionallyThrows(bytecode)) {
// Any other bytecode that doesn't return or throw will merge into the
// fallthrough.
MergeDeadIntoFrameState(iterator_.next_offset());
} else if (interpreter::Bytecodes::Returns(bytecode) && is_inline()) {
MergeDeadIntoFrameState(inline_exit_offset());
}
// TODO(leszeks): We could now continue iterating the bytecode
}
void UpdateSourceAndBytecodePosition(int offset) {
if (source_position_iterator_.done()) return;
if (source_position_iterator_.code_offset() == offset) {
current_source_position_ = SourcePosition(
source_position_iterator_.source_position().ScriptOffset(),
inlining_id_);
source_position_iterator_.Advance();
} else {
DCHECK_GT(source_position_iterator_.code_offset(), offset);
}
}
void PrintVirtualObjects() {
if (!v8_flags.trace_maglev_graph_building) return;
current_interpreter_frame_.virtual_objects().Print(
std::cout, "* VOs (Interpreter Frame State): ",
compilation_unit()->graph_labeller());
}
void VisitSingleBytecode() {
if (v8_flags.trace_maglev_graph_building) {
std::cout << std::setw(4) << iterator_.current_offset() << " : ";
interpreter::BytecodeDecoder::Decode(std::cout,
iterator_.current_address());
std::cout << std::endl;
}
int offset = iterator_.current_offset();
UpdateSourceAndBytecodePosition(offset);
MergePointInterpreterFrameState* merge_state = merge_states_[offset];
if (V8_UNLIKELY(merge_state != nullptr)) {
bool preserve_known_node_aspects = in_optimistic_peeling_iteration() &&
loop_headers_to_peel_.Contains(offset);
if (merge_state->is_resumable_loop()) {
current_for_in_state.enum_cache_indices = nullptr;
}
if (current_block_ != nullptr) {
DCHECK(!preserve_known_node_aspects);
// TODO(leszeks): Re-evaluate this DCHECK, we might hit it if the only
// bytecodes in this basic block were only register juggling.
// DCHECK(!node_buffer().empty());
BasicBlock* predecessor;
if (merge_state->is_loop() && !merge_state->is_resumable_loop() &&
need_checkpointed_loop_entry()) {
predecessor =
FinishBlock<CheckpointedJump>({}, &jump_targets_[offset]);
} else {
predecessor = FinishBlock<Jump>({}, &jump_targets_[offset]);
}
merge_state->Merge(this, *compilation_unit_, current_interpreter_frame_,
predecessor);
}
if (v8_flags.trace_maglev_graph_building) {
auto detail = merge_state->is_exception_handler() ? "exception handler"
: merge_state->is_loop() ? "loop header"
: "merge";
std::cout << "== New block (" << detail << " @" << merge_state
<< ") at "
<< compilation_unit()->shared_function_info().object()
<< "==" << std::endl;
PrintVirtualObjects();
}
if (V8_UNLIKELY(merge_state->is_exception_handler())) {
CHECK_EQ(predecessor_count(offset), 0);
// If we have no reference to this block, then the exception handler is
// dead.
if (!jump_targets_[offset].has_ref() ||
!merge_state->exception_handler_was_used()) {
MarkBytecodeDead();
return;
}
ProcessMergePointAtExceptionHandlerStart(offset);
} else if (merge_state->is_unmerged_unreachable_loop()) {
// We encountered a loop header that is only reachable by the JumpLoop
// back-edge, but the bytecode_analysis didn't notice upfront. This can
// e.g. be a loop that is entered on a dead fall-through.
static_assert(kLoopsMustBeEnteredThroughHeader);
MarkBytecodeDead();
return;
} else {
ProcessMergePoint(offset, preserve_known_node_aspects);
}
if (is_loop_effect_tracking_enabled() && merge_state->is_loop()) {
BeginLoopEffects(offset);
}
// We pass nullptr for the `predecessor` argument of StartNewBlock because
// this block is guaranteed to have a merge_state_, and hence to not have
// a `predecessor_` field.
StartNewBlock(offset, /*predecessor*/ nullptr);
} else if (V8_UNLIKELY(current_block_ == nullptr)) {
// If we don't have a current block, the bytecode must be dead (because of
// some earlier deopt). Mark this bytecode dead too and return.
// TODO(leszeks): Merge these two conditions by marking dead states with
// a sentinel value.
if (predecessor_count(offset) == 1) {
CHECK_NULL(merge_state);
CHECK(bytecode_analysis().IsLoopHeader(offset));
} else {
CHECK_EQ(predecessor_count(offset), 0);
}
MarkBytecodeDead();
return;
}
// Handle exceptions if we have a table.
if (bytecode().handler_table_size() > 0) {
// Pop all entries where offset >= end.
while (IsInsideTryBlock()) {
HandlerTableEntry& entry = catch_block_stack_.top();
if (offset < entry.end) break;
catch_block_stack_.pop();
}
// Push new entries from interpreter handler table where offset >= start
// && offset < end.
HandlerTable table(*bytecode().object());
while (next_handler_table_index_ < table.NumberOfRangeEntries()) {
int start = table.GetRangeStart(next_handler_table_index_);
if (offset < start) break;
int end = table.GetRangeEnd(next_handler_table_index_);
if (offset >= end) {
next_handler_table_index_++;
continue;
}
int handler = table.GetRangeHandler(next_handler_table_index_);
catch_block_stack_.push({end, handler});
DCHECK_NOT_NULL(merge_states_[handler]);
next_handler_table_index_++;
}
}
DCHECK_NOT_NULL(current_block_);
#ifdef DEBUG
// Clear new nodes for the next VisitFoo
new_nodes_.clear();
#endif
if (iterator_.current_bytecode() == interpreter::Bytecode::kJumpLoop &&
iterator_.GetJumpTargetOffset() < entrypoint_) {
static_assert(kLoopsMustBeEnteredThroughHeader);
CHECK(EmitUnconditionalDeopt(DeoptimizeReason::kOSREarlyExit)
.IsDoneWithAbort());
MarkBytecodeDead();
return;
}
switch (iterator_.current_bytecode()) {
#define BYTECODE_CASE(name, ...) \
case interpreter::Bytecode::k##name: { \
if (Visit##name().IsDoneWithAbort()) { \
MarkBytecodeDead(); \
} \
break; \
}
BYTECODE_LIST(BYTECODE_CASE, BYTECODE_CASE)
#undef BYTECODE_CASE
}
}
#define BYTECODE_VISITOR(name, ...) ReduceResult Visit##name();
BYTECODE_LIST(BYTECODE_VISITOR, BYTECODE_VISITOR)
#undef BYTECODE_VISITOR
#define DECLARE_VISITOR(name, ...) \
ReduceResult VisitIntrinsic##name(interpreter::RegisterList args);
INTRINSICS_LIST(DECLARE_VISITOR)
#undef DECLARE_VISITOR
void AddInitializedNodeToGraph(Node* node) {
// VirtualObjects should never be add to the Maglev graph.
DCHECK(!node->Is<VirtualObject>());
node_buffer().push_back(node);
node->set_owner(current_block_);
if (has_graph_labeller())
graph_labeller()->RegisterNode(node, compilation_unit_,
BytecodeOffset(iterator_.current_offset()),
current_source_position_);
if (v8_flags.trace_maglev_graph_building) {