-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRecompilerContract.cs
More file actions
776 lines (705 loc) · 30.4 KB
/
Copy pathRecompilerContract.cs
File metadata and controls
776 lines (705 loc) · 30.4 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
using System.Collections.ObjectModel;
using PSXRecomp.Architecture;
using PSXRecomp.Core.DiscImage.AnalysisArtifacts;
namespace PSXRecomp.Core.Recompiler;
[Domain]
public enum RecompilerIrOperationKind : byte
{
Nop,
Constant,
ReadGpr,
WriteGpr,
Add,
Subtract,
And,
Or,
Xor,
Nor,
ShiftLeftLogical,
ShiftRightLogical,
ShiftRightArithmetic,
/// <summary>
/// Reads 8 bits from the guest 32-bit address in input A and produces them
/// zero-extended into the 32-bit result. Signedness is not part of the
/// operation: a sign-extending guest load is expressed by the lowering as a
/// <see cref="ShiftLeftLogical"/> / <see cref="ShiftRightArithmetic"/> pair.
/// </summary>
Load8,
/// <summary>Reads 16 bits from the address in input A, zero-extended (see <see cref="Load8"/>).</summary>
Load16,
/// <summary>Reads 32 bits from the guest 32-bit address in input A.</summary>
Load32,
/// <summary>
/// Writes the low 8 bits of the value in input B to the guest 32-bit address
/// in input A, and produces no result.
/// </summary>
Store8,
/// <summary>Writes the low 16 bits of input B to the address in input A.</summary>
Store16,
/// <summary>Writes the 32-bit value in input B to the address in input A.</summary>
Store32,
/// <summary>Produces 1 when inputs A and B are equal, otherwise 0.</summary>
CompareEqual,
/// <summary>Produces 1 when inputs A and B differ, otherwise 0.</summary>
CompareNotEqual,
/// <summary>Produces 1 when the signed (32-bit two's-complement) value of input A
/// is less than the signed value of input B, otherwise 0.</summary>
CompareLessThanSigned,
/// <summary>Produces 1 when the unsigned value of input A is less than the
/// unsigned value of input B, otherwise 0.</summary>
CompareLessThanUnsigned,
}
[Domain]
public enum RecompilerIrTerminationReason : byte
{
Success,
UnsupportedInstruction,
UnsupportedIr,
UnsupportedMemory,
UnsupportedMmio,
UnresolvedIndirectFlow,
Exception,
ExecutionBudgetExceeded,
GenerationFailure,
HostCompilerFailure,
StateMismatch,
}
[Domain]
public enum RecompilerIrDiagnosticCode : byte
{
InvalidRegister,
InvalidOperationShape,
MissingOperand,
InvalidOperandWidth,
IllegalTermination,
ZeroRegisterWrite,
DuplicateBlock,
UnstableBlockOrder,
InvalidFlow,
ReservedFlow,
InvalidMemoryAccess,
InvalidMetadata,
DuplicateFunction,
InvalidFunction,
}
[Domain]
public enum RecompilerMemoryAccessKind : byte
{
Read,
Write,
}
/// <summary>
/// Classifies the guest-memory effect a Load8/16/32 or Store8/16/32 operation's
/// address carries, when that address can be established. This is the IR-level
/// effect contract (Issue #411): it distinguishes an ordinary guest-RAM access
/// from an MMIO/device-visible one so a consumer — validator, codegen, or a
/// future optimizer — never has to guess.
/// </summary>
[Domain]
public enum RecompilerIrMemoryEffectKind : byte
{
/// <summary>
/// The address was not established as ordinary memory or a device register
/// at IR-construction time. This is the default, and it is what every real
/// <see cref="MipsToIrLowerer"/> load/store carries: a MIPS base+offset
/// effective address depends on a guest register value that is only known
/// at execution time, not at lowering time. An unknown effect must never be
/// treated as ordinary — it is not reorderable, not dead-store-eliminable,
/// and not CSE-eligible.
/// </summary>
Unknown = 0,
/// <summary>
/// The address is provably ordinary guest memory (RAM or BIOS ROM, per
/// <see cref="Runtime.Ps1AddressTranslation"/> and
/// <see cref="Dma.Ps1MemoryMap.ClassifyRegion"/>): no device-visible side
/// effect. This does not mean idempotent/pure — an ordinary store still
/// mutates guest state that a later load or aliased store can observe, so
/// normal memory dependencies apply: a load still needs alias-analysis
/// proof before CSE, and a store still needs liveness and alias proof
/// before dead-store elimination or reordering.
/// </summary>
Ordinary = 1,
/// <summary>
/// The address is provably a PS1 hardware/device register (the
/// <see cref="Dma.Ps1MemoryMap.HwRegBase"/>..<see cref="Dma.Ps1MemoryMap.HwRegEnd"/>
/// window). A device read is not idempotent/pure and a device write is not
/// dead-store-eliminable; the relative order of device operations, and of a
/// device operation against any other observable effect, must be preserved.
/// </summary>
Device = 2,
}
[Domain]
public readonly record struct RecompilerIrValue(int Id)
{
public bool IsValid => Id >= 0;
}
[Domain]
public sealed record RecompilerIrOperation
{
public RecompilerIrOperation(
RecompilerIrOperationKind kind,
int resultValueId = -1,
int inputValueA = -1,
int inputValueB = -1,
byte register = 0,
byte shiftAmount = 0,
uint immediate = 0,
RecompilerIrMemoryEffectKind memoryEffect = RecompilerIrMemoryEffectKind.Unknown)
{
Kind = kind;
ResultValueId = resultValueId;
InputValueA = inputValueA;
InputValueB = inputValueB;
Register = register;
ShiftAmount = shiftAmount;
Immediate = immediate;
MemoryEffect = memoryEffect;
}
public RecompilerIrOperationKind Kind { get; }
public int ResultValueId { get; }
public int InputValueA { get; }
public int InputValueB { get; }
public byte Register { get; }
public byte ShiftAmount { get; }
public uint Immediate { get; }
/// <summary>
/// The memory-effect classification for a Load8/16/32 or Store8/16/32
/// operation (see <see cref="RecompilerIrMemoryEffectKind"/>). Meaningless
/// for any other operation kind, which must leave it at its
/// <see cref="RecompilerIrMemoryEffectKind.Unknown"/> default — the
/// validator enforces both.
/// </summary>
public RecompilerIrMemoryEffectKind MemoryEffect { get; }
}
/// <summary>
/// Classifies how control flows from a basic block to its successor(s). The
/// sequential case is the existing "success with a next PC" relation; branch,
/// jump and call make control flow explicit. <see cref="Return"/> remains a
/// reserved extension point and is rejected by the validator: it needs a target
/// held in a register, which <see cref="RecompilerIrFlow.Target"/> — a static
/// address — cannot carry.
/// </summary>
[Domain]
public enum RecompilerIrFlowKind : byte
{
Sequential = 0,
Branch = 1,
Jump = 2,
Call = 3,
Return = 4,
}
/// <summary>
/// The explicit control-flow transition of a block, carried by
/// <see cref="RecompilerIrExit"/> when the block does not simply fall through.
/// <list type="bullet">
/// <item>Branch: condition value id, taken target; the not-taken successor is the
/// exit's next PC.</item>
/// <item>Jump: unconditional target address.</item>
/// <item>Sequential: matches the existing success-with-next-PC relation.</item>
/// <item>Call: unconditional target address of the callee, with the exit's next
/// PC carrying the address control resumes at when the callee returns. The
/// linked return address itself is an architectural GPR write the lowering
/// emits; the flow states the call relation, not the link register.</item>
/// <item>Return: reserved (not yet supported).</item>
/// </list>
/// </summary>
[Domain]
public sealed record RecompilerIrFlow
{
public RecompilerIrFlow(
RecompilerIrFlowKind kind,
uint? target = null,
int conditionValueId = -1)
{
if (!Enum.IsDefined(kind)) throw new ArgumentOutOfRangeException(nameof(kind));
Kind = kind;
Target = target;
ConditionValueId = conditionValueId;
}
public RecompilerIrFlowKind Kind { get; }
public uint? Target { get; }
public int ConditionValueId { get; }
}
[Domain]
public sealed record RecompilerIrExit
{
public RecompilerIrExit(
RecompilerIrTerminationReason reason,
uint? nextPc = null,
RecompilerIrFlow? flow = null)
{
Reason = reason;
NextPc = nextPc;
Flow = flow;
}
public RecompilerIrTerminationReason Reason { get; }
public uint? NextPc { get; }
public RecompilerIrFlow? Flow { get; }
}
[Domain]
public sealed record RecompilerIrBlock
{
public RecompilerIrBlock(uint entryPc, IEnumerable<RecompilerIrOperation> operations, RecompilerIrExit exit)
{
ArgumentNullException.ThrowIfNull(operations);
Exit = exit ?? throw new ArgumentNullException(nameof(exit));
EntryPc = entryPc;
Operations = new ReadOnlyCollection<RecompilerIrOperation>(operations.ToArray());
}
public uint EntryPc { get; }
public IReadOnlyList<RecompilerIrOperation> Operations { get; }
public RecompilerIrExit Exit { get; }
}
/// <summary>
/// A generic, typed key/value metadata slot used to carry PS1/MIPS-specific
/// information (for example endianness, address-space region, or scratchpad base)
/// without leaking that information into the generic IR operation surface. The
/// key is a stable string; exactly one of <see cref="UIntValue"/> or
/// <see cref="StringValue"/> is set.
/// </summary>
[Domain]
public sealed record RecompilerIrMetadataEntry
{
public RecompilerIrMetadataEntry(string key, uint? uintValue = null, string? stringValue = null)
{
if (string.IsNullOrWhiteSpace(key)) throw new ArgumentException("Metadata key must be non-empty.", nameof(key));
if (uintValue is not null && stringValue is not null)
throw new ArgumentException("A metadata entry carries a single typed value, not both.", nameof(key));
if (uintValue is null && stringValue is null)
throw new ArgumentException("A metadata entry requires a value.", nameof(key));
Key = key;
UIntValue = uintValue;
StringValue = stringValue;
}
public string Key { get; }
public uint? UIntValue { get; }
public string? StringValue { get; }
}
/// <summary>
/// A function: an entry address plus the basic blocks reachable from it, and
/// optional PS1/MIPS-scoped metadata. Function blocks are a grouping view over
/// the blocks of a <see cref="RecompilerIrProgram"/>; the program remains the
/// SSOT for block ordering and uniqueness.
/// </summary>
[Domain]
public sealed record RecompilerIrFunction
{
public RecompilerIrFunction(
uint entryPc,
IEnumerable<RecompilerIrBlock> blocks,
IEnumerable<RecompilerIrMetadataEntry>? metadata = null)
{
ArgumentNullException.ThrowIfNull(blocks);
EntryPc = entryPc;
Blocks = new ReadOnlyCollection<RecompilerIrBlock>(blocks.ToArray());
Metadata = new ReadOnlyCollection<RecompilerIrMetadataEntry>((metadata ?? Array.Empty<RecompilerIrMetadataEntry>()).ToArray());
}
public uint EntryPc { get; }
public IReadOnlyList<RecompilerIrBlock> Blocks { get; }
public IReadOnlyList<RecompilerIrMetadataEntry> Metadata { get; }
}
[Domain]
public sealed record RecompilerIrProgram
{
public RecompilerIrProgram(
IEnumerable<RecompilerIrBlock> blocks,
IEnumerable<RecompilerIrFunction>? functions = null)
{
ArgumentNullException.ThrowIfNull(blocks);
Blocks = new ReadOnlyCollection<RecompilerIrBlock>(blocks.OrderBy(block => block.EntryPc).ToArray());
Functions = new ReadOnlyCollection<RecompilerIrFunction>((functions ?? Array.Empty<RecompilerIrFunction>()).OrderBy(function => function.EntryPc).ToArray());
}
public IReadOnlyList<RecompilerIrBlock> Blocks { get; }
public IReadOnlyList<RecompilerIrFunction> Functions { get; }
}
[Domain]
public sealed record RecompilerIrDiagnostic(
RecompilerIrDiagnosticCode Code,
string Message,
int BlockIndex,
int OperationIndex);
[Domain]
public sealed record RecompilerIrValidationResult(IReadOnlyList<RecompilerIrDiagnostic> Diagnostics)
{
public bool IsValid => Diagnostics.Count == 0;
}
[Domain]
public static class RecompilerIrValidator
{
public static RecompilerIrValidationResult Validate(RecompilerIrProgram program)
{
ArgumentNullException.ThrowIfNull(program);
var diagnostics = new List<RecompilerIrDiagnostic>();
uint? previousPc = null;
for (var blockIndex = 0; blockIndex < program.Blocks.Count; blockIndex++)
{
var block = program.Blocks[blockIndex];
if (previousPc == block.EntryPc)
{
Add(diagnostics, RecompilerIrDiagnosticCode.DuplicateBlock, "Block entry PCs must be unique.", blockIndex);
}
else if (previousPc is not null && previousPc > block.EntryPc)
{
Add(diagnostics, RecompilerIrDiagnosticCode.UnstableBlockOrder, "Blocks must be ordered by entry PC.", blockIndex);
}
previousPc = block.EntryPc;
var definedValueIds = new HashSet<int>();
for (var operationIndex = 0; operationIndex < block.Operations.Count; operationIndex++)
{
var operation = block.Operations[operationIndex];
ValidateOperation(operation, diagnostics, blockIndex, operationIndex);
ValidateInput(operation.InputValueA, definedValueIds, diagnostics, blockIndex, operationIndex);
ValidateInput(operation.InputValueB, definedValueIds, diagnostics, blockIndex, operationIndex);
if (operation.ResultValueId >= 0)
{
definedValueIds.Add(operation.ResultValueId);
}
}
ValidateExit(block.Exit, definedValueIds, diagnostics, blockIndex);
}
ValidateFunctions(program, diagnostics);
return new RecompilerIrValidationResult(new ReadOnlyCollection<RecompilerIrDiagnostic>(diagnostics));
}
private static void ValidateExit(RecompilerIrExit exit, HashSet<int> definedValueIds, List<RecompilerIrDiagnostic> diagnostics, int blockIndex)
{
if (!Enum.IsDefined(exit.Reason))
{
Add(diagnostics, RecompilerIrDiagnosticCode.IllegalTermination, "Termination reason must be a defined value.", blockIndex);
return;
}
var flow = exit.Flow;
if (flow is null)
{
if (exit.Reason == RecompilerIrTerminationReason.Success && exit.NextPc is null)
{
Add(diagnostics, RecompilerIrDiagnosticCode.IllegalTermination, "Success exits require a next PC.", blockIndex);
}
else if (exit.Reason != RecompilerIrTerminationReason.Success && exit.NextPc is not null)
{
Add(diagnostics, RecompilerIrDiagnosticCode.IllegalTermination, "Non-success exits must not provide a next PC.", blockIndex);
}
return;
}
if (!Enum.IsDefined(flow.Kind))
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidFlow, "Flow kind must be a defined value.", blockIndex);
return;
}
if (exit.Reason != RecompilerIrTerminationReason.Success)
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidFlow, "A flow is only valid on a success exit.", blockIndex);
return;
}
switch (flow.Kind)
{
case RecompilerIrFlowKind.Sequential:
if (exit.NextPc is null)
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidFlow, "Sequential flow requires a next PC.", blockIndex);
}
if (flow.Target is not null || flow.ConditionValueId >= 0)
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidFlow, "Sequential flow carries no target or condition.", blockIndex);
}
break;
case RecompilerIrFlowKind.Branch:
if (flow.Target is null)
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidFlow, "Branch flow requires a taken target.", blockIndex);
}
if (flow.ConditionValueId < 0)
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidFlow, "Branch flow requires a condition value.", blockIndex);
}
else if (!definedValueIds.Contains(flow.ConditionValueId))
{
Add(diagnostics, RecompilerIrDiagnosticCode.MissingOperand, "Branch condition value must be defined by an earlier operation in the block.", blockIndex);
}
if (exit.NextPc is null)
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidFlow, "Branch flow requires a fall-through next PC.", blockIndex);
}
break;
case RecompilerIrFlowKind.Jump:
if (flow.Target is null)
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidFlow, "Jump flow requires a target.", blockIndex);
}
if (flow.ConditionValueId >= 0)
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidFlow, "Jump flow carries no condition.", blockIndex);
}
if (exit.NextPc is not null)
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidFlow, "Jump flow must not provide a next PC.", blockIndex);
}
break;
case RecompilerIrFlowKind.Call:
if (flow.Target is null)
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidFlow, "Call flow requires a callee target.", blockIndex);
}
if (flow.ConditionValueId >= 0)
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidFlow, "Call flow carries no condition.", blockIndex);
}
if (exit.NextPc is null)
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidFlow, "Call flow requires the return-address next PC.", blockIndex);
}
break;
case RecompilerIrFlowKind.Return:
Add(diagnostics, RecompilerIrDiagnosticCode.ReservedFlow, $"Flow kind '{flow.Kind}' is reserved and not yet supported.", blockIndex);
break;
default:
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidFlow, "Flow kind must be a defined value.", blockIndex);
break;
}
}
private static void ValidateFunctions(RecompilerIrProgram program, List<RecompilerIrDiagnostic> diagnostics)
{
var blockPcs = program.Blocks.Select(block => block.EntryPc).ToHashSet();
var seenFunctions = new HashSet<uint>();
foreach (var function in program.Functions)
{
if (!seenFunctions.Add(function.EntryPc))
{
Add(diagnostics, RecompilerIrDiagnosticCode.DuplicateFunction, "Function entry PCs must be unique.", -1);
continue;
}
if (!blockPcs.Contains(function.EntryPc))
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidFunction, "Function entry PC must reference a block in the program.", -1);
continue;
}
foreach (var block in function.Blocks)
{
if (!blockPcs.Contains(block.EntryPc))
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidFunction, "A function block must exist in the program.", -1);
}
}
foreach (var entry in function.Metadata)
{
if (string.IsNullOrWhiteSpace(entry.Key))
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidMetadata, "Metadata keys must be non-empty.", -1);
}
}
}
}
private static void ValidateOperation(RecompilerIrOperation operation, List<RecompilerIrDiagnostic> diagnostics, int blockIndex, int operationIndex)
{
if (operation.Register > 31)
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidRegister, "GPR number must be within [0, 31].", blockIndex, operationIndex);
}
var hasResult = operation.ResultValueId >= 0;
var hasA = operation.InputValueA >= 0;
var hasB = operation.InputValueB >= 0;
if (!Enum.IsDefined(operation.Kind))
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidOperationShape, "Operation kind must be a defined value.", blockIndex, operationIndex);
return;
}
if (operation.ResultValueId < -1 || operation.InputValueA < -1 || operation.InputValueB < -1)
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidOperandWidth, "Value IDs must be -1 or non-negative.", blockIndex, operationIndex);
}
switch (operation.Kind)
{
case RecompilerIrOperationKind.Nop:
Require(!hasResult && !hasA && !hasB, diagnostics, blockIndex, operationIndex);
break;
case RecompilerIrOperationKind.Constant:
case RecompilerIrOperationKind.ReadGpr:
Require(hasResult && !hasA && !hasB, diagnostics, blockIndex, operationIndex);
break;
case RecompilerIrOperationKind.WriteGpr:
Require(!hasResult && hasA && !hasB, diagnostics, blockIndex, operationIndex);
if (operation.Register == 0)
{
Add(diagnostics, RecompilerIrDiagnosticCode.ZeroRegisterWrite, "GPR[0] is immutable and cannot be written.", blockIndex, operationIndex);
}
break;
case RecompilerIrOperationKind.Load8:
case RecompilerIrOperationKind.Load16:
case RecompilerIrOperationKind.Load32:
Require(hasResult && hasA && !hasB, diagnostics, blockIndex, operationIndex);
if (operation.Register != 0 || operation.ShiftAmount != 0)
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidMemoryAccess, "Load operations must not carry a register or shift amount.", blockIndex, operationIndex);
}
ValidateMemoryEffect(operation, diagnostics, blockIndex, operationIndex);
break;
case RecompilerIrOperationKind.Store8:
case RecompilerIrOperationKind.Store16:
case RecompilerIrOperationKind.Store32:
Require(!hasResult && hasA && hasB, diagnostics, blockIndex, operationIndex);
if (operation.Register != 0)
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidMemoryAccess, "Store operations must not carry a register.", blockIndex, operationIndex);
}
ValidateMemoryEffect(operation, diagnostics, blockIndex, operationIndex);
break;
case RecompilerIrOperationKind.CompareEqual:
case RecompilerIrOperationKind.CompareNotEqual:
case RecompilerIrOperationKind.CompareLessThanSigned:
case RecompilerIrOperationKind.CompareLessThanUnsigned:
Require(hasResult && hasA && hasB && operation.ShiftAmount == 0, diagnostics, blockIndex, operationIndex);
break;
case RecompilerIrOperationKind.ShiftLeftLogical:
case RecompilerIrOperationKind.ShiftRightLogical:
case RecompilerIrOperationKind.ShiftRightArithmetic:
Require(hasResult && hasA && !hasB && operation.ShiftAmount <= 31, diagnostics, blockIndex, operationIndex);
break;
default:
Require(hasResult && hasA && hasB && operation.ShiftAmount == 0, diagnostics, blockIndex, operationIndex);
break;
}
var isMemoryAccess = operation.Kind is RecompilerIrOperationKind.Load8 or RecompilerIrOperationKind.Load16 or RecompilerIrOperationKind.Load32
or RecompilerIrOperationKind.Store8 or RecompilerIrOperationKind.Store16 or RecompilerIrOperationKind.Store32;
if (!isMemoryAccess && operation.MemoryEffect != RecompilerIrMemoryEffectKind.Unknown)
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidMemoryAccess, "Only a memory-access operation may carry a memory effect.", blockIndex, operationIndex);
}
}
/// <summary>
/// Fails closed on a Load/Store operation whose memory effect is not one of
/// the defined <see cref="RecompilerIrMemoryEffectKind"/> values, rather than
/// letting a garbage byte silently pass through as if it meant something
/// (Issue #411: an unsupported/unclassifiable effect must be an explicit
/// diagnostic, never a silent fallback to "ordinary").
/// </summary>
private static void ValidateMemoryEffect(RecompilerIrOperation operation, List<RecompilerIrDiagnostic> diagnostics, int blockIndex, int operationIndex)
{
if (!Enum.IsDefined(operation.MemoryEffect))
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidMemoryAccess, "Memory effect must be a defined value.", blockIndex, operationIndex);
}
}
private static void ValidateInput(int valueId, HashSet<int> definedValueIds, List<RecompilerIrDiagnostic> diagnostics, int blockIndex, int operationIndex)
{
if (valueId >= 0 && !definedValueIds.Contains(valueId))
{
Add(diagnostics, RecompilerIrDiagnosticCode.MissingOperand, "Input value must be defined by an earlier operation in the block.", blockIndex, operationIndex);
}
}
private static void Require(bool condition, List<RecompilerIrDiagnostic> diagnostics, int blockIndex, int operationIndex)
{
if (!condition)
{
Add(diagnostics, RecompilerIrDiagnosticCode.InvalidOperationShape, "Operation has an invalid operand shape.", blockIndex, operationIndex);
}
}
private static void Add(List<RecompilerIrDiagnostic> diagnostics, RecompilerIrDiagnosticCode code, string message, int blockIndex, int operationIndex = -1) =>
diagnostics.Add(new RecompilerIrDiagnostic(code, message, blockIndex, operationIndex));
}
[Domain]
public sealed record RecompilerLoadDelayState
{
public RecompilerLoadDelayState(bool isPending = false, byte targetRegister = 0, uint value = 0)
{
if (targetRegister > 31) throw new ArgumentOutOfRangeException(nameof(targetRegister));
IsPending = isPending;
TargetRegister = targetRegister;
Value = value;
}
public bool IsPending { get; }
public byte TargetRegister { get; }
public uint Value { get; }
}
[Domain]
public sealed record RecompilerExceptionState
{
public RecompilerExceptionState(bool isRaised = false, uint code = 0, uint faultPc = 0, bool inDelaySlot = false)
{
IsRaised = isRaised;
Code = code;
FaultPc = faultPc;
InDelaySlot = inDelaySlot;
}
public bool IsRaised { get; }
public uint Code { get; }
public uint FaultPc { get; }
public bool InDelaySlot { get; }
}
[Domain]
public sealed record RecompilerMemoryObservation
{
public RecompilerMemoryObservation(uint address, uint value, byte width, RecompilerMemoryAccessKind access)
{
if (width is not (1 or 2 or 4)) throw new ArgumentOutOfRangeException(nameof(width));
if (!Enum.IsDefined(access)) throw new ArgumentOutOfRangeException(nameof(access));
Address = address;
Value = value;
Width = width;
Access = access;
}
public uint Address { get; }
public uint Value { get; }
public byte Width { get; }
public RecompilerMemoryAccessKind Access { get; }
}
[Domain]
public sealed record RecompilerStateSnapshot
{
public RecompilerStateSnapshot(
IEnumerable<uint> gpr,
uint hi,
uint lo,
uint pc,
RecompilerLoadDelayState? loadDelay = null,
RecompilerExceptionState? exception = null,
RecompilerIrTerminationReason termination = RecompilerIrTerminationReason.Success,
IEnumerable<RecompilerMemoryObservation>? memory = null,
IEnumerable<uint>? pcTrace = null)
{
ArgumentNullException.ThrowIfNull(gpr);
if (!Enum.IsDefined(termination)) throw new ArgumentOutOfRangeException(nameof(termination));
var registers = gpr.ToArray();
if (registers.Length != 32) throw new ArgumentException("A state snapshot must contain exactly 32 GPR values.", nameof(gpr));
registers[0] = 0;
Gpr = new ReadOnlyCollection<uint>(registers);
HI = hi;
LO = lo;
PC = pc;
LoadDelay = loadDelay ?? new RecompilerLoadDelayState();
Exception = exception ?? new RecompilerExceptionState();
Termination = termination;
Memory = new ReadOnlyCollection<RecompilerMemoryObservation>((memory ?? Array.Empty<RecompilerMemoryObservation>()).ToArray());
PcTrace = new ReadOnlyCollection<uint>((pcTrace ?? Array.Empty<uint>()).ToArray());
}
public IReadOnlyList<uint> Gpr { get; }
public uint HI { get; }
public uint LO { get; }
public uint PC { get; }
public RecompilerLoadDelayState LoadDelay { get; }
public RecompilerExceptionState Exception { get; }
public RecompilerIrTerminationReason Termination { get; }
public IReadOnlyList<RecompilerMemoryObservation> Memory { get; }
/// <summary>
/// The ordered guest PCs retired during the bounded run. The interpreter
/// records one PC per retired MIPS instruction (delay slots included); the
/// recompiled host records one PC per retired block (so a fused branch+delay
/// block retires a single entry). The host trace is therefore an ordered
/// subsequence of the interpreter trace for a matching execution (B1).
/// </summary>
public IReadOnlyList<uint> PcTrace { get; }
}
[Domain]
public static class RecompilerIrSerializer
{
public static string Serialize(RecompilerIrProgram program)
{
ArgumentNullException.ThrowIfNull(program);
var validation = RecompilerIrValidator.Validate(program);
if (!validation.IsValid) throw new ArgumentException("IR must validate before serialization.", nameof(program));
return ArtifactJson.Serialize(program);
}
public static string Serialize(RecompilerStateSnapshot snapshot)
{
ArgumentNullException.ThrowIfNull(snapshot);
return ArtifactJson.Serialize(snapshot);
}
}