-
-
Notifications
You must be signed in to change notification settings - Fork 35.4k
Expand file tree
/
Copy pathoperations.h
More file actions
9836 lines (8370 loc) Β· 353 KB
/
operations.h
File metadata and controls
9836 lines (8370 loc) Β· 353 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_COMPILER_TURBOSHAFT_OPERATIONS_H_
#define V8_COMPILER_TURBOSHAFT_OPERATIONS_H_
#include <cmath>
#include <cstdint>
#include <cstring>
#include <limits>
#include <optional>
#include <tuple>
#include <type_traits>
#include <utility>
#include "src/base/logging.h"
#include "src/base/macros.h"
#include "src/base/platform/mutex.h"
#include "src/base/small-vector.h"
#include "src/base/template-utils.h"
#include "src/base/vector.h"
#include "src/codegen/external-reference.h"
#include "src/common/globals.h"
#include "src/compiler/common-operator.h"
#include "src/compiler/fast-api-calls.h"
#include "src/compiler/globals.h"
#include "src/compiler/simplified-operator.h"
#include "src/compiler/turboshaft/deopt-data.h"
#include "src/compiler/turboshaft/fast-hash.h"
#include "src/compiler/turboshaft/index.h"
#include "src/compiler/turboshaft/representations.h"
#include "src/compiler/turboshaft/snapshot-table.h"
#include "src/compiler/turboshaft/types.h"
#include "src/compiler/turboshaft/utils.h"
#include "src/compiler/turboshaft/zone-with-name.h"
#include "src/compiler/write-barrier-kind.h"
#include "src/flags/flags.h"
#if V8_ENABLE_WEBASSEMBLY
#include "src/wasm/wasm-objects.h"
#endif
namespace v8::internal {
class HeapObject;
V8_EXPORT_PRIVATE std::ostream& operator<<(std::ostream& os,
AbortReason reason);
} // namespace v8::internal
namespace v8::internal::compiler {
class CallDescriptor;
class JSWasmCallParameters;
class DeoptimizeParameters;
class FrameStateInfo;
class Node;
enum class TrapId : int32_t;
} // namespace v8::internal::compiler
namespace v8::internal::compiler::turboshaft {
inline constexpr char kCompilationZoneName[] = "compilation-zone";
class Block;
struct FrameStateData;
class Graph;
struct FrameStateOp;
enum class HashingStrategy {
kDefault,
// This strategy requires that hashing a graph during builtin construction
// (mksnapshot) produces the same hash for repeated runs of mksnapshot. This
// requires that no pointers and external constants are used in hashes.
kMakeSnapshotStable,
};
// This belongs to `VariableReducer` in `variable-reducer.h`. It is defined here
// because of cyclic header dependencies.
struct VariableData {
MaybeRegisterRepresentation rep;
bool loop_invariant;
IntrusiveSetIndex active_loop_variables_index = {};
};
using Variable = SnapshotTable<OpIndex, VariableData>::Key;
// DEFINING NEW OPERATIONS
// =======================
// For each operation `Foo`, we define:
// - An entry V(Foo) in one of the TURBOSHAFT*OPERATION list (eg,
// TURBOSHAFT_OPERATION_LIST_BLOCK_TERMINATOR,
// TURBOSHAFT_SIMPLIFIED_OPERATION_LIST etc), which defines
// `Opcode::kFoo` and whether the operation is a block terminator.
// - A `struct FooOp`, which derives from either `OperationT<FooOp>` or
// `FixedArityOperationT<k, FooOp>` if the op always has excactly `k` inputs.
// Furthermore, the struct has to contain:
// - A bunch of options directly as public fields.
// - A getter `options()` returning a tuple of all these options. This is used
// for default printing and hashing. Alternatively, `void
// PrintOptions(std::ostream& os) const` and `size_t hash_value() const` can
// also be defined manually.
// - Getters for named inputs.
// - A constructor that first takes all the inputs and then all the options. For
// a variable arity operation where the constructor doesn't take the inputs as
// a single base::Vector<OpIndex> argument, it's also necessary to overwrite
// the static `New` function, see `CallOp` for an example.
// - An `Explode` method that unpacks an operation and invokes the passed
// callback. If the operation inherits from FixedArityOperationT, the base
// class already provides the required implementation.
// - `OpEffects` as either a static constexpr member `effects` or a
// non-static method `Effects()` if the effects depend on the particular
// operation and not just the opcode.
// - outputs_rep/inputs_rep methods, which should return a vector describing the
// representation of the outputs and inputs of this operations.
// After defining the struct here, you'll also need to integrate it in
// Turboshaft:
// - If Foo is not lowered before reaching the instruction selector, handle
// Opcode::kFoo in the Turboshaft VisitNode of instruction-selector.cc.
#ifdef V8_INTL_SUPPORT
#define TURBOSHAFT_INTL_OPERATION_LIST(V) V(StringToCaseIntl)
#else
#define TURBOSHAFT_INTL_OPERATION_LIST(V)
#endif // V8_INTL_SUPPORT
#ifdef V8_ENABLE_WEBASSEMBLY
// These operations should be lowered to Machine operations during
// WasmLoweringPhase.
#define TURBOSHAFT_WASM_OPERATION_LIST(V) \
V(WasmStackCheck) \
V(WasmIncCoverageCounter) \
V(GlobalGet) \
V(GlobalSet) \
V(RootConstant) \
V(IsRootConstant) \
V(Null) \
V(IsNull) \
V(AssertNotNull) \
V(RttCanon) \
V(WasmTypeCheck) \
V(WasmTypeCast) \
V(AnyConvertExtern) \
V(ExternConvertAny) \
V(WasmTypeAnnotation) \
V(StructGet) \
V(StructSet) \
V(StructAtomicRMW) \
V(ArrayGet) \
V(ArraySet) \
V(ArrayAtomicRMW) \
V(ArrayLength) \
V(WasmAllocateArray) \
V(WasmAllocateStruct) \
V(WasmRefFunc) \
V(StringAsWtf16) \
V(StringPrepareForGetCodeUnit)
#ifdef V8_ENABLE_WASM_DEINTERLEAVED_MEM_OPS
#define TURBOSHAFT_DEINTERLEAVED_OPERATION_LIST(V) \
V(Simd128LoadPairDeinterleave)
#else
#define TURBOSHAFT_DEINTERLEAVED_OPERATION_LIST(V)
#endif
#if V8_ENABLE_WASM_SIMD256_REVEC
#define TURBOSHAFT_SIMD256_COMMOM_OPERATION_LIST(V) \
V(Simd256Constant) \
V(Simd256Extract128Lane) \
V(Simd256LoadTransform) \
V(Simd256Unary) \
V(Simd256Binop) \
V(Simd256Shift) \
V(Simd256Ternary) \
V(Simd256Splat) \
V(SimdPack128To256)
#if V8_TARGET_ARCH_X64
#define TURBOSHAFT_SIMD256_X64_OPERATION_LIST(V) \
V(Simd256Shufd) \
V(Simd256Shufps) \
V(Simd256Unpack)
#define TURBOSHAFT_SIMD256_OPERATION_LIST(V) \
TURBOSHAFT_SIMD256_COMMOM_OPERATION_LIST(V) \
TURBOSHAFT_SIMD256_X64_OPERATION_LIST(V)
#else
#define TURBOSHAFT_SIMD256_OPERATION_LIST(V) \
TURBOSHAFT_SIMD256_COMMOM_OPERATION_LIST(V)
#endif // V8_TARGET_ARCH_X64
#else
#define TURBOSHAFT_SIMD256_OPERATION_LIST(V)
#endif
#define TURBOSHAFT_SIMD_OPERATION_LIST(V) \
V(Simd128Constant) \
V(Simd128Binop) \
V(Simd128Unary) \
V(Simd128Reduce) \
V(Simd128Shift) \
V(Simd128Test) \
V(Simd128Splat) \
V(Simd128Ternary) \
V(Simd128ExtractLane) \
V(Simd128ReplaceLane) \
V(Simd128LaneMemory) \
V(Simd128LoadTransform) \
V(Simd128Shuffle) \
TURBOSHAFT_SIMD256_OPERATION_LIST(V) \
TURBOSHAFT_DEINTERLEAVED_OPERATION_LIST(V)
#else
#define TURBOSHAFT_WASM_OPERATION_LIST(V)
#define TURBOSHAFT_SIMD_OPERATION_LIST(V)
#endif
#define TURBOSHAFT_OPERATION_LIST_BLOCK_TERMINATOR(V) \
V(CheckException) \
V(Goto) \
V(TailCall) \
V(Unreachable) \
V(Return) \
V(Branch) \
V(Switch) \
V(Deoptimize)
#ifdef V8_ENABLE_CONTINUATION_PRESERVED_EMBEDDER_DATA
#define TURBOSHAFT_CPED_OPERATION_LIST(V) \
V(GetContinuationPreservedEmbedderData) \
V(SetContinuationPreservedEmbedderData)
#else
#define TURBOSHAFT_CPED_OPERATION_LIST(V)
#endif // V8_ENABLE_CONTINUATION_PRESERVED_EMBEDDER_DATA
// These operations should be lowered to Machine operations during
// MachineLoweringPhase.
#define TURBOSHAFT_SIMPLIFIED_OPERATION_LIST(V) \
TURBOSHAFT_INTL_OPERATION_LIST(V) \
TURBOSHAFT_CPED_OPERATION_LIST(V) \
V(ArgumentsLength) \
V(BigIntBinop) \
V(BigIntComparison) \
V(BigIntUnary) \
V(CheckedClosure) \
V(WordBinopDeoptOnOverflow) \
V(CheckEqualsInternalizedString) \
V(CheckMaps) \
V(CompareMaps) \
V(Float64Is) \
V(ObjectIs) \
V(ObjectIsNumericValue) \
V(Float64SameValue) \
V(SameValue) \
V(ChangeOrDeopt) \
V(Convert) \
V(ConvertJSPrimitiveToObject) \
V(ConvertJSPrimitiveToUntagged) \
V(ConvertJSPrimitiveToUntaggedOrDeopt) \
V(ConvertUntaggedToJSPrimitive) \
V(ConvertUntaggedToJSPrimitiveOrDeopt) \
V(TruncateJSPrimitiveToUntagged) \
V(TruncateJSPrimitiveToUntaggedOrDeopt) \
V(DoubleArrayMinMax) \
V(EnsureWritableFastElements) \
V(FastApiCall) \
V(FindOrderedHashEntry) \
V(LoadDataViewElement) \
V(LoadFieldByIndex) \
V(LoadMessage) \
V(LoadStackArgument) \
V(LoadTypedElement) \
V(StoreDataViewElement) \
V(StoreMessage) \
V(StoreTypedElement) \
V(MaybeGrowFastElements) \
V(NewArgumentsElements) \
V(NewArray) \
V(RuntimeAbort) \
V(StaticAssert) \
V(StringAt) \
V(StringComparison) \
V(StringConcat) \
V(StringFromCodePointAt) \
V(StringIndexOf) \
V(StringLength) \
V(StringOrOddballStrictEqual) \
V(TypedArrayLength) \
V(StringSubstring) \
V(NewConsString) \
V(TransitionAndStoreArrayElement) \
V(TransitionElementsKind) \
V(TransitionElementsKindOrCheckMap) \
V(DebugPrint) \
V(CheckTurboshaftTypeOf) \
V(Word32SignHint)
// These Operations are the lowest level handled by Turboshaft, and are
// supported by the InstructionSelector.
#define TURBOSHAFT_MACHINE_OPERATION_LIST(V) \
V(WordBinop) \
V(FloatBinop) \
V(Word32PairBinop) \
V(OverflowCheckedBinop) \
V(WordUnary) \
V(OverflowCheckedUnary) \
V(FloatUnary) \
V(Shift) \
V(Comparison) \
V(Change) \
V(TryChange) \
V(BitcastWord32PairToFloat64) \
V(TaggedBitcast) \
V(Select) \
V(PendingLoopPhi) \
V(Constant) \
V(LoadRootRegister) \
V(Load) \
V(Store) \
V(Retain) \
V(Parameter) \
V(OsrValue) \
V(StackPointerGreaterThan) \
V(StackSlot) \
V(FrameConstant) \
V(DeoptimizeIf) \
IF_WASM(V, TrapIf) \
IF_WASM(V, LoadStackPointer) \
IF_WASM(V, SetStackPointer) \
IF_WASM(V, MemoryCopy) \
IF_WASM(V, MemoryFill) \
V(Phi) \
V(FrameState) \
V(Call) \
V(CatchBlockBegin) \
V(DidntThrow) \
V(MakeTuple) \
V(Projection) \
V(DebugBreak) \
V(AssumeMap) \
V(AtomicRMW) \
V(AtomicWord32Pair) \
V(MemoryBarrier) \
V(Comment) \
V(Dead) \
V(AbortCSADcheck) \
V(Pause)
#define TURBOSHAFT_JS_THROWING_OPERATION_LIST(V) \
V(GenericBinop) \
V(GenericUnop) \
V(ToNumberOrNumeric)
#define TURBOSHAFT_JS_OPERATION_LIST(V) \
TURBOSHAFT_JS_THROWING_OPERATION_LIST(V)
// These are operations that are not Machine operations and need to be lowered
// before Instruction Selection, but they are not lowered during the
// MachineLoweringPhase.
#define TURBOSHAFT_OTHER_OPERATION_LIST(V) \
V(Allocate) \
V(DecodeExternalPointer) \
V(JSStackCheck)
#define TURBOSHAFT_OPERATION_LIST_NOT_BLOCK_TERMINATOR(V) \
TURBOSHAFT_WASM_OPERATION_LIST(V) \
TURBOSHAFT_SIMD_OPERATION_LIST(V) \
TURBOSHAFT_MACHINE_OPERATION_LIST(V) \
TURBOSHAFT_SIMPLIFIED_OPERATION_LIST(V) \
TURBOSHAFT_JS_OPERATION_LIST(V) \
TURBOSHAFT_OTHER_OPERATION_LIST(V)
#define TURBOSHAFT_OPERATION_LIST(V) \
TURBOSHAFT_OPERATION_LIST_BLOCK_TERMINATOR(V) \
TURBOSHAFT_OPERATION_LIST_NOT_BLOCK_TERMINATOR(V)
enum class Opcode : uint8_t {
#define ENUM_CONSTANT(Name) k##Name,
TURBOSHAFT_OPERATION_LIST(ENUM_CONSTANT)
#undef ENUM_CONSTANT
};
const char* OpcodeName(Opcode opcode);
constexpr std::underlying_type_t<Opcode> OpcodeIndex(Opcode x) {
return static_cast<std::underlying_type_t<Opcode>>(x);
}
#define FORWARD_DECLARE(Name) struct Name##Op;
TURBOSHAFT_OPERATION_LIST(FORWARD_DECLARE)
#undef FORWARD_DECLARE
namespace detail {
template <class Op>
struct operation_to_opcode_map {};
#define OPERATION_OPCODE_MAP_CASE(Name) \
template <> \
struct operation_to_opcode_map<Name##Op> \
: std::integral_constant<Opcode, Opcode::k##Name> {};
TURBOSHAFT_OPERATION_LIST(OPERATION_OPCODE_MAP_CASE)
#undef OPERATION_OPCODE_MAP_CASE
} // namespace detail
template <typename Op>
struct operation_to_opcode
: detail::operation_to_opcode_map<std::remove_cvref_t<Op>> {};
template <typename Op>
constexpr Opcode operation_to_opcode_v = operation_to_opcode<Op>::value;
template <typename Op, uint64_t Mask, uint64_t Value>
struct OpMaskT {
using operation = Op;
static constexpr uint64_t mask = Mask;
static constexpr uint64_t value = Value;
};
#define COUNT_OPCODES(Name) +1
constexpr uint16_t kNumberOfBlockTerminatorOpcodes =
0 TURBOSHAFT_OPERATION_LIST_BLOCK_TERMINATOR(COUNT_OPCODES);
#undef COUNT_OPCODES
#define COUNT_OPCODES(Name) +1
constexpr uint16_t kNumberOfOpcodes =
0 TURBOSHAFT_OPERATION_LIST(COUNT_OPCODES);
#undef COUNT_OPCODES
inline constexpr bool IsBlockTerminator(Opcode opcode) {
return OpcodeIndex(opcode) < kNumberOfBlockTerminatorOpcodes;
}
// Operations that can throw and that have static output representations.
#define TURBOSHAFT_THROWING_STATIC_OUTPUTS_OPERATIONS_LIST(V) \
TURBOSHAFT_JS_THROWING_OPERATION_LIST(V)
// This list repeats the operations that may throw and need to be followed by
// `DidntThrow`.
#define TURBOSHAFT_THROWING_OPERATIONS_LIST(V) \
TURBOSHAFT_THROWING_STATIC_OUTPUTS_OPERATIONS_LIST(V) \
V(Call) \
V(FastApiCall)
// Operations that need to be followed by `DidntThrowOp`.
inline constexpr bool MayThrow(Opcode opcode) {
#define CASE(Name) case Opcode::k##Name:
switch (opcode) {
TURBOSHAFT_THROWING_OPERATIONS_LIST(CASE)
return true;
default:
return false;
}
#undef CASE
}
// For Throwing operations, outputs_rep() are empty, because the values are
// produced by the subsequent DidntThrow. Nevertheless, the operation has to
// define its output representations in an array that DidntThrow can then reuse
// to know what its outputs are. Additionally, when using Maglev as a frontend,
// catch handlers that have never been reach so far are not emitted, and instead
// the throwing operations lazy deopt instead of throwing.
//
// That's where the THROWING_OP_BOILERPLATE macro comes in: it creates an array
// of representations that DidntThrow can use, and will define outputs_rep() to
// be empty, and takes care of creating a LazyDeoptOnThrow member. For instance:
//
// THROWING_OP_BOILERPLATE(RegisterRepresentation::Tagged(),
// RegisterRepresentation::Word32())
//
// Warning: don't forget to add `lazy_deopt_on_throw` to the `options` of your
// Operation (you'll get a compile-time error if you forget it).
#define THROWING_OP_BOILERPLATE(...) \
static constexpr RegisterRepresentation kOutputRepsStorage[]{__VA_ARGS__}; \
static constexpr base::Vector<const RegisterRepresentation> kOutReps = \
base::VectorOf(kOutputRepsStorage, arraysize(kOutputRepsStorage)); \
base::Vector<const RegisterRepresentation> outputs_rep() const { \
return {}; \
} \
LazyDeoptOnThrow lazy_deopt_on_throw;
template <typename T>
inline base::Vector<T> InitVectorOf(
ZoneVector<T>& storage,
std::initializer_list<RegisterRepresentation> values) {
storage.resize(values.size());
size_t i = 0;
for (auto&& value : values) {
storage[i++] = value;
}
return base::VectorOf(storage);
}
class InputsRepFactory {
public:
constexpr static base::Vector<const MaybeRegisterRepresentation> SingleRep(
RegisterRepresentation rep) {
return base::VectorOf(ToMaybeRepPointer(rep), 1);
}
constexpr static base::Vector<const MaybeRegisterRepresentation> PairOf(
RegisterRepresentation rep) {
return base::VectorOf(ToMaybeRepPointer(rep), 2);
}
protected:
constexpr static const MaybeRegisterRepresentation* ToMaybeRepPointer(
RegisterRepresentation rep) {
size_t index = static_cast<size_t>(rep.value()) * 2;
DCHECK_LT(index, arraysize(rep_map));
return &rep_map[index];
}
private:
constexpr static MaybeRegisterRepresentation rep_map[] = {
MaybeRegisterRepresentation::Word32(),
MaybeRegisterRepresentation::Word32(),
MaybeRegisterRepresentation::Word64(),
MaybeRegisterRepresentation::Word64(),
MaybeRegisterRepresentation::Float32(),
MaybeRegisterRepresentation::Float32(),
MaybeRegisterRepresentation::Float64(),
MaybeRegisterRepresentation::Float64(),
MaybeRegisterRepresentation::Tagged(),
MaybeRegisterRepresentation::Tagged(),
MaybeRegisterRepresentation::Compressed(),
MaybeRegisterRepresentation::Compressed(),
MaybeRegisterRepresentation::Simd128(),
MaybeRegisterRepresentation::Simd128(),
#ifdef V8_ENABLE_WASM_SIMD256_REVEC
MaybeRegisterRepresentation::Simd256(),
MaybeRegisterRepresentation::Simd256(),
#endif // V8_ENABLE_WASM_SIMD256_REVEC
};
};
struct __attribute__((packed)) EffectDimensions {
// Produced by loads, consumed by operations that should not move before loads
// because they change memory.
bool load_heap_memory : 1;
bool load_off_heap_memory : 1;
// Produced by stores, consumed by operations that should not move before
// stores because they load or store memory.
bool store_heap_memory : 1;
bool store_off_heap_memory : 1;
// Operations that perform raw heap access (like initialization) consume
// `before_raw_heap_access` and produce `after_raw_heap_access`.
// Operations that need the heap to be in a consistent state produce
// `before_raw_heap_access` and consume `after_raw_heap_access`.
bool before_raw_heap_access : 1;
// Produced by operations that access raw/untagged pointers into the
// heap or keep such a pointer alive, consumed by operations that can GC to
// ensure they don't move before the raw access.
bool after_raw_heap_access : 1;
// Produced by any operation that can affect whether subsequent operations are
// executed, for example by branching, deopting, throwing or aborting.
// Consumed by all operations that should not be hoisted before a check
// because they rely on it. For example, loads usually rely on the shape of
// the heap object or the index being in bounds.
bool control_flow : 1;
// We need to ensure that the padding bits have a specified value, as they are
// observable in bitwise operations.
uint8_t unused_padding : 1;
using Bits = uint8_t;
constexpr EffectDimensions()
: load_heap_memory(false),
load_off_heap_memory(false),
store_heap_memory(false),
store_off_heap_memory(false),
before_raw_heap_access(false),
after_raw_heap_access(false),
control_flow(false),
unused_padding(0) {}
Bits bits() const { return base::bit_cast<Bits>(*this); }
static EffectDimensions FromBits(Bits bits) {
return base::bit_cast<EffectDimensions>(bits);
}
bool operator==(EffectDimensions other) const {
return bits() == other.bits();
}
bool operator!=(EffectDimensions other) const {
return bits() != other.bits();
}
};
static_assert(sizeof(EffectDimensions) == sizeof(EffectDimensions::Bits));
// Possible reorderings are restricted using two bit vectors: `produces` and
// `consumes`. Two operations cannot be reordered if the first operation
// produces an effect dimension that the second operation consumes. This is not
// necessarily symmetric. For example, it is possible to reorder
// Load(x)
// CheckMaps(y)
// to become
// CheckMaps(x)
// Load(y)
// because the load cannot affect the map check. But the other direction could
// be unsound, if the load depends on the map check having been executed. The
// former reordering is useful to push a load across a check into a branch if
// it is only needed there. The effect system expresses this by having the map
// check produce `EffectDimensions::control_flow` and the load consuming
// `EffectDimensions::control_flow`. If the producing operation comes before the
// consuming operation, then this order has to be preserved. But if the
// consuming operation comes first, then we are free to reorder them. Operations
// that produce and consume the same effect dimension always have a fixed order
// among themselves. For example, stores produce and consume the store
// dimensions. It is possible for operations to be reorderable unless certain
// other operations appear in-between. This way, the IR can be generous with
// reorderings as long as all operations are high-level, but become more
// restrictive as soon as low-level operations appear. For example, allocations
// can be freely reordered. Tagged bitcasts can be reordered with other tagged
// bitcasts. But a tagged bitcast cannot be reordered with allocations, as this
// would mean that an untagged pointer can be alive while a GC is happening. The
// way this works is that allocations produce the `before_raw_heap_access`
// dimension and consume the `after_raw_heap_access` dimension to stay either
// before or after a raw heap access. This means that there are no ordering
// constraints between allocations themselves. Bitcasts should not
// be moved accross an allocation. We treat them as raw heap access by letting
// them consume `before_raw_heap_access` and produce `after_raw_heap_access`.
// This way, allocations cannot be moved across bitcasts. Similarily,
// initializing stores and uninitialized allocations are classified as raw heap
// access, to prevent any operation that relies on a consistent heap state to be
// scheduled in the middle of an inline allocation. As long as we didn't lower
// to raw heap accesses yet, pure allocating operations or operations reading
// immutable memory can float freely. As soon as there are raw heap accesses,
// they become more restricted in their movement. Note that calls are not the
// most side-effectful operations, as they do not leave the heap in an
// inconsistent state, so they do not need to be marked as raw heap access.
struct __attribute__((packed)) OpEffects {
EffectDimensions produces;
EffectDimensions consumes;
// Operations that cannot be merged because they produce identity. That is,
// every repetition can produce a different result, but the order in which
// they are executed does not matter. All we care about is that they are
// different. Producing a random number or allocating an object with
// observable pointer equality are examples. Producing identity doesn't
// restrict reordering in straight-line code, but we must prevent using GVN or
// moving identity-producing operations in- or out of loops.
bool can_create_identity : 1;
// If the operation can allocate and therefore can trigger GC.
bool can_allocate : 1;
// Instructions that have no uses but are `required_when_unused` should not be
// removed.
bool required_when_unused : 1;
// We need to ensure that the padding bits have a specified value, as they are
// observable in bitwise operations. This is split into two fields so that
// also MSVC creates the correct object layout.
uint8_t unused_padding_1 : 5;
uint8_t unused_padding_2;
constexpr OpEffects()
: can_create_identity(false),
can_allocate(false),
required_when_unused(false),
unused_padding_1(0),
unused_padding_2(0) {}
using Bits = uint32_t;
Bits bits() const { return base::bit_cast<Bits>(*this); }
static OpEffects FromBits(Bits bits) {
return base::bit_cast<OpEffects>(bits);
}
bool operator==(OpEffects other) const { return bits() == other.bits(); }
bool operator!=(OpEffects other) const { return bits() != other.bits(); }
OpEffects operator|(OpEffects other) const {
return FromBits(bits() | other.bits());
}
OpEffects operator&(OpEffects other) const {
return FromBits(bits() & other.bits());
}
bool IsSubsetOf(OpEffects other) const {
return (bits() & ~other.bits()) == 0;
}
constexpr OpEffects AssumesConsistentHeap() const {
OpEffects result = *this;
// Do not move the operation into a region with raw heap access.
result.produces.before_raw_heap_access = true;
result.consumes.after_raw_heap_access = true;
return result;
}
// Like `CanAllocate()`, but allocated values must be immutable and not have
// identity (for example `HeapNumber`).
// Note that if we first allocate something as mutable and later make it
// immutable, we have to allocate it with identity.
constexpr OpEffects CanAllocateWithoutIdentity() const {
OpEffects result = AssumesConsistentHeap();
result.can_allocate = true;
return result;
}
// Allocations change the GC state and can trigger GC, as well as produce a
// fresh identity.
constexpr OpEffects CanAllocate() const {
return CanAllocateWithoutIdentity().CanCreateIdentity();
}
// The operation can leave the heap in an incosistent state or have untagged
// pointers into the heap as input or output.
constexpr OpEffects CanDoRawHeapAccess() const {
OpEffects result = *this;
// Do not move any operation that relies on a consistent heap state accross.
result.produces.after_raw_heap_access = true;
result.consumes.before_raw_heap_access = true;
return result;
}
// Reading mutable heap memory. Reading immutable memory doesn't count.
constexpr OpEffects CanReadHeapMemory() const {
OpEffects result = *this;
result.produces.load_heap_memory = true;
// Do not reorder before stores.
result.consumes.store_heap_memory = true;
return result;
}
// Reading mutable off-heap memory or other input. Reading immutable memory
// doesn't count.
constexpr OpEffects CanReadOffHeapMemory() const {
OpEffects result = *this;
result.produces.load_off_heap_memory = true;
// Do not reorder before stores.
result.consumes.store_off_heap_memory = true;
return result;
}
// Writing any off-memory or other output.
constexpr OpEffects CanWriteOffHeapMemory() const {
OpEffects result = *this;
result.required_when_unused = true;
result.produces.store_off_heap_memory = true;
// Do not reorder before stores.
result.consumes.store_off_heap_memory = true;
// Do not reorder before loads.
result.consumes.load_off_heap_memory = true;
// Do not move before deopting or aborting operations.
result.consumes.control_flow = true;
return result;
}
// Writing heap memory that existed before the operation started. Initializing
// newly allocated memory doesn't count.
constexpr OpEffects CanWriteHeapMemory() const {
OpEffects result = *this;
result.required_when_unused = true;
result.produces.store_heap_memory = true;
// Do not reorder before stores.
result.consumes.store_heap_memory = true;
// Do not reorder before loads.
result.consumes.load_heap_memory = true;
// Do not move before deopting or aborting operations.
result.consumes.control_flow = true;
return result;
}
// Writing any memory or other output, on- or off-heap.
constexpr OpEffects CanWriteMemory() const {
return CanWriteHeapMemory().CanWriteOffHeapMemory();
}
// Reading any memory or other input, on- or off-heap.
constexpr OpEffects CanReadMemory() const {
return CanReadHeapMemory().CanReadOffHeapMemory();
}
// The operation might read immutable data from the heap, so it can be freely
// reordered with operations that keep the heap in a consistent state. But we
// must prevent the operation from observing an incompletely initialized
// object.
constexpr OpEffects CanReadImmutableMemory() const {
OpEffects result = AssumesConsistentHeap();
return result;
}
// Partial operations that are only safe to execute after we performed certain
// checks, for example loads may only be safe after a corresponding bound or
// map checks.
constexpr OpEffects CanDependOnChecks() const {
OpEffects result = *this;
result.consumes.control_flow = true;
return result;
}
// The operation can affect control flow (like branch, deopt, throw or crash).
constexpr OpEffects CanChangeControlFlow() const {
OpEffects result = *this;
result.required_when_unused = true;
// Signal that this changes control flow. Prevents stores or operations
// relying on checks from flowing before this operation.
result.produces.control_flow = true;
// Stores must not flow past something that affects control flow.
result.consumes.store_heap_memory = true;
result.consumes.store_off_heap_memory = true;
return result;
}
// Execution of the current function may end with this operation, for example
// because of return, deopt, exception throw or abort/trap.
constexpr OpEffects CanLeaveCurrentFunction() const {
// All memory becomes observable.
return CanChangeControlFlow().CanReadMemory().RequiredWhenUnused();
}
// The operation can deopt.
constexpr OpEffects CanDeopt() const {
return CanLeaveCurrentFunction()
// We might depend on previous checks to avoid deopting.
.CanDependOnChecks();
}
constexpr OpEffects CanThrowOrTrap() const {
// Allocates an exception.
return CanLeaveCurrentFunction().CanAllocate();
}
// Producing identity doesn't prevent reorderings, but it prevents GVN from
// de-duplicating identical operations.
constexpr OpEffects CanCreateIdentity() const {
OpEffects result = *this;
result.can_create_identity = true;
return result;
}
// The set of all possible effects.
constexpr OpEffects CanCallAnything() const {
return CanReadMemory()
.CanWriteMemory()
.CanAllocate()
.CanChangeControlFlow()
.CanDependOnChecks()
.RequiredWhenUnused();
}
constexpr OpEffects RequiredWhenUnused() const {
OpEffects result = *this;
result.required_when_unused = true;
return result;
}
// Operations that can be removed if their result is not used. Unused
// allocations can be removed.
constexpr bool is_required_when_unused() const {
return required_when_unused;
}
// Operations that can be moved before a preceding branch or check.
bool hoistable_before_a_branch() const {
// Since this excludes `CanDependOnChecks()`, most loads actually cannot be
// hoisted.
return IsSubsetOf(OpEffects().CanReadMemory());
}
bool can_read_mutable_memory() const {
return produces.load_heap_memory | produces.load_off_heap_memory;
}
bool requires_consistent_heap() const {
return produces.before_raw_heap_access | consumes.after_raw_heap_access;
}
bool can_write() const {
return produces.store_heap_memory | produces.store_off_heap_memory;
}
bool can_be_constant_folded() const {
// Operations that CanDependOnChecks can still be constant-folded. If they
// did indeed depend on a check, then their result will only be used after
// said check has been executed anyways.
return IsSubsetOf(OpEffects().CanDependOnChecks());
}
};
static_assert(sizeof(OpEffects) == sizeof(OpEffects::Bits));
V8_INLINE size_t hash_value(OpEffects effects) {
return static_cast<size_t>(effects.bits());
}
inline bool CannotSwapOperations(OpEffects first, OpEffects second) {
return first.produces.bits() & (second.consumes.bits());
}
inline bool CannotSwapProtectedLoads(OpEffects first, OpEffects second) {
EffectDimensions produces = first.produces;
// The control flow effects produced by Loads are due to trap handler. We can
// ignore this kind of effect when swapping two Loads that both have trap
// handler.
produces.control_flow = false;
return produces.bits() & (second.consumes.bits());
}
V8_EXPORT_PRIVATE std::ostream& operator<<(std::ostream& os,
OpEffects op_effects);
// SaturatedUint8 is a wrapper around a uint8_t, which can be incremented and
// decremented with the `Incr` and `Decr` methods. These methods prevent over-
// and underflow, and saturate once the uint8_t reaches the maximum (255):
// future increment and decrement will not change the value then.
// We purposefuly do not expose the uint8_t directly, so that users go through
// Incr/Decr/SetToZero/SetToOne to manipulate it, so that the saturation and
// lack of over/underflow is always respected.
class SaturatedUint8 {
public:
SaturatedUint8() = default;
void Incr() {
if (V8_LIKELY(val != kMax)) {
val++;
}
}
void Decr() {
if (V8_LIKELY(val != 0 && val != kMax)) {
val--;
}
}
void SetToZero() { val = 0; }
void SetToOne() { val = 1; }
bool IsZero() const { return val == 0; }
bool IsOne() const { return val == 1; }
bool IsSaturated() const { return val == kMax; }
uint8_t Get() const { return val; }
SaturatedUint8& operator+=(const SaturatedUint8& other) {
uint32_t sum = val;
sum += other.val;
val = static_cast<uint8_t>(std::min<uint32_t>(sum, kMax));
return *this;
}
static SaturatedUint8 FromSize(size_t value) {
uint8_t val = static_cast<uint8_t>(std::min<size_t>(value, kMax));
return SaturatedUint8{val};
}
private:
explicit SaturatedUint8(uint8_t val) : val(val) {}
uint8_t val = 0;
static constexpr uint8_t kMax = std::numeric_limits<uint8_t>::max();
};
// underlying_operation<> is used to extract the operation type from OpMaskT
// classes used in Operation::Is<> and Operation::TryCast<>.
template <typename T>
struct underlying_operation {
using type = T;
};
template <typename T, uint64_t M, uint64_t V>
struct underlying_operation<OpMaskT<T, M, V>> {
using type = T;
};
template <typename T>
using underlying_operation_t = typename underlying_operation<T>::type;
// Baseclass for all Turboshaft operations.
// The `alignas(OpIndex)` is necessary because it is followed by an array of
// `OpIndex` inputs.
struct alignas(OpIndex) Operation {
struct IdentityMapper {
OpIndex Map(OpIndex index) { return index; }
OptionalOpIndex Map(OptionalOpIndex index) { return index; }
template <size_t N>
base::SmallVector<OpIndex, N> Map(base::Vector<const OpIndex> indices) {
return base::SmallVector<OpIndex, N>{indices};
}
};
const Opcode opcode;
// The number of uses of this operation in the current graph.
// Instead of overflowing, we saturate the value if it reaches the maximum. In
// this case, the true number of uses is unknown.
// We use such a small type to save memory and because nodes with a high
// number of uses are rare. Additionally, we usually only care if the number
// of uses is 0, 1 or bigger than 1.
SaturatedUint8 saturated_use_count;
const uint16_t input_count;
// The inputs are stored adjacent in memory, right behind the `Operation`
// object.
base::Vector<const OpIndex> inputs() const;
V8_INLINE OpIndex input(size_t i) const { return inputs()[i]; }
static size_t StorageSlotCount(Opcode opcode, size_t input_count);
size_t StorageSlotCount() const {
return StorageSlotCount(opcode, input_count);
}
base::Vector<const RegisterRepresentation> outputs_rep() const;
base::Vector<const MaybeRegisterRepresentation> inputs_rep(
ZoneVector<MaybeRegisterRepresentation>& storage) const;
template <class Op>
bool Is() const {
if constexpr (std::is_base_of_v<Operation, Op>) {
return opcode == Op::opcode;
} else {
// Otherwise this must be OpMaskT.
return IsOpmask<Op>();
}
}
template <class Op>
underlying_operation_t<Op>& Cast() {
DCHECK(Is<Op>());
return *static_cast<underlying_operation_t<Op>*>(this);
}
template <class Op>
const underlying_operation_t<Op>& Cast() const {
DCHECK(Is<Op>());
return *static_cast<const underlying_operation_t<Op>*>(this);
}
template <class Op>
const underlying_operation_t<Op>* TryCast() const {
if (!Is<Op>()) return nullptr;
return static_cast<const underlying_operation_t<Op>*>(this);
}
template <class Op>
underlying_operation_t<Op>* TryCast() {
if (!Is<Op>()) return nullptr;
return static_cast<underlying_operation_t<Op>*>(this);
}
OpEffects Effects() const;
bool IsBlockTerminator() const {
return turboshaft::IsBlockTerminator(opcode);