-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathgraphics_vk_spirv_exec.cpp
More file actions
1995 lines (1941 loc) · 74.1 KB
/
Copy pathgraphics_vk_spirv_exec.cpp
File metadata and controls
1995 lines (1941 loc) · 74.1 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
#include "subsystems/graphics/graphics_vk_spirv.h"
#include "subsystems/graphics/graphics_vk_internal.h"
#include "util/soft_float.h"
// SampleImageRgba8 / QueryImageSize / SamplerAddressModeFor live
// in `duetos::subsystems::graphics::internal` and are declared in
// graphics_vk_internal.h, which is already included above. The
// callers below use fully-qualified names.
/*
* DuetOS — SPIR-V interpreter, execution engine.
*
* Drives a parsed Program's instruction tape one basic block at
* a time. Float math goes through `util::soft_float`. Int math
* runs in native u32 / i32.
*
* SSA values are kept in a per-execution-frame array indexed by
* SPIR-V id. For a 32-bit scalar each id stores 1 Value (4 bytes);
* for vectors and structs we allocate a contiguous run starting at
* a flat heap offset and store the offset in the id table.
*
* Control flow is straight basic-block jumps. Phi is handled by
* recording the predecessor block id before each branch and
* consulting it at the next OpPhi. OpFunctionCall is a real call:
* each argument is bound to the matching OpFunctionParameter, the
* callee's basic blocks run to completion on the shared ExecContext
* (SPIR-V ids are module-unique, so the SSA table needs no per-frame
* save/restore beyond the caller's control-flow cursor), and the
* callee's OpReturnValue is copied into the call result. Vulkan
* forbids shader recursion, so each function is live at most once on
* the call stack — no explicit call-stack model is needed. Pointer
* (inout) parameters bind by aliasing the argument's storage; an
* OpAccessChain whose base is itself a pointer parameter is the one
* remaining GAP (see BindParam).
*
* The interpreter has a per-shader instruction budget (`kStepBudget`)
* to bound runaway loops. Exceeding the budget aborts execution
* with a false return; the caller treats this as a draw-no-paint
* regression and falls back to the fixed-function path.
*
* Opcodes recognised (full list in the switch below):
* - Memory: OpLoad, OpStore, OpAccessChain
* - Composite: OpVectorShuffle, OpCompositeConstruct,
* OpCompositeExtract, OpCompositeInsert
* - Arithmetic int: SNegate, IAdd, ISub, IMul, SDiv, UDiv
* - Arithmetic float: FNegate, FAdd, FSub, FMul, FDiv
* - Vector ops: VectorTimesScalar, MatrixTimesVector, Dot
* - Conversion: ConvertFToS, ConvertSToF, ConvertUToF, Bitcast
* - Compare: IEqual, INotEqual, SLessThan, FOrdLessThan
* - Control: Branch, BranchConditional, Phi, Return, ReturnValue,
* LoopMerge / SelectionMerge (no-op markers)
* - Function call: OpFunctionCall (inline)
* - ExtInst GLSL.std.450: Sqrt, FMin, FMax, FClamp, FMix, Step,
* Length, Normalize, Cross, Sin, Cos, Pow
*
* In scope but partial:
* - OpImageSample{Implicit,Explicit}Lod: descriptor fetch via
* `LookupDescriptor(0, 0)` + `SampleImageRgba8`. The addressing
* mode comes from the bound VkSampler's `SamplerRecord` —
* REPEAT / MIRRORED_REPEAT / CLAMP_TO_EDGE / CLAMP_TO_BORDER
* all execute. Explicit LOD operand is parsed but ignored (no
* mipmap chain). Unbound samples return the UV coordinate as
* the "missing texture" diagnostic.
*
* Out of scope for v1 — opcodes that survive parsing but cause
* execution to abort:
* - OpAtomic*, OpControlBarrier, OpMemoryBarrier
* - OpImageRead / OpImageWrite (storage images)
* - OpKill (deferred — frag shaders that discard are rare in
* hello-world cases)
* - OpSwitch (sane shaders rarely emit; deferred)
*/
namespace duetos::subsystems::graphics::spirv
{
namespace
{
using ::duetos::core::Sf32;
using ::duetos::core::Sf32FromBits;
using ::duetos::core::Sf32ToBits;
constexpr u32 kStepBudget = 8192; // max instructions per ExecuteEntryPoint call
constexpr u32 kSsaHeapBytes = 8192;
// Max native recursion depth of OpFunctionCall. Real shader call
// graphs are shallow; this only bounds a malicious self-/mutually-
// recursive module so it can't overflow the kernel stack.
constexpr u32 kMaxCallDepth = 16;
// SPIR-V opcodes the executor switches on. Numbering = SPIRV-Headers.
constexpr u16 kOpExtInst = 12;
constexpr u16 kOpFunctionCall = 57;
// Texture sampling opcodes (Khronos numbering).
constexpr u16 kOpSampledImage = 86;
constexpr u16 kOpImageSampleImplicitLod = 87;
constexpr u16 kOpImageSampleExplicitLod = 88;
constexpr u16 kOpImageFetch = 95;
constexpr u16 kOpImageRead = 98;
constexpr u16 kOpImageWrite = 99;
constexpr u16 kOpImageQuerySize = 104;
constexpr u16 kOpImageQuerySizeLod = 103;
// Boolean + selection opcodes.
constexpr u16 kOpAny = 154;
constexpr u16 kOpAll = 155;
constexpr u16 kOpSelect = 169;
constexpr u16 kOpKill = 252; // fragment discard
[[maybe_unused]] constexpr u16 kOpVariable = 59;
constexpr u16 kOpLoad = 61;
constexpr u16 kOpStore = 62;
constexpr u16 kOpAccessChain = 65;
constexpr u16 kOpVectorExtractDynamic = 77;
constexpr u16 kOpVectorInsertDynamic = 78;
constexpr u16 kOpVectorShuffle = 79;
constexpr u16 kOpCompositeConstruct = 80;
constexpr u16 kOpCompositeExtract = 81;
constexpr u16 kOpCompositeInsert = 82;
constexpr u16 kOpConvertFToU = 109;
constexpr u16 kOpConvertFToS = 110;
constexpr u16 kOpConvertSToF = 111;
constexpr u16 kOpConvertUToF = 112;
constexpr u16 kOpUConvert = 113;
constexpr u16 kOpSConvert = 114;
constexpr u16 kOpFConvert = 115;
constexpr u16 kOpBitcast = 124;
constexpr u16 kOpSNegate = 126;
constexpr u16 kOpFNegate = 127;
constexpr u16 kOpIAdd = 128;
constexpr u16 kOpFAdd = 129;
constexpr u16 kOpISub = 130;
constexpr u16 kOpFSub = 131;
constexpr u16 kOpIMul = 132;
constexpr u16 kOpFMul = 133;
constexpr u16 kOpUDiv = 134;
constexpr u16 kOpSDiv = 135;
constexpr u16 kOpFDiv = 136;
constexpr u16 kOpVectorTimesScalar = 142;
constexpr u16 kOpMatrixTimesVector = 145;
constexpr u16 kOpDot = 148;
constexpr u16 kOpIEqual = 170;
constexpr u16 kOpINotEqual = 171;
constexpr u16 kOpULessThan = 176;
constexpr u16 kOpSLessThan = 177;
constexpr u16 kOpUGreaterThan = 172;
constexpr u16 kOpSGreaterThan = 173;
constexpr u16 kOpULessThanEqual = 178;
constexpr u16 kOpSLessThanEqual = 179;
constexpr u16 kOpUGreaterThanEqual = 174;
constexpr u16 kOpSGreaterThanEqual = 175;
constexpr u16 kOpFOrdEqual = 180;
constexpr u16 kOpFOrdNotEqual = 182;
constexpr u16 kOpFOrdLessThan = 184;
constexpr u16 kOpFOrdGreaterThan = 186;
constexpr u16 kOpFOrdLessThanEqual = 188;
constexpr u16 kOpFOrdGreaterThanEqual = 190;
// Bitwise / logical / shifts.
constexpr u16 kOpShiftRightLogical = 194;
constexpr u16 kOpShiftRightArithmetic = 195;
constexpr u16 kOpShiftLeftLogical = 196;
constexpr u16 kOpBitwiseOr = 197;
constexpr u16 kOpBitwiseXor = 198;
constexpr u16 kOpBitwiseAnd = 199;
constexpr u16 kOpNot = 200; // ~x
constexpr u16 kOpLogicalEqual = 164;
constexpr u16 kOpLogicalNotEqual = 165;
constexpr u16 kOpLogicalOr = 166;
constexpr u16 kOpLogicalAnd = 167;
constexpr u16 kOpLogicalNot = 168;
constexpr u16 kOpUMod = 137;
constexpr u16 kOpSMod = 139;
constexpr u16 kOpSRem = 138;
constexpr u16 kOpFRem = 140;
constexpr u16 kOpFMod = 141;
// Derivative opcodes — meaningful only when a fragment shader runs
// in 2x2-quad scope so finite differences can be measured between
// neighbouring invocations. The serial interpreter executes one
// invocation at a time, so the spec-correct "0" return is what we
// have to give. GAP: real derivatives need 2x2-quad execution.
constexpr u16 kOpDPdx = 207;
constexpr u16 kOpDPdy = 208;
constexpr u16 kOpFwidth = 209;
constexpr u16 kOpDPdxFine = 210;
constexpr u16 kOpDPdyFine = 211;
constexpr u16 kOpFwidthFine = 212;
constexpr u16 kOpDPdxCoarse = 213;
constexpr u16 kOpDPdyCoarse = 214;
constexpr u16 kOpFwidthCoarse = 215;
// Workgroup / memory barriers — serial interpreter has no parallel
// execution so the spec-correct collapse is a no-op. GAP: real
// barriers matter once the executor runs multiple invocations
// concurrently per workgroup.
constexpr u16 kOpControlBarrier = 224;
constexpr u16 kOpMemoryBarrier = 225;
// Atomic ops — serial interpreter has no contention so these
// collapse to plain Load / Store / IAdd on the pointed-to scalar.
// GAP: real atomicity matters once compute dispatch is parallel.
constexpr u16 kOpAtomicLoad = 227;
constexpr u16 kOpAtomicStore = 228;
constexpr u16 kOpAtomicExchange = 229;
constexpr u16 kOpAtomicIIncrement = 232;
constexpr u16 kOpAtomicIDecrement = 233;
constexpr u16 kOpAtomicIAdd = 234;
constexpr u16 kOpAtomicISub = 235;
constexpr u16 kOpAtomicSMin = 236;
constexpr u16 kOpAtomicUMin = 237;
constexpr u16 kOpAtomicSMax = 238;
constexpr u16 kOpAtomicUMax = 239;
constexpr u16 kOpAtomicAnd = 240;
constexpr u16 kOpAtomicOr = 241;
constexpr u16 kOpAtomicXor = 242;
constexpr u16 kOpPhi = 245;
constexpr u16 kOpLoopMerge = 246;
constexpr u16 kOpSelectionMerge = 247;
[[maybe_unused]] constexpr u16 kOpLabel = 248; // labels open basic blocks at parse time, not at exec time
constexpr u16 kOpBranch = 249;
constexpr u16 kOpBranchConditional = 250;
constexpr u16 kOpReturn = 253;
constexpr u16 kOpReturnValue = 254;
// GLSL.std.450 sub-opcodes. Sin/Cos/Pow dispatch through the
// soft-float polynomial approximations in util/soft_float;
// accuracy ~5e-4 max — plenty for shader work.
constexpr u32 kGlslFAbs = 4;
constexpr u32 kGlslSAbs = 5;
constexpr u32 kGlslFloor = 8;
constexpr u32 kGlslCeil = 9;
constexpr u32 kGlslFract = 10;
constexpr u32 kGlslRound = 1;
constexpr u32 kGlslSin = 13;
constexpr u32 kGlslCos = 14;
constexpr u32 kGlslPow = 26;
constexpr u32 kGlslSqrt = 31;
constexpr u32 kGlslFMin = 37;
constexpr u32 kGlslFMax = 40;
constexpr u32 kGlslFClamp = 43;
constexpr u32 kGlslFMix = 46;
constexpr u32 kGlslStep = 48;
constexpr u32 kGlslLength = 66;
constexpr u32 kGlslCross = 68;
constexpr u32 kGlslNormalize = 69;
// Per-invocation SSA state. Stored on the stack of
// `ExecuteEntryPoint`; the heap is a flat byte buffer indexed by
// `ssa_offset[id]` for composite values; for scalar ids the
// value fits in `ssa_value[id].bits`.
struct ExecContext
{
Program* prog;
Value scalar[kMaxIds];
u32 composite_offset[kMaxIds];
u8 heap[kSsaHeapBytes];
u32 heap_used;
u32 type_of[kMaxIds]; // type_id per result-id; cached at first def
u32 prev_block_label; // for Phi resolution
u32 cur_block_label;
u32 jump_target; // 0 = no jump
bool returned;
// True iff the shader hit OpKill. Distinct from `returned`
// because the rasterizer needs to know whether the per-pixel
// colour write should be SKIPPED (kill) versus written normally
// (clean return). Sticky across function calls within a single
// ExecuteEntryPoint — once a fragment kills itself it stays
// killed for the rest of this invocation.
bool killed;
u32 step_count;
// Set by OpReturnValue to the operand id of the returned value;
// read by an OpFunctionCall caller to copy the callee's result
// into the call's result id. Zero for void returns / no call in
// flight. A single slot suffices because ExecuteCallee saves and
// restores it around each nested call, so even a (bounded —
// see call_depth) recursive call graph never clobbers a caller's
// pending value.
u32 return_value_id;
// Native recursion depth of the SPIR-V function-call interpreter.
// Vulkan forbids shader recursion, but an untrusted module can
// still encode a self-calling function; without this cap that
// recurses ExecuteCallee->ExecuteBlock->ExecuteCallee until the
// kernel stack overflows (the per-instruction kStepBudget bounds
// total work, NOT native stack depth). Capped in ExecuteCallee.
u32 call_depth;
};
const TypeRecord* TypeOf(const Program* p, u32 type_id)
{
if (type_id == 0 || type_id >= kMaxIds || p->id_kinds[type_id] != IdKind::Type)
return nullptr;
return &p->types[p->id_to_index[type_id]];
}
// Decompose any composite type into its scalar-component count
// (vec3 = 3, mat4 = 16, struct of {float, vec3} = 4). Used by
// the heap allocator and by extract/insert.
u32 ComponentCount(const Program* p, u32 type_id)
{
const TypeRecord* t = TypeOf(p, type_id);
if (t == nullptr)
return 0;
switch (t->kind)
{
case TypeKind::Void:
return 0;
case TypeKind::Bool:
case TypeKind::Int:
case TypeKind::Float:
return 1;
case TypeKind::Vector:
return t->component_count;
case TypeKind::Matrix:
case TypeKind::Array:
return ComponentCount(p, t->component_id) * t->component_count;
case TypeKind::Struct:
{
u32 sum = 0;
for (u32 i = 0; i < t->member_count; ++i)
sum += ComponentCount(p, t->members[i]);
return sum;
}
case TypeKind::Pointer:
case TypeKind::Function:
case TypeKind::Image:
case TypeKind::Sampler:
case TypeKind::SampledImage:
return 1;
}
return 0;
}
bool AllocComposite(ExecContext& ec, u32 id, u32 type_id, u32* out_offset, u32* out_count)
{
// `id` is a SPIR-V result id taken raw from the untrusted module
// (the parser does not clamp it). Bound it before indexing the
// fixed [kMaxIds] tables — an out-of-range id is a guest-driven
// OOB write into the static ExecContext otherwise.
if (id == 0 || id >= kMaxIds)
return false;
const u32 n = ComponentCount(ec.prog, type_id);
if (n == 0)
return false;
const u32 bytes = n * 4u;
if (ec.heap_used + bytes > kSsaHeapBytes)
return false;
*out_offset = ec.heap_used;
*out_count = n;
ec.heap_used += bytes;
ec.composite_offset[id] = *out_offset + 1u; // bias so 0 = unset
ec.type_of[id] = type_id;
return true;
}
bool IsComposite(const ExecContext& ec, u32 id)
{
if (id == 0 || id >= kMaxIds)
return false;
return ec.composite_offset[id] != 0u;
}
u32* CompositeData(ExecContext& ec, u32 id)
{
if (!IsComposite(ec, id))
return nullptr;
const u32 offset = ec.composite_offset[id] - 1u;
return reinterpret_cast<u32*>(&ec.heap[offset]);
}
const u32* CompositeDataC(const ExecContext& ec, u32 id)
{
if (!IsComposite(ec, id))
return nullptr;
const u32 offset = ec.composite_offset[id] - 1u;
return reinterpret_cast<const u32*>(&ec.heap[offset]);
}
void SetScalar(ExecContext& ec, u32 id, u32 type_id, u32 bits)
{
// `id` is a guest-supplied result/pointer id; reject out-of-range
// before writing the [kMaxIds] tables (see AllocComposite).
if (id == 0 || id >= kMaxIds)
return;
ec.scalar[id].bits = bits;
ec.composite_offset[id] = 0u;
ec.type_of[id] = type_id;
}
u32 GetScalarBits(const ExecContext& ec, u32 id)
{
if (id == 0 || id >= kMaxIds)
return 0;
if (ec.prog->id_kinds[id] == IdKind::Constant)
return ec.prog->constants[ec.prog->id_to_index[id]].components[0].bits;
return ec.scalar[id].bits;
}
// Read a scalar or composite source id into a flat u32 buffer of
// `count_words` 4-byte components. Returns the number of words
// actually written. Used by binary ops that need to handle scalar
// or vector operands uniformly.
u32 LoadOperandComponents(const ExecContext& ec, u32 id, u32* out, u32 cap)
{
if (id == 0 || id >= kMaxIds || cap == 0)
return 0;
if (ec.prog->id_kinds[id] == IdKind::Constant)
{
const ConstantRecord& c = ec.prog->constants[ec.prog->id_to_index[id]];
const u32 n = (c.component_count < cap) ? c.component_count : cap;
for (u32 i = 0; i < n; ++i)
out[i] = c.components[i].bits;
return n;
}
if (IsComposite(ec, id))
{
const u32* src = CompositeDataC(ec, id);
const u32 type_id = ec.type_of[id];
const u32 n = ComponentCount(ec.prog, type_id);
const u32 m = (n < cap) ? n : cap;
for (u32 i = 0; i < m; ++i)
out[i] = src[i];
return m;
}
out[0] = ec.scalar[id].bits;
return 1;
}
// Store `count_words` components into an SSA result. If count==1
// the result is a scalar; else a composite.
void StoreResultComponents(ExecContext& ec, u32 id, u32 type_id, const u32* in, u32 count)
{
if (count == 0)
return;
if (count == 1)
{
SetScalar(ec, id, type_id, in[0]);
return;
}
u32 offset = 0;
u32 actual_count = 0;
if (!AllocComposite(ec, id, type_id, &offset, &actual_count))
return;
u32* dst = CompositeData(ec, id);
if (dst == nullptr)
return;
const u32 n = (count < actual_count) ? count : actual_count;
for (u32 i = 0; i < n; ++i)
dst[i] = in[i];
}
// --------------------------------------------------------------
// Op handlers — small and uniform. Caller has already pre-fetched
// the operand window pointer + word count.
// --------------------------------------------------------------
void DoBinaryIntOp(ExecContext& ec, u16 op, u32 type_id, u32 result_id, u32 a_id, u32 b_id)
{
u32 a[16]{}, b[16]{}, r[16]{};
const u32 n = LoadOperandComponents(ec, a_id, a, 16);
LoadOperandComponents(ec, b_id, b, 16);
for (u32 i = 0; i < n; ++i)
{
const i32 ai = static_cast<i32>(a[i]);
const i32 bi = static_cast<i32>(b[i]);
switch (op)
{
case kOpIAdd:
r[i] = static_cast<u32>(ai + bi);
break;
case kOpISub:
r[i] = static_cast<u32>(ai - bi);
break;
case kOpIMul:
r[i] = static_cast<u32>(ai * bi);
break;
case kOpSDiv:
r[i] = (bi == 0) ? 0u : static_cast<u32>(ai / bi);
break;
case kOpUDiv:
r[i] = (b[i] == 0) ? 0u : (a[i] / b[i]);
break;
case kOpUMod:
r[i] = (b[i] == 0) ? 0u : (a[i] % b[i]);
break;
case kOpSMod:
{
if (bi == 0)
{
r[i] = 0;
break;
}
// GLSL `mod` semantics: result has same sign as divisor.
const i32 q = ai % bi;
const i32 m = ((q != 0) && ((q < 0) != (bi < 0))) ? q + bi : q;
r[i] = static_cast<u32>(m);
break;
}
case kOpSRem:
r[i] = (bi == 0) ? 0u : static_cast<u32>(ai % bi); // C remainder semantics
break;
case kOpSNegate:
r[i] = static_cast<u32>(-ai);
break;
case kOpNot:
r[i] = ~a[i];
break;
case kOpBitwiseAnd:
r[i] = a[i] & b[i];
break;
case kOpBitwiseOr:
r[i] = a[i] | b[i];
break;
case kOpBitwiseXor:
r[i] = a[i] ^ b[i];
break;
case kOpShiftLeftLogical:
r[i] = (b[i] >= 32u) ? 0u : (a[i] << b[i]);
break;
case kOpShiftRightLogical:
r[i] = (b[i] >= 32u) ? 0u : (a[i] >> b[i]);
break;
case kOpShiftRightArithmetic:
r[i] = (b[i] >= 32u) ? (ai < 0 ? 0xFFFFFFFFu : 0u) : static_cast<u32>(ai >> b[i]);
break;
case kOpLogicalEqual:
r[i] = ((a[i] != 0) == (b[i] != 0)) ? 1u : 0u;
break;
case kOpLogicalNotEqual:
r[i] = ((a[i] != 0) != (b[i] != 0)) ? 1u : 0u;
break;
case kOpLogicalAnd:
r[i] = ((a[i] != 0) && (b[i] != 0)) ? 1u : 0u;
break;
case kOpLogicalOr:
r[i] = ((a[i] != 0) || (b[i] != 0)) ? 1u : 0u;
break;
case kOpLogicalNot:
r[i] = (a[i] == 0) ? 1u : 0u;
break;
case kOpIEqual:
r[i] = (a[i] == b[i]) ? 1u : 0u;
break;
case kOpINotEqual:
r[i] = (a[i] != b[i]) ? 1u : 0u;
break;
case kOpULessThan:
r[i] = (a[i] < b[i]) ? 1u : 0u;
break;
case kOpSLessThan:
r[i] = (ai < bi) ? 1u : 0u;
break;
case kOpUGreaterThan:
r[i] = (a[i] > b[i]) ? 1u : 0u;
break;
case kOpSGreaterThan:
r[i] = (ai > bi) ? 1u : 0u;
break;
case kOpULessThanEqual:
r[i] = (a[i] <= b[i]) ? 1u : 0u;
break;
case kOpSLessThanEqual:
r[i] = (ai <= bi) ? 1u : 0u;
break;
case kOpUGreaterThanEqual:
r[i] = (a[i] >= b[i]) ? 1u : 0u;
break;
case kOpSGreaterThanEqual:
r[i] = (ai >= bi) ? 1u : 0u;
break;
default:
r[i] = 0;
break;
}
}
StoreResultComponents(ec, result_id, type_id, r, n);
}
void DoBinaryFloatOp(ExecContext& ec, u16 op, u32 type_id, u32 result_id, u32 a_id, u32 b_id)
{
u32 a[16]{}, b[16]{}, r[16]{};
const u32 n = LoadOperandComponents(ec, a_id, a, 16);
LoadOperandComponents(ec, b_id, b, 16);
for (u32 i = 0; i < n; ++i)
{
const Sf32 af = Sf32FromBits(a[i]);
const Sf32 bf = Sf32FromBits(b[i]);
Sf32 rf{0};
switch (op)
{
case kOpFAdd:
rf = ::duetos::core::Sf32Add(af, bf);
break;
case kOpFSub:
rf = ::duetos::core::Sf32Sub(af, bf);
break;
case kOpFMul:
rf = ::duetos::core::Sf32Mul(af, bf);
break;
case kOpFDiv:
rf = ::duetos::core::Sf32Div(af, bf);
break;
case kOpFRem:
case kOpFMod:
{
// FRem: result has same sign as dividend (a - trunc(a/b)*b).
// FMod: result has same sign as divisor (a - floor(a/b)*b).
// v0 collapses both to a - trunc(a/b)*b for FRem and
// adjusts for FMod when signs differ; no GLSL.std.450
// dependency.
if (::duetos::core::Sf32IsZero(bf))
{
rf = ::duetos::core::Sf32Zero();
break;
}
const Sf32 quot = ::duetos::core::Sf32Div(af, bf);
const i32 tq = ::duetos::core::Sf32ToI32(quot);
const Sf32 trunc_q = ::duetos::core::Sf32FromI32(tq);
Sf32 rem = ::duetos::core::Sf32Sub(af, ::duetos::core::Sf32Mul(trunc_q, bf));
if (op == kOpFMod && !::duetos::core::Sf32IsZero(rem) &&
::duetos::core::Sf32IsNegative(rem) != ::duetos::core::Sf32IsNegative(bf))
rem = ::duetos::core::Sf32Add(rem, bf);
rf = rem;
break;
}
case kOpFNegate:
rf = ::duetos::core::Sf32Neg(af);
break;
case kOpFOrdLessThan:
r[i] = ::duetos::core::Sf32LessThan(af, bf) ? 1u : 0u;
continue;
case kOpFOrdGreaterThan:
r[i] = ::duetos::core::Sf32GreaterThan(af, bf) ? 1u : 0u;
continue;
case kOpFOrdLessThanEqual:
r[i] = ::duetos::core::Sf32LessOrEqual(af, bf) ? 1u : 0u;
continue;
case kOpFOrdGreaterThanEqual:
r[i] = ::duetos::core::Sf32GreaterOrEqual(af, bf) ? 1u : 0u;
continue;
case kOpFOrdEqual:
r[i] = ::duetos::core::Sf32Equal(af, bf) ? 1u : 0u;
continue;
case kOpFOrdNotEqual:
r[i] = ::duetos::core::Sf32NotEqual(af, bf) ? 1u : 0u;
continue;
default:
break;
}
r[i] = Sf32ToBits(rf);
}
StoreResultComponents(ec, result_id, type_id, r, n);
}
void DoLoad(ExecContext& ec, u32 type_id, u32 result_id, u32 ptr_id)
{
// `ptr_id` is a raw operand from the untrusted module; bound it
// before indexing p->id_kinds[kMaxIds].
if (ptr_id == 0 || ptr_id >= kMaxIds)
return;
// Pointer is either an OpVariable id (direct) or an
// OpAccessChain result (we record the resolved storage offset
// there). For variables we read from the storage heap; for
// access-chain we read from the offset stored in ssa_value.
const Program* p = ec.prog;
u32 src_bytes_offset = 0;
const u8* src_base = nullptr;
if (p->id_kinds[ptr_id] == IdKind::Variable)
{
const VariableRecord& v = p->variables[p->id_to_index[ptr_id]];
switch (v.storage)
{
case StorageClass::Input:
src_base = p->input.bytes;
break;
case StorageClass::Output:
src_base = p->output.bytes;
break;
case StorageClass::UniformConstant:
src_base = p->uniform_constant.bytes;
break;
case StorageClass::Uniform:
src_base = p->uniform.bytes;
break;
case StorageClass::PushConstant:
src_base = p->push_constant.bytes;
break;
default:
src_base = p->private_storage.bytes;
break;
}
src_bytes_offset = v.storage_offset;
}
else
{
// AccessChain stashes (storage_class<<24 | offset) in the
// scalar value; resolve back via the high byte.
const u32 packed = ec.scalar[ptr_id].bits;
const u32 sc = (packed >> 24) & 0xFFu;
src_bytes_offset = packed & 0x00FFFFFFu;
switch (static_cast<StorageClass>(sc))
{
case StorageClass::Input:
src_base = p->input.bytes;
break;
case StorageClass::Output:
src_base = p->output.bytes;
break;
case StorageClass::UniformConstant:
src_base = p->uniform_constant.bytes;
break;
case StorageClass::Uniform:
src_base = p->uniform.bytes;
break;
case StorageClass::PushConstant:
src_base = p->push_constant.bytes;
break;
default:
src_base = p->private_storage.bytes;
break;
}
}
const u32 n = ComponentCount(p, type_id);
u32 buf[16]{};
for (u32 i = 0; i < n && i < 16; ++i)
{
const u32 b = src_bytes_offset + i * 4u;
if (b + 4u > kMaxStorageBytes)
break;
buf[i] = (static_cast<u32>(src_base[b]) | (static_cast<u32>(src_base[b + 1]) << 8) |
(static_cast<u32>(src_base[b + 2]) << 16) | (static_cast<u32>(src_base[b + 3]) << 24));
}
StoreResultComponents(ec, result_id, type_id, buf, n);
}
void DoStore(ExecContext& ec, u32 ptr_id, u32 value_id)
{
// `ptr_id` is a raw operand from the untrusted module; bound it
// before indexing p->id_kinds[kMaxIds].
if (ptr_id == 0 || ptr_id >= kMaxIds)
return;
Program* p = ec.prog;
u32 dst_bytes_offset = 0;
u8* dst_base = nullptr;
if (p->id_kinds[ptr_id] == IdKind::Variable)
{
VariableRecord& v = p->variables[p->id_to_index[ptr_id]];
switch (v.storage)
{
case StorageClass::Input:
dst_base = p->input.bytes;
break;
case StorageClass::Output:
dst_base = p->output.bytes;
break;
case StorageClass::UniformConstant:
dst_base = p->uniform_constant.bytes;
break;
case StorageClass::Uniform:
dst_base = p->uniform.bytes;
break;
case StorageClass::PushConstant:
dst_base = p->push_constant.bytes;
break;
default:
dst_base = p->private_storage.bytes;
break;
}
dst_bytes_offset = v.storage_offset;
}
else
{
const u32 packed = ec.scalar[ptr_id].bits;
const u32 sc = (packed >> 24) & 0xFFu;
dst_bytes_offset = packed & 0x00FFFFFFu;
switch (static_cast<StorageClass>(sc))
{
case StorageClass::Input:
dst_base = p->input.bytes;
break;
case StorageClass::Output:
dst_base = p->output.bytes;
break;
default:
dst_base = p->private_storage.bytes;
break;
}
}
u32 buf[16]{};
const u32 n = LoadOperandComponents(ec, value_id, buf, 16);
for (u32 i = 0; i < n; ++i)
{
const u32 b = dst_bytes_offset + i * 4u;
if (b + 4u > kMaxStorageBytes)
break;
dst_base[b + 0] = static_cast<u8>(buf[i] & 0xFFu);
dst_base[b + 1] = static_cast<u8>((buf[i] >> 8) & 0xFFu);
dst_base[b + 2] = static_cast<u8>((buf[i] >> 16) & 0xFFu);
dst_base[b + 3] = static_cast<u8>((buf[i] >> 24) & 0xFFu);
}
}
void DoAccessChain(ExecContext& ec, u32 type_id, u32 result_id, u32 base_ptr_id, const u32* idx_ids, u32 idx_count)
{
// Resolve a pointer to a base variable + chain of index ids
// (each pointing at an OpConstant of int type) into a byte
// offset within the variable's storage backing. Packs the
// result as (storage_class<<24 | byte_offset) into the scalar
// slot so subsequent Load / Store can unpack it without
// touching the pointer type system.
(void)type_id;
Program* p = ec.prog;
// `base_ptr_id` is a raw operand from the untrusted module; bound
// it before indexing p->id_kinds[kMaxIds].
if (base_ptr_id == 0 || base_ptr_id >= kMaxIds)
return;
if (p->id_kinds[base_ptr_id] != IdKind::Variable)
return;
const VariableRecord& v = p->variables[p->id_to_index[base_ptr_id]];
u32 offset = v.storage_offset;
u32 cur_type_id = v.type_id;
// Strip the outer Pointer.
if (cur_type_id < kMaxIds && p->id_kinds[cur_type_id] == IdKind::Type)
{
const TypeRecord& tr = p->types[p->id_to_index[cur_type_id]];
if (tr.kind == TypeKind::Pointer)
cur_type_id = tr.component_id;
}
for (u32 k = 0; k < idx_count; ++k)
{
const TypeRecord* ct = TypeOf(p, cur_type_id);
if (ct == nullptr)
break;
const u32 idx_id = idx_ids[k];
u32 idx = 0;
if (idx_id < kMaxIds && p->id_kinds[idx_id] == IdKind::Constant)
idx = p->constants[p->id_to_index[idx_id]].components[0].bits;
else if (idx_id < kMaxIds)
idx = ec.scalar[idx_id].bits;
switch (ct->kind)
{
case TypeKind::Struct:
{
if (idx >= ct->member_count)
return;
offset += ct->member_offsets[idx];
cur_type_id = ct->members[idx];
break;
}
case TypeKind::Vector:
case TypeKind::Array:
{
offset += idx * 4u; // 32-bit components
cur_type_id = ct->component_id;
break;
}
case TypeKind::Matrix:
{
const TypeRecord* col = TypeOf(p, ct->component_id);
const u32 col_size = (col != nullptr) ? col->component_count * 4u : 16u;
offset += idx * col_size;
cur_type_id = ct->component_id;
break;
}
default:
return;
}
}
const u32 packed = (static_cast<u32>(v.storage) << 24) | (offset & 0x00FFFFFFu);
SetScalar(ec, result_id, type_id, packed);
}
void DoCompositeExtract(ExecContext& ec, u32 type_id, u32 result_id, u32 composite_id, const u32* idx_lits,
u32 idx_count)
{
u32 buf[16]{};
const u32 n = LoadOperandComponents(ec, composite_id, buf, 16);
if (idx_count == 0 || idx_lits[0] >= n)
{
SetScalar(ec, result_id, type_id, 0u);
return;
}
// v1 supports a single-level extract (most shaders only fetch
// one scalar from a vec). Nested composite extracts walk
// additional indices in idx_lits[1..] and need a richer model
// — not in v1.
SetScalar(ec, result_id, type_id, buf[idx_lits[0]]);
}
void DoCompositeConstruct(ExecContext& ec, u32 type_id, u32 result_id, const u32* operand_ids, u32 operand_count)
{
u32 buf[16]{};
u32 cursor = 0;
for (u32 i = 0; i < operand_count && cursor < 16; ++i)
{
u32 sub[16]{};
const u32 m = LoadOperandComponents(ec, operand_ids[i], sub, 16);
for (u32 j = 0; j < m && cursor < 16; ++j)
buf[cursor++] = sub[j];
}
StoreResultComponents(ec, result_id, type_id, buf, cursor);
}
void DoVectorShuffle(ExecContext& ec, u32 type_id, u32 result_id, u32 v1_id, u32 v2_id, const u32* idx_lits,
u32 idx_count)
{
u32 a[16]{}, b[16]{}, r[16]{};
const u32 n1 = LoadOperandComponents(ec, v1_id, a, 16);
LoadOperandComponents(ec, v2_id, b, 16);
const u32 n = (idx_count < 16) ? idx_count : 16;
for (u32 i = 0; i < n; ++i)
{
const u32 idx = idx_lits[i];
if (idx == 0xFFFFFFFFu)
r[i] = 0;
else if (idx < n1)
r[i] = a[idx];
else
r[i] = b[idx - n1];
}
StoreResultComponents(ec, result_id, type_id, r, n);
}
void DoVectorTimesScalar(ExecContext& ec, u32 type_id, u32 result_id, u32 vec_id, u32 scalar_id)
{
u32 v[16]{}, r[16]{};
const u32 n = LoadOperandComponents(ec, vec_id, v, 16);
u32 s_bits = GetScalarBits(ec, scalar_id);
const Sf32 s = Sf32FromBits(s_bits);
for (u32 i = 0; i < n; ++i)
r[i] = Sf32ToBits(::duetos::core::Sf32Mul(Sf32FromBits(v[i]), s));
StoreResultComponents(ec, result_id, type_id, r, n);
}
void DoMatrixTimesVector(ExecContext& ec, u32 type_id, u32 result_id, u32 mat_id, u32 vec_id)
{
// Column-major matrix: mat[col][row]. Each column is a vector
// of `rows` floats. Result = sum_over_cols(mat[col] *
// vec[col]). v1 supports any (rows, cols) up to (4, 4).
u32 m_data[16]{};
u32 v_data[4]{};
const u32 m_n = LoadOperandComponents(ec, mat_id, m_data, 16);
const u32 v_n = LoadOperandComponents(ec, vec_id, v_data, 4);
if (v_n == 0 || m_n == 0)
return;
const u32 cols = v_n;
const u32 rows = m_n / cols;
u32 r[4]{};
for (u32 row = 0; row < rows && row < 4; ++row)
{
Sf32 acc{0};
for (u32 col = 0; col < cols && col < 4; ++col)
{
const Sf32 mij = Sf32FromBits(m_data[col * rows + row]);
const Sf32 vj = Sf32FromBits(v_data[col]);
acc = ::duetos::core::Sf32Add(acc, ::duetos::core::Sf32Mul(mij, vj));
}
r[row] = Sf32ToBits(acc);
}
StoreResultComponents(ec, result_id, type_id, r, rows);
}
void DoDot(ExecContext& ec, u32 type_id, u32 result_id, u32 a_id, u32 b_id)
{
u32 a[16]{}, b[16]{};
const u32 n = LoadOperandComponents(ec, a_id, a, 16);
LoadOperandComponents(ec, b_id, b, 16);
Sf32 acc{0};
for (u32 i = 0; i < n; ++i)
acc = ::duetos::core::Sf32Add(acc, ::duetos::core::Sf32Mul(Sf32FromBits(a[i]), Sf32FromBits(b[i])));
SetScalar(ec, result_id, type_id, Sf32ToBits(acc));
}
void DoExtInst(ExecContext& ec, u32 type_id, u32 result_id, u32 sub_op, const u32* arg_ids, u32 arg_count)
{
u32 a[16]{}, b[16]{}, c[16]{}, r[16]{};
const u32 n = (arg_count > 0) ? LoadOperandComponents(ec, arg_ids[0], a, 16) : 0;
const u32 n2 = (arg_count > 1) ? LoadOperandComponents(ec, arg_ids[1], b, 16) : 0;
const u32 n3 = (arg_count > 2) ? LoadOperandComponents(ec, arg_ids[2], c, 16) : 0;
(void)n2;
(void)n3;
switch (sub_op)
{
case kGlslSqrt:
for (u32 i = 0; i < n; ++i)
r[i] = Sf32ToBits(::duetos::core::Sf32Sqrt(Sf32FromBits(a[i])));
StoreResultComponents(ec, result_id, type_id, r, n);
break;
case kGlslFAbs:
for (u32 i = 0; i < n; ++i)
r[i] = Sf32ToBits(::duetos::core::Sf32Abs(Sf32FromBits(a[i])));
StoreResultComponents(ec, result_id, type_id, r, n);
break;
case kGlslSAbs:
for (u32 i = 0; i < n; ++i)
{
const i32 v = static_cast<i32>(a[i]);
r[i] = static_cast<u32>(v < 0 ? -v : v);
}
StoreResultComponents(ec, result_id, type_id, r, n);
break;
case kGlslFloor:
for (u32 i = 0; i < n; ++i)
r[i] = Sf32ToBits(::duetos::core::Sf32Floor(Sf32FromBits(a[i])));
StoreResultComponents(ec, result_id, type_id, r, n);