-
Notifications
You must be signed in to change notification settings - Fork 4.5k
/
SpanHelpers.Byte.cs
2419 lines (2118 loc) · 108 KB
/
SpanHelpers.Byte.cs
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
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Diagnostics;
using System.Numerics;
using System.Runtime.CompilerServices;
using System.Runtime.Intrinsics;
using System.Runtime.Intrinsics.Arm;
using System.Runtime.Intrinsics.X86;
namespace System
{
internal static partial class SpanHelpers // .Byte
{
public static int IndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return 0; // A zero-length sequence is always treated as "found" at the start of the search space.
int valueTailLength = valueLength - 1;
if (valueTailLength == 0)
return IndexOf(ref searchSpace, value, searchSpaceLength); // for single-byte values use plain IndexOf
nint offset = 0;
byte valueHead = value;
int searchSpaceMinusValueTailLength = searchSpaceLength - valueTailLength;
if (Vector128.IsHardwareAccelerated && searchSpaceMinusValueTailLength >= Vector128<byte>.Count)
{
goto SEARCH_TWO_BYTES;
}
ref byte valueTail = ref Unsafe.Add(ref value, 1);
int remainingSearchSpaceLength = searchSpaceMinusValueTailLength;
while (remainingSearchSpaceLength > 0)
{
// Do a quick search for the first element of "value".
int relativeIndex = IndexOf(ref Unsafe.Add(ref searchSpace, offset), valueHead, remainingSearchSpaceLength);
if (relativeIndex < 0)
break;
remainingSearchSpaceLength -= relativeIndex;
offset += relativeIndex;
if (remainingSearchSpaceLength <= 0)
break; // The unsearched portion is now shorter than the sequence we're looking for. So it can't be there.
// Found the first element of "value". See if the tail matches.
if (SequenceEqual(
ref Unsafe.Add(ref searchSpace, offset + 1),
ref valueTail, (nuint)(uint)valueTailLength)) // The (nuint)-cast is necessary to pick the correct overload
return (int)offset; // The tail matched. Return a successful find.
remainingSearchSpaceLength--;
offset++;
}
return -1;
// Based on http://0x80.pl/articles/simd-strfind.html#algorithm-1-generic-simd "Algorithm 1: Generic SIMD" by Wojciech Muła
// Some details about the implementation can also be found in https://github.com/dotnet/runtime/pull/63285
SEARCH_TWO_BYTES:
if (Vector256.IsHardwareAccelerated && searchSpaceMinusValueTailLength - Vector256<byte>.Count >= 0)
{
// Find the last unique (which is not equal to ch1) byte
// the algorithm is fine if both are equal, just a little bit less efficient
byte ch2Val = Unsafe.Add(ref value, valueTailLength);
nint ch1ch2Distance = valueTailLength;
while (ch2Val == value && ch1ch2Distance > 1)
ch2Val = Unsafe.Add(ref value, --ch1ch2Distance);
Vector256<byte> ch1 = Vector256.Create(value);
Vector256<byte> ch2 = Vector256.Create(ch2Val);
nint searchSpaceMinusValueTailLengthAndVector =
searchSpaceMinusValueTailLength - (nint)Vector256<byte>.Count;
do
{
Debug.Assert(offset >= 0);
// Make sure we don't go out of bounds
Debug.Assert(offset + ch1ch2Distance + Vector256<byte>.Count <= searchSpaceLength);
Vector256<byte> cmpCh2 = Vector256.Equals(ch2, Vector256.LoadUnsafe(ref searchSpace, (nuint)(offset + ch1ch2Distance)));
Vector256<byte> cmpCh1 = Vector256.Equals(ch1, Vector256.LoadUnsafe(ref searchSpace, (nuint)offset));
Vector256<byte> cmpAnd = (cmpCh1 & cmpCh2).AsByte();
// Early out: cmpAnd is all zeros
if (cmpAnd != Vector256<byte>.Zero)
{
goto CANDIDATE_FOUND;
}
LOOP_FOOTER:
offset += Vector256<byte>.Count;
if (offset == searchSpaceMinusValueTailLength)
return -1;
// Overlap with the current chunk for trailing elements
if (offset > searchSpaceMinusValueTailLengthAndVector)
offset = searchSpaceMinusValueTailLengthAndVector;
continue;
CANDIDATE_FOUND:
uint mask = cmpAnd.ExtractMostSignificantBits();
do
{
int bitPos = BitOperations.TrailingZeroCount(mask);
if (valueLength == 2 || // we already matched two bytes
SequenceEqual(
ref Unsafe.Add(ref searchSpace, offset + bitPos),
ref value, (nuint)(uint)valueLength)) // The (nuint)-cast is necessary to pick the correct overload
{
return (int)(offset + bitPos);
}
mask = BitOperations.ResetLowestSetBit(mask); // Clear the lowest set bit
} while (mask != 0);
goto LOOP_FOOTER;
} while (true);
}
else // 128bit vector path (SSE2 or AdvSimd)
{
// Find the last unique (which is not equal to ch1) byte
// the algorithm is fine if both are equal, just a little bit less efficient
byte ch2Val = Unsafe.Add(ref value, valueTailLength);
int ch1ch2Distance = valueTailLength;
while (ch2Val == value && ch1ch2Distance > 1)
ch2Val = Unsafe.Add(ref value, --ch1ch2Distance);
Vector128<byte> ch1 = Vector128.Create(value);
Vector128<byte> ch2 = Vector128.Create(ch2Val);
nint searchSpaceMinusValueTailLengthAndVector =
searchSpaceMinusValueTailLength - (nint)Vector128<byte>.Count;
do
{
Debug.Assert(offset >= 0);
// Make sure we don't go out of bounds
Debug.Assert(offset + ch1ch2Distance + Vector128<byte>.Count <= searchSpaceLength);
Vector128<byte> cmpCh2 = Vector128.Equals(ch2, Vector128.LoadUnsafe(ref searchSpace, (nuint)(offset + ch1ch2Distance)));
Vector128<byte> cmpCh1 = Vector128.Equals(ch1, Vector128.LoadUnsafe(ref searchSpace, (nuint)offset));
Vector128<byte> cmpAnd = (cmpCh1 & cmpCh2).AsByte();
// Early out: cmpAnd is all zeros
if (cmpAnd != Vector128<byte>.Zero)
{
goto CANDIDATE_FOUND;
}
LOOP_FOOTER:
offset += Vector128<byte>.Count;
if (offset == searchSpaceMinusValueTailLength)
return -1;
// Overlap with the current chunk for trailing elements
if (offset > searchSpaceMinusValueTailLengthAndVector)
offset = searchSpaceMinusValueTailLengthAndVector;
continue;
CANDIDATE_FOUND:
uint mask = cmpAnd.ExtractMostSignificantBits();
do
{
int bitPos = BitOperations.TrailingZeroCount(mask);
if (valueLength == 2 || // we already matched two bytes
SequenceEqual(
ref Unsafe.Add(ref searchSpace, offset + bitPos),
ref value, (nuint)(uint)valueLength)) // The (nuint)-cast is necessary to pick the correct overload
{
return (int)(offset + bitPos);
}
// Clear the lowest set bit
mask = BitOperations.ResetLowestSetBit(mask);
} while (mask != 0);
goto LOOP_FOOTER;
} while (true);
}
}
public static int LastIndexOf(ref byte searchSpace, int searchSpaceLength, ref byte value, int valueLength)
{
Debug.Assert(searchSpaceLength >= 0);
Debug.Assert(valueLength >= 0);
if (valueLength == 0)
return searchSpaceLength; // A zero-length sequence is always treated as "found" at the end of the search space.
int valueTailLength = valueLength - 1;
if (valueTailLength == 0)
return LastIndexOf(ref searchSpace, value, searchSpaceLength); // for single-byte values use plain LastIndexOf
int offset = 0;
byte valueHead = value;
int searchSpaceMinusValueTailLength = searchSpaceLength - valueTailLength;
if (Vector128.IsHardwareAccelerated && searchSpaceMinusValueTailLength >= Vector128<byte>.Count)
{
goto SEARCH_TWO_BYTES;
}
ref byte valueTail = ref Unsafe.Add(ref value, 1);
while (true)
{
Debug.Assert(0 <= offset && offset <= searchSpaceLength); // Ensures no deceptive underflows in the computation of "remainingSearchSpaceLength".
int remainingSearchSpaceLength = searchSpaceLength - offset - valueTailLength;
if (remainingSearchSpaceLength <= 0)
break; // The unsearched portion is now shorter than the sequence we're looking for. So it can't be there.
// Do a quick search for the first element of "value".
int relativeIndex = LastIndexOf(ref searchSpace, valueHead, remainingSearchSpaceLength);
if (relativeIndex < 0)
break;
// Found the first element of "value". See if the tail matches.
if (SequenceEqual(
ref Unsafe.Add(ref searchSpace, relativeIndex + 1),
ref valueTail, (nuint)(uint)valueTailLength)) // The (nuint)-cast is necessary to pick the correct overload
return relativeIndex; // The tail matched. Return a successful find.
offset += remainingSearchSpaceLength - relativeIndex;
}
return -1;
// Based on http://0x80.pl/articles/simd-strfind.html#algorithm-1-generic-simd "Algorithm 1: Generic SIMD" by Wojciech Muła
// Some details about the implementation can also be found in https://github.com/dotnet/runtime/pull/63285
SEARCH_TWO_BYTES:
if (Vector256.IsHardwareAccelerated && searchSpaceMinusValueTailLength >= Vector256<byte>.Count)
{
offset = searchSpaceMinusValueTailLength - Vector256<byte>.Count;
// Find the last unique (which is not equal to ch1) byte
// the algorithm is fine if both are equal, just a little bit less efficient
byte ch2Val = Unsafe.Add(ref value, valueTailLength);
int ch1ch2Distance = valueTailLength;
while (ch2Val == value && ch1ch2Distance > 1)
ch2Val = Unsafe.Add(ref value, --ch1ch2Distance);
Vector256<byte> ch1 = Vector256.Create(value);
Vector256<byte> ch2 = Vector256.Create(ch2Val);
do
{
Vector256<byte> cmpCh1 = Vector256.Equals(ch1, Vector256.LoadUnsafe(ref searchSpace, (nuint)offset));
Vector256<byte> cmpCh2 = Vector256.Equals(ch2, Vector256.LoadUnsafe(ref searchSpace, (nuint)(offset + ch1ch2Distance)));
Vector256<byte> cmpAnd = (cmpCh1 & cmpCh2).AsByte();
// Early out: cmpAnd is all zeros
if (cmpAnd != Vector256<byte>.Zero)
{
uint mask = cmpAnd.ExtractMostSignificantBits();
do
{
// unlike IndexOf, here we use LZCNT to process matches starting from the end
int bitPos = 31 - BitOperations.LeadingZeroCount(mask);
if (valueLength == 2 || // we already matched two bytes
SequenceEqual(
ref Unsafe.Add(ref searchSpace, offset + bitPos),
ref value, (nuint)(uint)valueLength)) // The (nuint)-cast is necessary to pick the correct overload
{
return bitPos + offset;
}
// Clear the highest set bit.
mask = BitOperations.ResetBit(mask, bitPos);
} while (mask != 0);
}
offset -= Vector256<byte>.Count;
if (offset == -Vector256<byte>.Count)
return -1;
// Overlap with the current chunk if there is not enough room for the next one
if (offset < 0)
offset = 0;
} while (true);
}
else // 128bit vector path (SSE2 or AdvSimd)
{
offset = searchSpaceMinusValueTailLength - Vector128<byte>.Count;
// Find the last unique (which is not equal to ch1) byte
// the algorithm is fine if both are equal, just a little bit less efficient
byte ch2Val = Unsafe.Add(ref value, valueTailLength);
int ch1ch2Distance = valueTailLength;
while (ch2Val == value && ch1ch2Distance > 1)
ch2Val = Unsafe.Add(ref value, --ch1ch2Distance);
Vector128<byte> ch1 = Vector128.Create(value);
Vector128<byte> ch2 = Vector128.Create(ch2Val);
do
{
Vector128<byte> cmpCh1 = Vector128.Equals(ch1, Vector128.LoadUnsafe(ref searchSpace, (nuint)offset));
Vector128<byte> cmpCh2 = Vector128.Equals(ch2, Vector128.LoadUnsafe(ref searchSpace, (nuint)(offset + ch1ch2Distance)));
Vector128<byte> cmpAnd = (cmpCh1 & cmpCh2).AsByte();
// Early out: cmpAnd is all zeros
// it's especially important for ARM where ExtractMostSignificantBits is not cheap
if (cmpAnd != Vector128<byte>.Zero)
{
uint mask = cmpAnd.ExtractMostSignificantBits();
do
{
// unlike IndexOf, here we use LZCNT to process matches starting from the end
int bitPos = 31 - BitOperations.LeadingZeroCount(mask);
if (valueLength == 2 || // we already matched two bytes
SequenceEqual(
ref Unsafe.Add(ref searchSpace, offset + bitPos),
ref value, (nuint)(uint)valueLength)) // The (nuint)-cast is necessary to pick the correct overload
{
return bitPos + offset;
}
// Clear the highest set bit.
mask = BitOperations.ResetBit(mask, bitPos);
} while (mask != 0);
}
offset -= Vector128<byte>.Count;
if (offset == -Vector128<byte>.Count)
return -1;
// Overlap with the current chunk if there is not enough room for the next one
if (offset < 0)
offset = 0;
} while (true);
}
}
// Adapted from IndexOf(...)
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static bool Contains(ref byte searchSpace, byte value, int length)
{
Debug.Assert(length >= 0);
uint uValue = value; // Use uint for comparisons to avoid unnecessary 8->32 extensions
nuint offset = 0; // Use nuint for arithmetic to avoid unnecessary 64->32->64 truncations
nuint lengthToExamine = (uint)length;
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
lengthToExamine = UnalignedCountVector(ref searchSpace);
}
while (lengthToExamine >= 8)
{
lengthToExamine -= 8;
ref byte start = ref Unsafe.AddByteOffset(ref searchSpace, offset);
if (uValue == Unsafe.AddByteOffset(ref start, 0) ||
uValue == Unsafe.AddByteOffset(ref start, 1) ||
uValue == Unsafe.AddByteOffset(ref start, 2) ||
uValue == Unsafe.AddByteOffset(ref start, 3) ||
uValue == Unsafe.AddByteOffset(ref start, 4) ||
uValue == Unsafe.AddByteOffset(ref start, 5) ||
uValue == Unsafe.AddByteOffset(ref start, 6) ||
uValue == Unsafe.AddByteOffset(ref start, 7))
{
goto Found;
}
offset += 8;
}
if (lengthToExamine >= 4)
{
lengthToExamine -= 4;
ref byte start = ref Unsafe.AddByteOffset(ref searchSpace, offset);
if (uValue == Unsafe.AddByteOffset(ref start, 0) ||
uValue == Unsafe.AddByteOffset(ref start, 1) ||
uValue == Unsafe.AddByteOffset(ref start, 2) ||
uValue == Unsafe.AddByteOffset(ref start, 3))
{
goto Found;
}
offset += 4;
}
while (lengthToExamine > 0)
{
lengthToExamine--;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset))
goto Found;
offset++;
}
if (Vector.IsHardwareAccelerated && (offset < (uint)length))
{
lengthToExamine = ((uint)length - offset) & (nuint)~(Vector<byte>.Count - 1);
Vector<byte> values = new(value);
Vector<byte> matches;
while (offset < lengthToExamine)
{
matches = Vector.Equals(values, LoadVector(ref searchSpace, offset));
if (matches == Vector<byte>.Zero)
{
offset += (nuint)Vector<byte>.Count;
continue;
}
goto Found;
}
// The total length is at least Vector<byte>.Count, so instead of falling back to a
// sequential scan for the remainder, we check the vector read from the end -- note: unaligned read necessary.
// We do this only if at least one element is left.
if (offset < (uint)length)
{
offset = (uint)(length - Vector<byte>.Count);
matches = Vector.Equals(values, LoadVector(ref searchSpace, offset));
if (matches != Vector<byte>.Zero)
{
goto Found;
}
}
}
return false;
Found:
return true;
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static unsafe int IndexOf(ref byte searchSpace, byte value, int length)
{
Debug.Assert(length >= 0);
uint uValue = value; // Use uint for comparisons to avoid unnecessary 8->32 extensions
nuint offset = 0; // Use nuint for arithmetic to avoid unnecessary 64->32->64 truncations
nuint lengthToExamine = (nuint)(uint)length;
if (Sse2.IsSupported || AdvSimd.Arm64.IsSupported)
{
// Avx2 branch also operates on Sse2 sizes, so check is combined.
if (length >= Vector128<byte>.Count * 2)
{
lengthToExamine = UnalignedCountVector128(ref searchSpace);
}
}
else if (Vector.IsHardwareAccelerated)
{
if (length >= Vector<byte>.Count * 2)
{
lengthToExamine = UnalignedCountVector(ref searchSpace);
}
}
SequentialScan:
while (lengthToExamine >= 8)
{
lengthToExamine -= 8;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset))
goto Found;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset + 1))
goto Found1;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset + 2))
goto Found2;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset + 3))
goto Found3;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset + 4))
goto Found4;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset + 5))
goto Found5;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset + 6))
goto Found6;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset + 7))
goto Found7;
offset += 8;
}
if (lengthToExamine >= 4)
{
lengthToExamine -= 4;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset))
goto Found;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset + 1))
goto Found1;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset + 2))
goto Found2;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset + 3))
goto Found3;
offset += 4;
}
while (lengthToExamine > 0)
{
lengthToExamine -= 1;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset))
goto Found;
offset += 1;
}
// We get past SequentialScan only if IsHardwareAccelerated or intrinsic .IsSupported is true; and remain length is greater than Vector length.
// However, we still have the redundant check to allow the JIT to see that the code is unreachable and eliminate it when the platform does not
// have hardware accelerated. After processing Vector lengths we return to SequentialScan to finish any remaining.
if (Avx2.IsSupported)
{
if (offset < (nuint)(uint)length)
{
if ((((nuint)(uint)Unsafe.AsPointer(ref searchSpace) + offset) & (nuint)(Vector256<byte>.Count - 1)) != 0)
{
// Not currently aligned to Vector256 (is aligned to Vector128); this can cause a problem for searches
// with no upper bound e.g. String.strlen.
// Start with a check on Vector128 to align to Vector256, before moving to processing Vector256.
// This ensures we do not fault across memory pages while searching for an end of string.
Vector128<byte> values = Vector128.Create(value);
Vector128<byte> search = LoadVector128(ref searchSpace, offset);
// Same method as below
int matches = Sse2.MoveMask(Sse2.CompareEqual(values, search));
if (matches == 0)
{
// Zero flags set so no matches
offset += (nuint)Vector128<byte>.Count;
}
else
{
// Find bitflag offset of first match and add to current offset
return (int)(offset + (uint)BitOperations.TrailingZeroCount(matches));
}
}
lengthToExamine = GetByteVector256SpanLength(offset, length);
if (lengthToExamine > offset)
{
Vector256<byte> values = Vector256.Create(value);
do
{
Vector256<byte> search = LoadVector256(ref searchSpace, offset);
int matches = Avx2.MoveMask(Avx2.CompareEqual(values, search));
// Note that MoveMask has converted the equal vector elements into a set of bit flags,
// So the bit position in 'matches' corresponds to the element offset.
if (matches == 0)
{
// Zero flags set so no matches
offset += (nuint)Vector256<byte>.Count;
continue;
}
// Find bitflag offset of first match and add to current offset
return (int)(offset + (uint)BitOperations.TrailingZeroCount(matches));
} while (lengthToExamine > offset);
}
lengthToExamine = GetByteVector128SpanLength(offset, length);
if (lengthToExamine > offset)
{
Vector128<byte> values = Vector128.Create(value);
Vector128<byte> search = LoadVector128(ref searchSpace, offset);
// Same method as above
int matches = Sse2.MoveMask(Sse2.CompareEqual(values, search));
if (matches == 0)
{
// Zero flags set so no matches
offset += (nuint)Vector128<byte>.Count;
}
else
{
// Find bitflag offset of first match and add to current offset
return (int)(offset + (uint)BitOperations.TrailingZeroCount(matches));
}
}
if (offset < (nuint)(uint)length)
{
lengthToExamine = ((nuint)(uint)length - offset);
goto SequentialScan;
}
}
}
else if (Sse2.IsSupported)
{
if (offset < (nuint)(uint)length)
{
lengthToExamine = GetByteVector128SpanLength(offset, length);
Vector128<byte> values = Vector128.Create(value);
while (lengthToExamine > offset)
{
Vector128<byte> search = LoadVector128(ref searchSpace, offset);
// Same method as above
int matches = Sse2.MoveMask(Sse2.CompareEqual(values, search));
if (matches == 0)
{
// Zero flags set so no matches
offset += (nuint)Vector128<byte>.Count;
continue;
}
// Find bitflag offset of first match and add to current offset
return (int)(offset + (uint)BitOperations.TrailingZeroCount(matches));
}
if (offset < (nuint)(uint)length)
{
lengthToExamine = ((nuint)(uint)length - offset);
goto SequentialScan;
}
}
}
else if (AdvSimd.Arm64.IsSupported)
{
if (offset < (nuint)(uint)length)
{
lengthToExamine = GetByteVector128SpanLength(offset, length);
Vector128<byte> values = Vector128.Create(value);
while (lengthToExamine > offset)
{
Vector128<byte> search = LoadVector128(ref searchSpace, offset);
Vector128<byte> compareResult = AdvSimd.CompareEqual(values, search);
if (compareResult == Vector128<byte>.Zero)
{
offset += (nuint)Vector128<byte>.Count;
continue;
}
return (int)(offset + FindFirstMatchedLane(compareResult));
}
if (offset < (nuint)(uint)length)
{
lengthToExamine = ((nuint)(uint)length - offset);
goto SequentialScan;
}
}
}
else if (Vector.IsHardwareAccelerated)
{
if (offset < (nuint)(uint)length)
{
lengthToExamine = GetByteVectorSpanLength(offset, length);
Vector<byte> values = new Vector<byte>(value);
while (lengthToExamine > offset)
{
var matches = Vector.Equals(values, LoadVector(ref searchSpace, offset));
if (Vector<byte>.Zero.Equals(matches))
{
offset += (nuint)Vector<byte>.Count;
continue;
}
// Find offset of first match and add to current offset
return (int)offset + LocateFirstFoundByte(matches);
}
if (offset < (nuint)(uint)length)
{
lengthToExamine = ((nuint)(uint)length - offset);
goto SequentialScan;
}
}
}
return -1;
Found: // Workaround for https://github.com/dotnet/runtime/issues/8795
return (int)offset;
Found1:
return (int)(offset + 1);
Found2:
return (int)(offset + 2);
Found3:
return (int)(offset + 3);
Found4:
return (int)(offset + 4);
Found5:
return (int)(offset + 5);
Found6:
return (int)(offset + 6);
Found7:
return (int)(offset + 7);
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static int LastIndexOf(ref byte searchSpace, byte value, int length)
{
Debug.Assert(length >= 0);
uint uValue = value; // Use uint for comparisons to avoid unnecessary 8->32 extensions
nuint offset = (nuint)(uint)length; // Use nuint for arithmetic to avoid unnecessary 64->32->64 truncations
nuint lengthToExamine = (nuint)(uint)length;
if (Vector.IsHardwareAccelerated && length >= Vector<byte>.Count * 2)
{
lengthToExamine = UnalignedCountVectorFromEnd(ref searchSpace, length);
}
SequentialScan:
while (lengthToExamine >= 8)
{
lengthToExamine -= 8;
offset -= 8;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset + 7))
goto Found7;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset + 6))
goto Found6;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset + 5))
goto Found5;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset + 4))
goto Found4;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset + 3))
goto Found3;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset + 2))
goto Found2;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset + 1))
goto Found1;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset))
goto Found;
}
if (lengthToExamine >= 4)
{
lengthToExamine -= 4;
offset -= 4;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset + 3))
goto Found3;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset + 2))
goto Found2;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset + 1))
goto Found1;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset))
goto Found;
}
while (lengthToExamine > 0)
{
lengthToExamine -= 1;
offset -= 1;
if (uValue == Unsafe.AddByteOffset(ref searchSpace, offset))
goto Found;
}
if (Vector.IsHardwareAccelerated && (offset > 0))
{
lengthToExamine = (offset & (nuint)~(Vector<byte>.Count - 1));
Vector<byte> values = new Vector<byte>(value);
while (lengthToExamine > (nuint)(Vector<byte>.Count - 1))
{
var matches = Vector.Equals(values, LoadVector(ref searchSpace, offset - (nuint)Vector<byte>.Count));
if (Vector<byte>.Zero.Equals(matches))
{
offset -= (nuint)Vector<byte>.Count;
lengthToExamine -= (nuint)Vector<byte>.Count;
continue;
}
// Find offset of first match and add to current offset
return (int)(offset) - Vector<byte>.Count + LocateLastFoundByte(matches);
}
if (offset > 0)
{
lengthToExamine = offset;
goto SequentialScan;
}
}
return -1;
Found: // Workaround for https://github.com/dotnet/runtime/issues/8795
return (int)offset;
Found1:
return (int)(offset + 1);
Found2:
return (int)(offset + 2);
Found3:
return (int)(offset + 3);
Found4:
return (int)(offset + 4);
Found5:
return (int)(offset + 5);
Found6:
return (int)(offset + 6);
Found7:
return (int)(offset + 7);
}
[MethodImpl(MethodImplOptions.AggressiveOptimization)]
public static int IndexOfAny(ref byte searchSpace, byte value0, byte value1, int length)
{
Debug.Assert(length >= 0);
uint uValue0 = value0; // Use uint for comparisons to avoid unnecessary 8->32 extensions
uint uValue1 = value1; // Use uint for comparisons to avoid unnecessary 8->32 extensions
nuint offset = 0; // Use nuint for arithmetic to avoid unnecessary 64->32->64 truncations
nuint lengthToExamine = (nuint)(uint)length;
if (Sse2.IsSupported || AdvSimd.Arm64.IsSupported)
{
// Avx2 branch also operates on Sse2 sizes, so check is combined.
nint vectorDiff = (nint)length - Vector128<byte>.Count;
if (vectorDiff >= 0)
{
// >= Sse2 intrinsics are supported, and length is enough to use them so use that path.
// We jump forward to the intrinsics at the end of the method so a naive branch predict
// will choose the non-intrinsic path so short lengths which don't gain anything aren't
// overly disadvantaged by having to jump over a lot of code. Whereas the longer lengths
// more than make this back from the intrinsics.
lengthToExamine = (nuint)vectorDiff;
goto IntrinsicsCompare;
}
}
else if (Vector.IsHardwareAccelerated)
{
// Calculate lengthToExamine here for test, as it is used later
nint vectorDiff = (nint)length - Vector<byte>.Count;
if (vectorDiff >= 0)
{
// Similar as above for Vector version
lengthToExamine = (nuint)vectorDiff;
goto IntrinsicsCompare;
}
}
uint lookUp;
while (lengthToExamine >= 8)
{
lengthToExamine -= 8;
lookUp = Unsafe.AddByteOffset(ref searchSpace, offset);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found;
lookUp = Unsafe.AddByteOffset(ref searchSpace, offset + 1);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found1;
lookUp = Unsafe.AddByteOffset(ref searchSpace, offset + 2);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found2;
lookUp = Unsafe.AddByteOffset(ref searchSpace, offset + 3);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found3;
lookUp = Unsafe.AddByteOffset(ref searchSpace, offset + 4);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found4;
lookUp = Unsafe.AddByteOffset(ref searchSpace, offset + 5);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found5;
lookUp = Unsafe.AddByteOffset(ref searchSpace, offset + 6);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found6;
lookUp = Unsafe.AddByteOffset(ref searchSpace, offset + 7);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found7;
offset += 8;
}
if (lengthToExamine >= 4)
{
lengthToExamine -= 4;
lookUp = Unsafe.AddByteOffset(ref searchSpace, offset);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found;
lookUp = Unsafe.AddByteOffset(ref searchSpace, offset + 1);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found1;
lookUp = Unsafe.AddByteOffset(ref searchSpace, offset + 2);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found2;
lookUp = Unsafe.AddByteOffset(ref searchSpace, offset + 3);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found3;
offset += 4;
}
while (lengthToExamine > 0)
{
lookUp = Unsafe.AddByteOffset(ref searchSpace, offset);
if (uValue0 == lookUp || uValue1 == lookUp)
goto Found;
offset += 1;
lengthToExamine -= 1;
}
NotFound:
return -1;
Found: // Workaround for https://github.com/dotnet/runtime/issues/8795
return (int)offset;
Found1:
return (int)(offset + 1);
Found2:
return (int)(offset + 2);
Found3:
return (int)(offset + 3);
Found4:
return (int)(offset + 4);
Found5:
return (int)(offset + 5);
Found6:
return (int)(offset + 6);
Found7:
return (int)(offset + 7);
IntrinsicsCompare:
// When we move into a Vectorized block, we process everything of Vector size;
// and then for any remainder we do a final compare of Vector size but starting at
// the end and forwards, which may overlap on an earlier compare.
// We include the Supported check again here even though path will not be taken, so the asm isn't generated if not supported.
if (Sse2.IsSupported)
{
int matches;
if (Avx2.IsSupported)
{
Vector256<byte> search;
// Guard as we may only have a valid size for Vector128; when we will move to the Sse2
// We have already subtracted Vector128<byte>.Count from lengthToExamine so compare against that
// to see if we have double the size for Vector256<byte>.Count
if (lengthToExamine >= (nuint)Vector128<byte>.Count)
{
Vector256<byte> values0 = Vector256.Create(value0);
Vector256<byte> values1 = Vector256.Create(value1);
// Subtract Vector128<byte>.Count so we have now subtracted Vector256<byte>.Count
lengthToExamine -= (nuint)Vector128<byte>.Count;
// First time this checks again against 0, however we will move into final compare if it fails.
while (lengthToExamine > offset)
{
search = LoadVector256(ref searchSpace, offset);
// Bitwise Or to combine the flagged matches for the second value to our match flags
matches = Avx2.MoveMask(
Avx2.Or(
Avx2.CompareEqual(values0, search),
Avx2.CompareEqual(values1, search)));
// Note that MoveMask has converted the equal vector elements into a set of bit flags,
// So the bit position in 'matches' corresponds to the element offset.
if (matches == 0)
{
// None matched
offset += (nuint)Vector256<byte>.Count;
continue;
}
goto IntrinsicsMatch;
}
// Move to Vector length from end for final compare
search = LoadVector256(ref searchSpace, lengthToExamine);
offset = lengthToExamine;
// Same as method as above
matches = Avx2.MoveMask(
Avx2.Or(
Avx2.CompareEqual(values0, search),
Avx2.CompareEqual(values1, search)));
if (matches == 0)
{
// None matched
goto NotFound;
}
goto IntrinsicsMatch;
}
}
// Initial size check was done on method entry.
Debug.Assert(length >= Vector128<byte>.Count);
{
Vector128<byte> search;
Vector128<byte> values0 = Vector128.Create(value0);
Vector128<byte> values1 = Vector128.Create(value1);
// First time this checks against 0 and we will move into final compare if it fails.
while (lengthToExamine > offset)
{
search = LoadVector128(ref searchSpace, offset);
matches = Sse2.MoveMask(
Sse2.Or(
Sse2.CompareEqual(values0, search),
Sse2.CompareEqual(values1, search))
.AsByte());
// Note that MoveMask has converted the equal vector elements into a set of bit flags,
// So the bit position in 'matches' corresponds to the element offset.
if (matches == 0)