-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSafeCoreOwnership.cs
More file actions
2790 lines (2571 loc) · 150 KB
/
Copy pathSafeCoreOwnership.cs
File metadata and controls
2790 lines (2571 loc) · 150 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
using System.Collections.Immutable;
using System.Collections.ObjectModel;
using System.Diagnostics;
using System.Globalization;
using RustSharp.Syntax;
namespace RustSharp.Semantics;
/// <summary>The value semantics used by the bounded safe-core ownership pass.</summary>
public enum SafeCoreOwnershipKind
{
Move,
Copy,
}
/// <summary>How a panic edge disposes values that are still live.</summary>
public enum SafeCorePanicStrategy
{
Unwind,
Abort,
}
public enum SafeCoreOwnershipOutcome
{
Returned,
Unwound,
Aborted,
Unreachable,
LimitExceeded,
}
public static class SafeCoreOwnershipDiagnosticCodes
{
public const string InvalidInput = "RSO0001";
public const string InvalidControlFlow = "RSO0002";
public const string LimitReached = "RSO0003";
public const string UseAfterMove = "RSO1001";
public const string BorrowConflict = "RSO1002";
public const string MoveWhileBorrowed = "RSO1003";
public const string InvalidBorrow = "RSO1004";
public const string Escape = "RSO1005";
public const string InvalidDrop = "RSO1006";
public const string ImmutableBorrow = "RSO1007";
public const string InvalidMovePath = "RSO1008";
}
/// <summary>A local tracked by the ownership pass. IDs index the owning function.</summary>
public sealed record SafeCoreOwnershipLocal(
int Id,
string Name,
SafeCoreType Type,
SafeCoreOwnershipKind Kind,
bool HasDrop,
int ScopeId,
bool IsReference,
bool InitiallyInitialized,
SafeCoreMirSource Source)
{
/// <summary>Original aggregate field represented by a synthetic reference slot.</summary>
public SafeCoreOwnershipPlace? StoragePlace { get; init; }
/// <summary>The physical reference slot exists only while its containing enum variant is active.</summary>
public bool IsOptionalEnumPayload { get; init; }
}
/// <summary>A bounded projection used to identify a move/borrow path.</summary>
public enum SafeCoreOwnershipProjectionKind
{
Field,
TupleIndex,
ArrayIndex,
Dereference,
DynamicIndex,
ArrayRange,
SliceRange,
FromEndIndex,
}
public sealed record SafeCoreOwnershipProjection(
SafeCoreOwnershipProjectionKind Kind,
string? Name,
int Index)
{
/// <summary>Exclusive upper bound for a constant array or slice range.</summary>
public int EndIndex { get; init; } = -1;
public int MinimumLength { get; init; }
public static SafeCoreOwnershipProjection Field(string name) =>
new(SafeCoreOwnershipProjectionKind.Field, name, -1);
public static SafeCoreOwnershipProjection TupleIndex(int index) =>
new(SafeCoreOwnershipProjectionKind.TupleIndex, null, index);
public static SafeCoreOwnershipProjection ArrayIndex(int index) =>
new(SafeCoreOwnershipProjectionKind.ArrayIndex, null, index);
public static SafeCoreOwnershipProjection Dereference() =>
new(SafeCoreOwnershipProjectionKind.Dereference, null, -1);
public static SafeCoreOwnershipProjection DynamicIndex(int localId) =>
new(SafeCoreOwnershipProjectionKind.DynamicIndex, null, localId);
public static SafeCoreOwnershipProjection ArrayRange(int start, int end) =>
new(SafeCoreOwnershipProjectionKind.ArrayRange, null, start) { EndIndex = end };
/// <summary>A pattern partition excluding a fixed prefix and suffix from a dynamic slice.</summary>
public static SafeCoreOwnershipProjection SliceRange(int prefix, int suffix) =>
new(SafeCoreOwnershipProjectionKind.SliceRange, null, prefix) { EndIndex = suffix };
public static SafeCoreOwnershipProjection FromEndIndex(int distance, int minimumLength) =>
new(SafeCoreOwnershipProjectionKind.FromEndIndex, null, distance) { MinimumLength = minimumLength };
}
/// <summary>
/// A local plus a finite projection chain. Root places preserve the original
/// local-only ownership behavior; projected places let the pass model partial
/// moves without pretending that an aggregate's entire value was consumed.
/// </summary>
public sealed class SafeCoreOwnershipPlace
{
public SafeCoreOwnershipPlace(int localId, IReadOnlyList<SafeCoreOwnershipProjection>? projections = null)
{
ArgumentOutOfRangeException.ThrowIfNegative(localId, nameof(localId));
projections ??= [];
if (projections.Count > 128) throw new ArgumentException("Ownership projection depth exceeds its bound.", nameof(projections));
var copy = new SafeCoreOwnershipProjection[projections.Count];
for (int index = 0; index < copy.Length; index++)
{
SafeCoreOwnershipProjection projection = projections[index] ??
throw new ArgumentException("Ownership projections cannot contain null values.", nameof(projections));
if (!Enum.IsDefined(projection.Kind) ||
(projection.Kind != SafeCoreOwnershipProjectionKind.FromEndIndex && projection.MinimumLength != 0) ||
(projection.Kind == SafeCoreOwnershipProjectionKind.FromEndIndex &&
(projection.Name is not null || projection.Index <= 0 || projection.MinimumLength < projection.Index)) ||
(projection.Kind == SafeCoreOwnershipProjectionKind.Field &&
(string.IsNullOrWhiteSpace(projection.Name) || projection.Name.Length > 4_096 || projection.Index != -1)) ||
(projection.Kind is SafeCoreOwnershipProjectionKind.TupleIndex or SafeCoreOwnershipProjectionKind.ArrayIndex or SafeCoreOwnershipProjectionKind.DynamicIndex &&
(projection.Name is not null || projection.Index < 0)) ||
(projection.Kind == SafeCoreOwnershipProjectionKind.ArrayRange &&
(projection.Name is not null || projection.Index < 0 || projection.EndIndex < projection.Index)) ||
(projection.Kind == SafeCoreOwnershipProjectionKind.SliceRange &&
(projection.Name is not null || projection.Index < 0 || projection.EndIndex < 0)) ||
(projection.Kind is not (SafeCoreOwnershipProjectionKind.ArrayRange or SafeCoreOwnershipProjectionKind.SliceRange) && projection.EndIndex != -1) ||
(projection.Kind is SafeCoreOwnershipProjectionKind.Dereference &&
(projection.Name is not null || projection.Index != -1)))
throw new ArgumentException("Ownership projection metadata is invalid.", nameof(projections));
copy[index] = projection;
}
LocalId = localId;
Projections = Array.AsReadOnly(copy);
}
public int LocalId { get; }
public IReadOnlyList<SafeCoreOwnershipProjection> Projections { get; }
public bool IsRoot => Projections.Count == 0;
public static SafeCoreOwnershipPlace Root(int localId) => new(localId);
public SafeCoreOwnershipPlace Append(SafeCoreOwnershipProjection projection) =>
new(LocalId, [.. Projections, projection]);
public override string ToString()
{
var builder = new System.Text.StringBuilder(LocalId.ToString(CultureInfo.InvariantCulture));
foreach (SafeCoreOwnershipProjection projection in Projections)
{
switch (projection.Kind)
{
case SafeCoreOwnershipProjectionKind.Field:
builder.Append('.').Append(projection.Name);
break;
case SafeCoreOwnershipProjectionKind.TupleIndex:
builder.Append(".tuple[").Append(projection.Index.ToString(CultureInfo.InvariantCulture)).Append(']');
break;
case SafeCoreOwnershipProjectionKind.ArrayIndex:
builder.Append('[').Append(projection.Index.ToString(CultureInfo.InvariantCulture)).Append(']');
break;
case SafeCoreOwnershipProjectionKind.ArrayRange:
builder.Append('[').Append(projection.Index.ToString(CultureInfo.InvariantCulture)).Append("..")
.Append(projection.EndIndex.ToString(CultureInfo.InvariantCulture)).Append(']');
break;
case SafeCoreOwnershipProjectionKind.SliceRange:
builder.Append('[').Append(projection.Index.ToString(CultureInfo.InvariantCulture)).Append("..len-")
.Append(projection.EndIndex.ToString(CultureInfo.InvariantCulture)).Append(']');
break;
case SafeCoreOwnershipProjectionKind.DynamicIndex:
builder.Append("[local:").Append(projection.Index.ToString(CultureInfo.InvariantCulture)).Append(']');
break;
case SafeCoreOwnershipProjectionKind.FromEndIndex:
builder.Append("[len-").Append(projection.Index.ToString(CultureInfo.InvariantCulture)).Append(";min=")
.Append(projection.MinimumLength.ToString(CultureInfo.InvariantCulture)).Append(']');
break;
case SafeCoreOwnershipProjectionKind.Dereference:
builder.Append('.').Append('*');
break;
}
}
return builder.ToString();
}
}
public enum SafeCoreOwnershipInstructionKind
{
Use,
Assign,
Move,
Borrow,
EndBorrow,
Write,
Drop,
Consume,
CallArguments,
EnterScope,
ExitScope,
}
/// <summary>One bounded ownership operation with original source evidence.</summary>
public sealed record SafeCoreOwnershipInstruction(
SafeCoreOwnershipInstructionKind Kind,
int LocalId,
int RelatedLocalId,
bool IsMutable,
int ScopeId,
SafeCoreMirSource Source)
{
/// <summary>Checked possible referents of a direct call's returned reference.</summary>
public IReadOnlyList<SafeCoreOwnershipPlace>? AlternativePlaces { get; init; }
public IReadOnlyList<SafeCoreOwnershipCallArgument>? ReferenceArguments { get; init; }
public static SafeCoreOwnershipInstruction CheckCallArguments(IReadOnlyList<SafeCoreOwnershipCallArgument> arguments, SafeCoreMirSource source) =>
new(SafeCoreOwnershipInstructionKind.CallArguments, -1, -1, false, -1, source) { ReferenceArguments = arguments };
public static SafeCoreOwnershipInstruction Consume(SafeCoreOwnershipPlace place, SafeCoreMirSource source) =>
new(SafeCoreOwnershipInstructionKind.Consume, place.LocalId, -1, false, -1, source) { Place = place };
/// <summary>Optional projected place; null means the root local in LocalId.</summary>
public SafeCoreOwnershipPlace? Place { get; init; }
/// <summary>Optional projected destination/related place for Move/Borrow.</summary>
public SafeCoreOwnershipPlace? RelatedPlace { get; init; }
/// <summary>The borrow refers to checked immutable promoted storage.</summary>
public bool IsStaticBorrow { get; init; }
/// <summary>An aggregate enum transfer may have an inactive reference payload slot.</summary>
public bool AllowAbsentReference { get; init; }
/// <summary>Exact boolean assignment facts derived from the corresponding MIR rvalue.</summary>
public bool? ConstantBoolean { get; init; }
public int CopiedBooleanLocalId { get; init; } = -1;
/// <summary>Required payload slots for an enum tag equality; absence proves the comparison false.</summary>
public IReadOnlyList<int>? EnumVariantReferenceSlots { get; init; }
public static SafeCoreOwnershipInstruction Use(int localId, SafeCoreMirSource source) =>
new(SafeCoreOwnershipInstructionKind.Use, localId, -1, false, -1, source);
public static SafeCoreOwnershipInstruction Use(SafeCoreOwnershipPlace place, SafeCoreMirSource source) =>
new(SafeCoreOwnershipInstructionKind.Use, place.LocalId, -1, false, -1, source) { Place = place };
public static SafeCoreOwnershipInstruction Assign(int localId, SafeCoreMirSource source) =>
new(SafeCoreOwnershipInstructionKind.Assign, localId, -1, false, -1, source);
/// <summary>Assign a copied shared reference while retaining its active loan.</summary>
public static SafeCoreOwnershipInstruction AssignReference(int sourceLocalId, int destinationLocalId,
SafeCoreMirSource source) =>
new(SafeCoreOwnershipInstructionKind.Assign, destinationLocalId, sourceLocalId, false, -1, source);
public static SafeCoreOwnershipInstruction AssignReference(SafeCoreOwnershipPlace sourcePlace,
SafeCoreOwnershipPlace destinationPlace, SafeCoreMirSource source) =>
new(SafeCoreOwnershipInstructionKind.Assign, destinationPlace.LocalId, sourcePlace.LocalId, false, -1, source)
{ Place = destinationPlace, RelatedPlace = sourcePlace };
public static SafeCoreOwnershipInstruction Assign(SafeCoreOwnershipPlace place, SafeCoreMirSource source) =>
new(SafeCoreOwnershipInstructionKind.Assign, place.LocalId, -1, false, -1, source) { Place = place };
public static SafeCoreOwnershipInstruction Move(int sourceLocalId, int destinationLocalId, SafeCoreMirSource source) =>
new(SafeCoreOwnershipInstructionKind.Move, sourceLocalId, destinationLocalId, false, -1, source);
public static SafeCoreOwnershipInstruction Move(SafeCoreOwnershipPlace sourcePlace,
SafeCoreOwnershipPlace destinationPlace, SafeCoreMirSource source) =>
new(SafeCoreOwnershipInstructionKind.Move, sourcePlace.LocalId, destinationPlace.LocalId, false, -1, source)
{
Place = sourcePlace,
RelatedPlace = destinationPlace,
};
public static SafeCoreOwnershipInstruction Borrow(int ownerLocalId, int referenceLocalId, bool mutable, SafeCoreMirSource source) =>
new(SafeCoreOwnershipInstructionKind.Borrow, ownerLocalId, referenceLocalId, mutable, -1, source);
public static SafeCoreOwnershipInstruction Borrow(SafeCoreOwnershipPlace ownerPlace,
SafeCoreOwnershipPlace referencePlace, bool mutable, SafeCoreMirSource source) =>
new(SafeCoreOwnershipInstructionKind.Borrow, ownerPlace.LocalId, referencePlace.LocalId, mutable, -1, source)
{
Place = ownerPlace,
RelatedPlace = referencePlace,
};
public static SafeCoreOwnershipInstruction EndBorrow(int referenceLocalId, SafeCoreMirSource source) =>
new(SafeCoreOwnershipInstructionKind.EndBorrow, referenceLocalId, -1, false, -1, source);
public static SafeCoreOwnershipInstruction EndBorrow(SafeCoreOwnershipPlace referencePlace, SafeCoreMirSource source) =>
new(SafeCoreOwnershipInstructionKind.EndBorrow, referencePlace.LocalId, -1, false, -1, source)
{
Place = referencePlace,
};
public static SafeCoreOwnershipInstruction Write(int referenceLocalId, SafeCoreMirSource source) =>
new(SafeCoreOwnershipInstructionKind.Write, referenceLocalId, -1, false, -1, source);
public static SafeCoreOwnershipInstruction Write(SafeCoreOwnershipPlace referencePlace, SafeCoreMirSource source) =>
new(SafeCoreOwnershipInstructionKind.Write, referencePlace.LocalId, -1, false, -1, source)
{
Place = referencePlace,
};
public static SafeCoreOwnershipInstruction Drop(int localId, SafeCoreMirSource source) =>
new(SafeCoreOwnershipInstructionKind.Drop, localId, -1, false, -1, source);
public static SafeCoreOwnershipInstruction Drop(SafeCoreOwnershipPlace place, SafeCoreMirSource source) =>
new(SafeCoreOwnershipInstructionKind.Drop, place.LocalId, -1, false, -1, source) { Place = place };
public static SafeCoreOwnershipInstruction EnterScope(int scopeId, SafeCoreMirSource source) =>
new(SafeCoreOwnershipInstructionKind.EnterScope, -1, -1, false, scopeId, source);
public static SafeCoreOwnershipInstruction ExitScope(int scopeId, SafeCoreMirSource source) =>
new(SafeCoreOwnershipInstructionKind.ExitScope, -1, -1, false, scopeId, source);
}
/// <summary>A reference argument whose loan remains active throughout one direct call.</summary>
public sealed record SafeCoreOwnershipCallArgument(SafeCoreOwnershipPlace Place, bool IsMutable)
{
public bool AllowAbsent { get; init; }
}
public enum SafeCoreOwnershipTerminatorKind
{
Goto,
Branch,
Return,
Panic,
Unreachable,
}
/// <summary>One explicit CFG terminator. A return value is a local ID or -1.</summary>
public sealed record SafeCoreOwnershipTerminator(
SafeCoreOwnershipTerminatorKind Kind,
int LocalId,
int TargetBlockId,
int FalseTargetBlockId,
SafeCoreMirSource Source)
{
public static SafeCoreOwnershipTerminator Goto(int targetBlockId, SafeCoreMirSource source) =>
new(SafeCoreOwnershipTerminatorKind.Goto, -1, targetBlockId, -1, source);
public static SafeCoreOwnershipTerminator Branch(int conditionLocalId, int trueTargetBlockId,
int falseTargetBlockId, SafeCoreMirSource source) =>
new(SafeCoreOwnershipTerminatorKind.Branch, conditionLocalId, trueTargetBlockId, falseTargetBlockId, source);
public static SafeCoreOwnershipTerminator Return(int localId, SafeCoreMirSource source) =>
new(SafeCoreOwnershipTerminatorKind.Return, localId, -1, -1, source);
public static SafeCoreOwnershipTerminator ReturnUnit(SafeCoreMirSource source) => Return(-1, source);
public static SafeCoreOwnershipTerminator Panic(SafeCoreMirSource source) =>
new(SafeCoreOwnershipTerminatorKind.Panic, -1, -1, -1, source);
public static SafeCoreOwnershipTerminator Unreachable(SafeCoreMirSource source) =>
new(SafeCoreOwnershipTerminatorKind.Unreachable, -1, -1, -1, source);
}
public sealed class SafeCoreOwnershipScope
{
public SafeCoreOwnershipScope(int id, int parentId, SafeCoreMirSource source)
{
Id = id;
ParentId = parentId;
Source = source;
}
public int Id { get; }
public int ParentId { get; }
public SafeCoreMirSource Source { get; }
}
public sealed class SafeCoreOwnershipBlock
{
public SafeCoreOwnershipBlock(
int id,
int scopeId,
IReadOnlyList<SafeCoreOwnershipInstruction> instructions,
SafeCoreOwnershipTerminator terminator,
SafeCoreMirSource source)
{
Id = id;
ScopeId = scopeId;
Instructions = Freeze(instructions, 65_536, nameof(instructions));
Terminator = terminator ?? throw new ArgumentNullException(nameof(terminator));
Source = source;
}
public int Id { get; }
public int ScopeId { get; }
public IReadOnlyList<SafeCoreOwnershipInstruction> Instructions { get; }
public SafeCoreOwnershipTerminator Terminator { get; }
public SafeCoreMirSource Source { get; }
private static ReadOnlyCollection<T> Freeze<T>(IReadOnlyList<T> values, int maximum, string parameterName)
{
ArgumentNullException.ThrowIfNull(values);
if (values.Count > maximum) throw new ArgumentException("Ownership collection exceeds its bound.", parameterName);
var copy = new T[values.Count];
for (int index = 0; index < copy.Length; index++)
{
copy[index] = values[index] ?? throw new ArgumentException("Ownership collections cannot contain null values.", parameterName);
}
return Array.AsReadOnly(copy);
}
}
public sealed class SafeCoreOwnershipFunction
{
public SafeCoreOwnershipFunction(
string name,
IReadOnlyList<SafeCoreOwnershipLocal> locals,
IReadOnlyList<SafeCoreOwnershipScope> scopes,
IReadOnlyList<SafeCoreOwnershipBlock> blocks,
int entryBlockId,
SafeCorePanicStrategy panicStrategy,
SafeCoreMirSource source)
{
ArgumentException.ThrowIfNullOrWhiteSpace(name);
Name = name;
Locals = Freeze(locals, 4096, nameof(locals));
Scopes = Freeze(scopes, 4096, nameof(scopes));
Blocks = Freeze(blocks, 16_384, nameof(blocks));
EntryBlockId = entryBlockId;
PanicStrategy = panicStrategy;
Source = source;
}
public string Name { get; }
public IReadOnlyList<SafeCoreOwnershipLocal> Locals { get; }
public IReadOnlyList<SafeCoreOwnershipScope> Scopes { get; }
public IReadOnlyList<SafeCoreOwnershipBlock> Blocks { get; }
public int EntryBlockId { get; }
public SafeCorePanicStrategy PanicStrategy { get; }
public SafeCoreMirSource Source { get; }
private static ReadOnlyCollection<T> Freeze<T>(IReadOnlyList<T> values, int maximum, string parameterName)
{
ArgumentNullException.ThrowIfNull(values);
if (values.Count > maximum) throw new ArgumentException("Ownership collection exceeds its bound.", parameterName);
var copy = new T[values.Count];
for (int index = 0; index < copy.Length; index++)
copy[index] = values[index] ?? throw new ArgumentException("Ownership collections cannot contain null values.", parameterName);
return Array.AsReadOnly(copy);
}
}
public sealed class SafeCoreOwnershipProgram
{
public SafeCoreOwnershipProgram(IReadOnlyList<SafeCoreOwnershipFunction> functions)
{
ArgumentNullException.ThrowIfNull(functions);
if (functions.Count is < 1 or > 4096) throw new ArgumentException("Ownership program function count is out of bounds.", nameof(functions));
var copy = new SafeCoreOwnershipFunction[functions.Count];
for (int index = 0; index < copy.Length; index++) copy[index] = functions[index] ?? throw new ArgumentException("Function cannot be null.", nameof(functions));
Functions = Array.AsReadOnly(copy);
}
public IReadOnlyList<SafeCoreOwnershipFunction> Functions { get; }
}
public sealed record SafeCoreOwnershipDiagnostic(
string Code,
string Message,
string FunctionName,
int BlockId,
int InstructionIndex,
SafeCoreMirSource Source)
{
public override string ToString() =>
$"{Code} {FunctionName} bb{BlockId}:{InstructionIndex}: {Message}";
}
public sealed record SafeCoreOwnershipPath(
int PathId,
string FunctionName,
SafeCoreOwnershipOutcome Outcome,
ImmutableArray<string> DropOrder,
ImmutableArray<string> Trace);
public sealed record SafeCoreOwnershipOptions
{
public TimeSpan Timeout { get; init; } = TimeSpan.FromSeconds(10);
public int MaximumOperations { get; init; } = 1_000_000;
public int MaximumPaths { get; init; } = 4096;
public int MaximumBlockVisits { get; init; } = 128;
public int MaximumDiagnostics { get; init; } = 256;
/// <summary>Infer borrow end points from bounded CFG liveness.</summary>
public bool InferNonLexicalLifetimes { get; init; }
/// <summary>Short alias for callers that use the conventional NLL name.</summary>
public bool InferNll { get; init; }
public CancellationToken CancellationToken { get; init; }
}
public sealed record SafeCoreOwnershipAnalysisResult(
ImmutableArray<SafeCoreOwnershipDiagnostic> Diagnostics,
ImmutableArray<SafeCoreOwnershipPath> Paths,
bool IsTruncated)
{
public bool IsSuccessful => !IsTruncated && Diagnostics.IsEmpty && !Paths.IsEmpty &&
Paths.All(path => path.Outcome is SafeCoreOwnershipOutcome.Returned or SafeCoreOwnershipOutcome.Unwound or SafeCoreOwnershipOutcome.Aborted or SafeCoreOwnershipOutcome.Unreachable);
}
/// <summary>
/// Bounded, branch-sensitive ownership analysis for the safe-core MIR boundary.
/// It is deliberately backend independent and records every cleanup path before
/// an IL emitter is allowed to consume ownership evidence.
/// </summary>
public static class SafeCoreOwnershipAnalysis
{
public const string Profile = "safe-core-ownership-v1";
private static readonly SafeCoreMirSource InvalidSource =
new("<invalid>", new TextSpan(0, 0), 0, 0);
public static SafeCoreOwnershipAnalysisResult Analyze(
SafeCoreOwnershipProgram program,
SafeCoreOwnershipOptions? options = null)
{
ArgumentNullException.ThrowIfNull(program);
options ??= new();
if (options.Timeout <= TimeSpan.Zero || options.Timeout > TimeSpan.FromMinutes(1) ||
options.MaximumOperations is < 1 or > 4_000_000 || options.MaximumPaths is < 1 or > 65_536 ||
options.MaximumBlockVisits is < 1 or > 4096 || options.MaximumDiagnostics is < 1 or > 4096)
throw new ArgumentOutOfRangeException(nameof(options));
var diagnostics = ImmutableArray.CreateBuilder<SafeCoreOwnershipDiagnostic>();
var paths = ImmutableArray.CreateBuilder<SafeCoreOwnershipPath>();
var diagnosticKeys = new HashSet<string>(StringComparer.Ordinal);
var clock = Stopwatch.StartNew();
int operations = 0;
bool truncated = false;
int nextPathId = 0;
void Step()
{
options.CancellationToken.ThrowIfCancellationRequested();
if (++operations > options.MaximumOperations || clock.Elapsed >= options.Timeout)
throw new OwnershipLimitException();
}
void AddDiagnostic(string code, string message, string functionName, int blockId, int instructionIndex, SafeCoreMirSource source)
{
Step();
source ??= InvalidSource;
string key = string.Join('\u001f', code, functionName, blockId.ToString(CultureInfo.InvariantCulture),
instructionIndex.ToString(CultureInfo.InvariantCulture), message);
if (diagnosticKeys.Add(key))
{
if (diagnostics.Count >= options.MaximumDiagnostics) throw new OwnershipLimitException();
diagnostics.Add(new(code, message, functionName, blockId, instructionIndex, source));
}
}
try
{
var functionNames = new HashSet<string>(StringComparer.Ordinal);
foreach (SafeCoreOwnershipFunction function in program.Functions)
{
Step();
if (!functionNames.Add(function.Name))
{
AddDiagnostic(SafeCoreOwnershipDiagnosticCodes.InvalidInput,
"Ownership function names must be unique.", function.Name, -1, -1, function.Source);
continue;
}
ValidateShape(function, AddDiagnostic, Step);
if (diagnostics.Any(diagnostic => diagnostic.FunctionName == function.Name &&
diagnostic.Code is SafeCoreOwnershipDiagnosticCodes.InvalidInput or SafeCoreOwnershipDiagnosticCodes.InvalidControlFlow))
continue;
AnalyzeFunction(function, paths, AddDiagnostic, Step, ref nextPathId, options);
}
}
catch (OwnershipLimitException)
{
truncated = true;
if (diagnostics.Count < options.MaximumDiagnostics)
{
SafeCoreMirSource source = program.Functions[0].Source;
diagnostics.Add(new(SafeCoreOwnershipDiagnosticCodes.LimitReached,
"Ownership analysis exceeded its work, path, block-visit or time limit.",
program.Functions[0].Name, -1, -1, source));
}
}
return new(diagnostics.ToImmutable(), paths.ToImmutable(), truncated);
}
private static void ValidateShape(
SafeCoreOwnershipFunction function,
Action<string, string, string, int, int, SafeCoreMirSource> add,
Action step)
{
if (!IsValidSource(function.Source))
add(SafeCoreOwnershipDiagnosticCodes.InvalidInput, "Ownership function source evidence is invalid.", function.Name, -1, -1, function.Source);
var blockIds = new HashSet<int>();
var localIds = new HashSet<int>();
var scopeIds = new HashSet<int>();
foreach (SafeCoreOwnershipLocal local in function.Locals)
{
step();
if (!IsValidSource(local.Source))
add(SafeCoreOwnershipDiagnosticCodes.InvalidInput, "Ownership local source evidence is invalid.", function.Name, -1, -1, local.Source);
if (local.Id < 0 || local.Id != localIds.Count || !localIds.Add(local.Id) ||
string.IsNullOrWhiteSpace(local.Name) || local.Type is null || !Enum.IsDefined(local.Kind) ||
local.IsOptionalEnumPayload && (!local.IsReference || local.StoragePlace is null))
add(SafeCoreOwnershipDiagnosticCodes.InvalidInput, "Ownership local IDs and metadata must be dense and valid.", function.Name, -1, -1, local.Source);
}
if (!Enum.IsDefined(function.PanicStrategy))
add(SafeCoreOwnershipDiagnosticCodes.InvalidInput, "Ownership panic strategy is outside the supported enum.", function.Name, -1, -1, function.Source);
foreach (SafeCoreOwnershipScope scope in function.Scopes)
{
step();
if (!IsValidSource(scope.Source))
add(SafeCoreOwnershipDiagnosticCodes.InvalidInput, "Ownership scope source evidence is invalid.", function.Name, -1, -1, scope.Source);
if (scope.Id < 0 || !scopeIds.Add(scope.Id) || scope.ParentId >= scope.Id || scope.ParentId < -1)
add(SafeCoreOwnershipDiagnosticCodes.InvalidInput, "Ownership scopes must have unique IDs and an earlier parent.", function.Name, -1, -1, scope.Source);
}
foreach (SafeCoreOwnershipScope scope in function.Scopes)
{
step();
if (scope.Id == 0 && scope.ParentId != -1)
add(SafeCoreOwnershipDiagnosticCodes.InvalidInput, "Root ownership scope must not have a parent.", function.Name, -1, -1, scope.Source);
else if (scope.Id != 0 && scope.ParentId < 0)
add(SafeCoreOwnershipDiagnosticCodes.InvalidInput, "Non-root ownership scopes require a parent.", function.Name, -1, -1, scope.Source);
else if (scope.ParentId >= 0 && !scopeIds.Contains(scope.ParentId))
add(SafeCoreOwnershipDiagnosticCodes.InvalidInput, "An ownership scope parent is outside the scope arena.", function.Name, -1, -1, scope.Source);
}
if (!scopeIds.Contains(0))
add(SafeCoreOwnershipDiagnosticCodes.InvalidInput, "Ownership functions require root scope 0.", function.Name, -1, -1, function.Source);
foreach (SafeCoreOwnershipLocal local in function.Locals)
{
step();
if (!scopeIds.Contains(local.ScopeId))
add(SafeCoreOwnershipDiagnosticCodes.InvalidInput, "An ownership local references an unknown scope.", function.Name, -1, -1, local.Source);
}
if (function.EntryBlockId < 0 || function.EntryBlockId >= function.Blocks.Count)
add(SafeCoreOwnershipDiagnosticCodes.InvalidControlFlow, "Entry block is outside the block arena.", function.Name, -1, -1, function.Source);
foreach (SafeCoreOwnershipBlock block in function.Blocks)
{
step();
if (!IsValidSource(block.Source))
add(SafeCoreOwnershipDiagnosticCodes.InvalidInput, "Ownership block source evidence is invalid.", function.Name, block.Id, -1, block.Source);
if (block.Id < 0 || block.Id != blockIds.Count || !blockIds.Add(block.Id) || !scopeIds.Contains(block.ScopeId))
add(SafeCoreOwnershipDiagnosticCodes.InvalidControlFlow, "Block IDs and scope references must be dense and valid.", function.Name, block.Id, -1, block.Source);
ValidateTerminator(function, block, add, step);
for (int instructionIndex = 0; instructionIndex < block.Instructions.Count; instructionIndex++)
{
step();
SafeCoreOwnershipInstruction instruction = block.Instructions[instructionIndex];
if (!IsValidSource(instruction.Source))
add(SafeCoreOwnershipDiagnosticCodes.InvalidInput, "Ownership instruction source evidence is invalid.", function.Name, block.Id, instructionIndex, instruction.Source);
if (!Enum.IsDefined(instruction.Kind))
{
add(SafeCoreOwnershipDiagnosticCodes.InvalidInput,
"Ownership instruction kind is outside the supported enum.",
function.Name, block.Id, instructionIndex, instruction.Source);
continue;
}
bool requiresLocal = instruction.Kind is
SafeCoreOwnershipInstructionKind.Use or
SafeCoreOwnershipInstructionKind.Assign or
SafeCoreOwnershipInstructionKind.Move or
SafeCoreOwnershipInstructionKind.Borrow or
SafeCoreOwnershipInstructionKind.EndBorrow or
SafeCoreOwnershipInstructionKind.Write or
SafeCoreOwnershipInstructionKind.Drop or SafeCoreOwnershipInstructionKind.Consume;
bool requiresRelatedLocal = instruction.Kind is
SafeCoreOwnershipInstructionKind.Move or
SafeCoreOwnershipInstructionKind.Borrow;
if ((requiresLocal && !IsValidLocalId(instruction.LocalId, function.Locals.Count)) ||
(requiresRelatedLocal && !IsValidLocalId(instruction.RelatedLocalId, function.Locals.Count)) ||
((!requiresLocal && !requiresRelatedLocal) &&
(instruction.LocalId != -1 || instruction.RelatedLocalId != -1)))
add(SafeCoreOwnershipDiagnosticCodes.InvalidInput, "Ownership instruction references a local outside the arena.", function.Name, block.Id, instructionIndex, instruction.Source);
ValidatePlace(instruction.Place, instruction.LocalId, function, block, instructionIndex, add);
ValidatePlace(instruction.RelatedPlace, instruction.RelatedLocalId, function, block, instructionIndex, add);
if (instruction.ConstantBoolean is not null || instruction.CopiedBooleanLocalId != -1 || instruction.EnumVariantReferenceSlots is not null)
{
bool validBoolean = instruction.Kind == SafeCoreOwnershipInstructionKind.Assign && instruction.RelatedLocalId == -1 &&
instruction.Place is not { IsRoot: false } && IsValidLocalId(instruction.LocalId, function.Locals.Count) &&
function.Locals[instruction.LocalId].Type.Kind == SafeCoreSemanticTypeKind.Bool;
if (instruction.CopiedBooleanLocalId != -1)
validBoolean &= IsValidLocalId(instruction.CopiedBooleanLocalId, function.Locals.Count) &&
function.Locals[instruction.CopiedBooleanLocalId].Type.Kind == SafeCoreSemanticTypeKind.Bool;
if (instruction.EnumVariantReferenceSlots is { } required)
{
validBoolean &= required.Count is > 0 and <= 4096;
foreach (int slot in required.Take(4096))
{
step();
validBoolean &= IsValidLocalId(slot, function.Locals.Count) && function.Locals[slot].IsOptionalEnumPayload;
}
}
if (!validBoolean)
add(SafeCoreOwnershipDiagnosticCodes.InvalidInput, "Boolean ownership facts require a checked boolean assignment and optional enum reference slots.",
function.Name, block.Id, instructionIndex, instruction.Source);
}
if (instruction.AlternativePlaces is { } alternatives)
{
if (instruction.Kind != SafeCoreOwnershipInstructionKind.Borrow || alternatives.Count is < 1 or > 4096)
add(SafeCoreOwnershipDiagnosticCodes.InvalidBorrow, "Alternative origins require a bounded borrow instruction.", function.Name, block.Id, instructionIndex, instruction.Source);
foreach (SafeCoreOwnershipPlace alternative in alternatives.Take(4096))
{ step(); ValidatePlace(alternative, alternative.LocalId, function, block, instructionIndex, add); }
}
if (instruction.ReferenceArguments is { } referenceArguments)
{
if (instruction.Kind != SafeCoreOwnershipInstructionKind.CallArguments || referenceArguments.Count is < 1 or > 4096)
add(SafeCoreOwnershipDiagnosticCodes.InvalidBorrow, "Call reference arguments require a bounded call ownership effect.", function.Name, block.Id, instructionIndex, instruction.Source);
foreach (SafeCoreOwnershipCallArgument argument in referenceArguments.Take(4096))
{ step(); ValidatePlace(argument.Place, argument.Place.LocalId, function, block, instructionIndex, add); }
}
else if (instruction.Kind == SafeCoreOwnershipInstructionKind.CallArguments)
add(SafeCoreOwnershipDiagnosticCodes.InvalidBorrow, "A call ownership effect requires reference argument evidence.", function.Name, block.Id, instructionIndex, instruction.Source);
if (instruction.Kind is not (SafeCoreOwnershipInstructionKind.Move or SafeCoreOwnershipInstructionKind.Borrow or SafeCoreOwnershipInstructionKind.Assign) &&
instruction.RelatedPlace is not null)
add(SafeCoreOwnershipDiagnosticCodes.InvalidMovePath,
"Only move, borrow and reference assignment instructions may carry a related projected place.",
function.Name, block.Id, instructionIndex, instruction.Source);
if (instruction.Kind is SafeCoreOwnershipInstructionKind.EnterScope or SafeCoreOwnershipInstructionKind.ExitScope)
{
if (!scopeIds.Contains(instruction.ScopeId))
add(SafeCoreOwnershipDiagnosticCodes.InvalidInput, "Ownership instruction references an unknown scope.", function.Name, block.Id, instructionIndex, instruction.Source);
}
else if (instruction.ScopeId != -1)
{
add(SafeCoreOwnershipDiagnosticCodes.InvalidInput, "Only scope instructions may carry a scope ID.", function.Name, block.Id, instructionIndex, instruction.Source);
}
}
}
}
private static bool IsValidLocalId(int id, int count) => id >= 0 && id < count;
private static void ValidatePlace(
SafeCoreOwnershipPlace? place,
int localId,
SafeCoreOwnershipFunction function,
SafeCoreOwnershipBlock block,
int instructionIndex,
Action<string, string, string, int, int, SafeCoreMirSource> add)
{
if (place is null) return;
if (place.LocalId != localId || !IsValidLocalId(place.LocalId, function.Locals.Count))
{
add(SafeCoreOwnershipDiagnosticCodes.InvalidMovePath,
"A projected place must identify the instruction's local arena slot.",
function.Name, block.Id, instructionIndex, block.Source);
return;
}
for (int index = 0; index < place.Projections.Count; index++)
{
SafeCoreOwnershipProjection? projection = place.Projections[index];
if (projection is null || !Enum.IsDefined(projection.Kind) ||
(projection.Kind != SafeCoreOwnershipProjectionKind.FromEndIndex && projection.MinimumLength != 0) ||
(projection.Kind == SafeCoreOwnershipProjectionKind.FromEndIndex &&
(projection.Name is not null || projection.Index <= 0 || projection.MinimumLength < projection.Index)) ||
(projection.Kind == SafeCoreOwnershipProjectionKind.Field &&
(string.IsNullOrWhiteSpace(projection.Name) || projection.Name.Length > 4_096 || projection.Index != -1)) ||
(projection.Kind is SafeCoreOwnershipProjectionKind.TupleIndex or SafeCoreOwnershipProjectionKind.ArrayIndex or SafeCoreOwnershipProjectionKind.DynamicIndex &&
(projection.Name is not null || projection.Index < 0)) ||
(projection.Kind == SafeCoreOwnershipProjectionKind.ArrayRange &&
(projection.Name is not null || projection.Index < 0 || projection.EndIndex < projection.Index)) ||
(projection.Kind == SafeCoreOwnershipProjectionKind.SliceRange &&
(projection.Name is not null || projection.Index < 0 || projection.EndIndex < 0)) ||
(projection.Kind is not (SafeCoreOwnershipProjectionKind.ArrayRange or SafeCoreOwnershipProjectionKind.SliceRange) && projection.EndIndex != -1) ||
(projection.Kind == SafeCoreOwnershipProjectionKind.Dereference &&
(projection.Name is not null || projection.Index != -1)))
{
add(SafeCoreOwnershipDiagnosticCodes.InvalidMovePath,
"A projected place contains invalid projection metadata.",
function.Name, block.Id, instructionIndex, block.Source);
}
}
}
private static bool IsValidSource(SafeCoreMirSource? source) =>
source is not null && !string.IsNullOrWhiteSpace(source.SourcePath) && source.SourcePath.Length <= 4_096 &&
source.HirNodeId >= 0 && source.SourceLength >= 0 && source.SourceLength <= 16 * 1024 * 1024 &&
source.Span.Start >= 0 && source.Span.Length >= 0 &&
(long)source.Span.Start + source.Span.Length <= source.SourceLength;
private static void ValidateTerminator(
SafeCoreOwnershipFunction function,
SafeCoreOwnershipBlock block,
Action<string, string, string, int, int, SafeCoreMirSource> add,
Action step)
{
step();
SafeCoreOwnershipTerminator terminator = block.Terminator;
if (!IsValidSource(terminator.Source))
add(SafeCoreOwnershipDiagnosticCodes.InvalidInput, "Ownership terminator source evidence is invalid.", function.Name, block.Id, -1, terminator.Source);
bool validTarget(int target) => target >= 0 && target < function.Blocks.Count;
bool sentinel(int value) => value == -1;
switch (terminator.Kind)
{
case SafeCoreOwnershipTerminatorKind.Goto:
if (!validTarget(terminator.TargetBlockId) || !sentinel(terminator.FalseTargetBlockId) || !sentinel(terminator.LocalId))
add(SafeCoreOwnershipDiagnosticCodes.InvalidControlFlow, "A goto terminator must contain one valid target and no local or false target.", function.Name, block.Id, -1, terminator.Source);
break;
case SafeCoreOwnershipTerminatorKind.Branch:
if (!IsValidLocalId(terminator.LocalId, function.Locals.Count))
add(SafeCoreOwnershipDiagnosticCodes.InvalidInput, "A branch condition references a local outside the arena.", function.Name, block.Id, -1, terminator.Source);
if (!validTarget(terminator.TargetBlockId) || !validTarget(terminator.FalseTargetBlockId))
add(SafeCoreOwnershipDiagnosticCodes.InvalidControlFlow, "A branch terminator must contain two valid targets.", function.Name, block.Id, -1, terminator.Source);
break;
case SafeCoreOwnershipTerminatorKind.Return:
if (terminator.LocalId != -1 && !IsValidLocalId(terminator.LocalId, function.Locals.Count))
add(SafeCoreOwnershipDiagnosticCodes.InvalidInput, "A return value references a local outside the arena.", function.Name, block.Id, -1, terminator.Source);
if (!sentinel(terminator.TargetBlockId) || !sentinel(terminator.FalseTargetBlockId))
add(SafeCoreOwnershipDiagnosticCodes.InvalidControlFlow, "A return terminator cannot contain control-flow targets.", function.Name, block.Id, -1, terminator.Source);
break;
case SafeCoreOwnershipTerminatorKind.Panic:
case SafeCoreOwnershipTerminatorKind.Unreachable:
if (!sentinel(terminator.LocalId) || !sentinel(terminator.TargetBlockId) || !sentinel(terminator.FalseTargetBlockId))
add(SafeCoreOwnershipDiagnosticCodes.InvalidControlFlow, "A terminal terminator cannot contain locals or targets.", function.Name, block.Id, -1, terminator.Source);
break;
default:
add(SafeCoreOwnershipDiagnosticCodes.InvalidControlFlow, "Unsupported ownership terminator.", function.Name, block.Id, -1, terminator.Source);
break;
}
}
private static void AnalyzeFunction(
SafeCoreOwnershipFunction function,
ImmutableArray<SafeCoreOwnershipPath>.Builder paths,
Action<string, string, string, int, int, SafeCoreMirSource> add,
Action step,
ref int nextPathId,
SafeCoreOwnershipOptions options)
{
var locals = new Dictionary<int, SafeCoreOwnershipLocal>();
foreach (SafeCoreOwnershipLocal local in function.Locals) locals.Add(local.Id, local);
var scopes = function.Scopes.ToDictionary(scope => scope.Id);
var blocks = function.Blocks.ToDictionary(block => block.Id);
NllLiveness? nll = options.InferNonLexicalLifetimes || options.InferNll
? BuildNllLiveness(function, locals, step)
: null;
var work = new Stack<WorkItem>();
work.Push(new WorkItem(function.EntryBlockId, new PathState(function, step), 0));
while (work.Count > 0)
{
step();
if (paths.Count >= options.MaximumPaths) throw new OwnershipLimitException();
WorkItem item = work.Pop();
if (!blocks.TryGetValue(item.BlockId, out SafeCoreOwnershipBlock? block))
{
add(SafeCoreOwnershipDiagnosticCodes.InvalidControlFlow, "A work item targets an unknown block.", function.Name, item.BlockId, -1, function.Source);
continue;
}
PathState state = item.State;
state.Visit(item.BlockId, options.MaximumBlockVisits, step);
SafeCoreMirSource escapeSource = block.Source;
void ReportEscape(int ownerId, int referenceId)
{
string ownerName = locals.TryGetValue(ownerId, out SafeCoreOwnershipLocal? owner) ? owner.Name : ownerId.ToString(CultureInfo.InvariantCulture);
string referenceName = locals.TryGetValue(referenceId, out SafeCoreOwnershipLocal? reference) ? reference.Name : referenceId.ToString(CultureInfo.InvariantCulture);
add(SafeCoreOwnershipDiagnosticCodes.Escape,
$"Reference '{referenceName}' outlives owner '{ownerName}' when its scope exits.",
function.Name, block.Id, -1, escapeSource);
}
state.EnterBlock(block.ScopeId, scopes, locals, step, ReportEscape);
for (int index = 0; index < block.Instructions.Count; index++)
{
step();
SafeCoreOwnershipInstruction instruction = block.Instructions[index];
escapeSource = instruction.Source;
if (!Apply(instruction, index, block, function, state, locals, scopes, add, step, ReportEscape)) break;
nll?.EndDeadBorrows(state, block.Id, index, locals, step);
}
SafeCoreOwnershipTerminator terminator = block.Terminator;
nll?.EndDeadBorrowsAtBlockExit(state, block.Id, block.Terminator, locals, step);
escapeSource = terminator.Source;
switch (terminator.Kind)
{
case SafeCoreOwnershipTerminatorKind.Goto:
work.Push(new WorkItem(terminator.TargetBlockId, state, item.Depth + 1));
break;
case SafeCoreOwnershipTerminatorKind.Branch:
if (!state.RequireBool(terminator.LocalId, locals, add, function, block, -1, terminator.Source)) break;
bool? knownCondition = state.KnownBoolean(terminator.LocalId);
if (knownCondition is { } known)
{
int target = known ? terminator.TargetBlockId : terminator.FalseTargetBlockId;
state.Trace.Add($"branch {target}");
work.Push(new WorkItem(target, state, item.Depth + 1));
break;
}
PathState falseState = state.Clone();
PathState trueState = state;
falseState.Trace.Add($"branch {terminator.FalseTargetBlockId}");
trueState.Trace.Add($"branch {terminator.TargetBlockId}");
work.Push(new WorkItem(terminator.FalseTargetBlockId, falseState, item.Depth + 1));
work.Push(new WorkItem(terminator.TargetBlockId, trueState, item.Depth + 1));
break;
case SafeCoreOwnershipTerminatorKind.Return:
if (terminator.LocalId >= 0 && !state.Use(terminator.LocalId, locals, add, function, block, -1, terminator.Source)) break;
if (terminator.LocalId >= 0 && locals[terminator.LocalId].IsReference && state.IsBorrowActive(terminator.LocalId) && !state.IsExternalBorrow(terminator.LocalId))
add(SafeCoreOwnershipDiagnosticCodes.Escape, "A borrowed reference cannot escape through a return.", function.Name, block.Id, -1, terminator.Source);
int? transferredLocalId = terminator.LocalId >= 0 &&
locals[terminator.LocalId].Kind == SafeCoreOwnershipKind.Move
? terminator.LocalId
: null;
state.CleanupAll(locals, scopes, step, includeValues: true, reportEscape: ReportEscape,
transferredLocalId: transferredLocalId);
state.Trace.Add("return");
paths.Add(state.ToPath(nextPathId++, function.Name, SafeCoreOwnershipOutcome.Returned));
break;
case SafeCoreOwnershipTerminatorKind.Panic:
if (function.PanicStrategy == SafeCorePanicStrategy.Unwind)
{
state.CleanupAll(locals, scopes, step, includeValues: true, reportEscape: ReportEscape);
state.Trace.Add("panic_unwind");
paths.Add(state.ToPath(nextPathId++, function.Name, SafeCoreOwnershipOutcome.Unwound));
}
else
{
state.Trace.Add("panic_abort");
paths.Add(state.ToPath(nextPathId++, function.Name, SafeCoreOwnershipOutcome.Aborted));
}
break;
case SafeCoreOwnershipTerminatorKind.Unreachable:
state.Trace.Add("unreachable");
paths.Add(state.ToPath(nextPathId++, function.Name, SafeCoreOwnershipOutcome.Unreachable));
break;
default:
add(SafeCoreOwnershipDiagnosticCodes.InvalidControlFlow, "Unsupported ownership terminator.", function.Name, block.Id, -1, terminator.Source);
break;
}
}
}
private static NllLiveness BuildNllLiveness(
SafeCoreOwnershipFunction function,
IReadOnlyDictionary<int, SafeCoreOwnershipLocal> locals,
Action step)
{
var blocks = function.Blocks.ToDictionary(block => block.Id);
var successors = new Dictionary<int, int[]>(blocks.Count);
foreach (SafeCoreOwnershipBlock block in function.Blocks)
{
step();
successors[block.Id] = Successors(block.Terminator, blocks.Count);
}
var liveIn = blocks.Keys.ToDictionary(id => id, static _ => new HashSet<int>());
var liveOut = blocks.Keys.ToDictionary(id => id, static _ => new HashSet<int>());
var predecessors = blocks.Keys.ToDictionary(id => id, static _ => new List<int>());
foreach ((int blockId, int[] targets) in successors)
{
foreach (int target in targets)
{
step();
if (predecessors.TryGetValue(target, out List<int>? incoming))
incoming.Add(blockId);
}
}
// Liveness is a finite monotone data-flow problem. A worklist avoids a
// fragile fixed round count on long CFG chains while the shared step
// budget still bounds every queue operation and union.
var queue = new Queue<int>(function.Blocks.Select(static block => block.Id).Reverse());
var queued = new HashSet<int>(queue);
while (queue.Count != 0)
{
step();
int blockId = queue.Dequeue();
queued.Remove(blockId);
SafeCoreOwnershipBlock block = blocks[blockId];
var nextOut = new HashSet<int>();
foreach (int successor in successors[blockId])
{
step();
if (liveIn.TryGetValue(successor, out HashSet<int>? successorLive))
nextOut.UnionWith(successorLive);
}
var nextIn = new HashSet<int>(nextOut);