|
| 1 | +using System; |
| 2 | +using System.Runtime.CompilerServices; |
| 3 | + |
| 4 | +namespace BMI1Intrinsics |
| 5 | +{ |
| 6 | + internal class Program |
| 7 | + { |
| 8 | + private static int _errorCode = 100; |
| 9 | + |
| 10 | + static int Main(string[] args) |
| 11 | + { |
| 12 | + // bmi1 expression are folded to to hwintrinsics that return identical results |
| 13 | + |
| 14 | + var values = new (uint input1, uint input2, uint andnExpected, uint blsiExpected, uint blsrExpected, uint blmskExpected)[] { |
| 15 | + (0, 0, 0, 0 ,0 ,0), |
| 16 | + (1, 0, 1, 1 ,0 ,0xfffffffe), |
| 17 | + (uint.MaxValue / 2, 0, 0x7fffffff, 0x1 ,0x7ffffffe ,0xfffffffe), |
| 18 | + ((uint.MaxValue / 2) - 1, 0, 0x7FFFFFFE, 2 ,0x7FFFFFFC ,0xFFFFFFFC), |
| 19 | + ((uint.MaxValue / 2) + 1, 0, 0x80000000, 0x80000000 ,0 ,0), |
| 20 | + (uint.MaxValue - 1, 0, 0xFFFFFFFE, 2 ,0xFFFFFFFC ,0xFFFFFFFC), |
| 21 | + (uint.MaxValue , 0, 0xFFFFFFFF, 1 ,0xFFFFFFFE ,0xFFFFFFFE), |
| 22 | + (0xAAAAAAAA,0xAAAAAAAA,0,2,0xAAAAAAA8,0xFFFFFFFC), |
| 23 | + (0xAAAAAAAA,0x55555555,0xAAAAAAAA,2,0xAAAAAAA8,0xFFFFFFFC), |
| 24 | + }; |
| 25 | + |
| 26 | + foreach (var value in values) |
| 27 | + { |
| 28 | + Test(value.input1, AndNot(value.input1, value.input2), value.andnExpected, nameof(AndNot)); |
| 29 | + Test(value.input1, ExtractLowestSetIsolatedBit(value.input1), value.blsiExpected, nameof(ExtractLowestSetIsolatedBit)); |
| 30 | + Test(value.input1, ResetLowestSetBit(value.input1), value.blsrExpected, nameof(ResetLowestSetBit)); |
| 31 | + Test(value.input1, GetMaskUpToLowestSetBit(value.input1), value.blmskExpected, nameof(GetMaskUpToLowestSetBit)); |
| 32 | + } |
| 33 | + |
| 34 | + return _errorCode; |
| 35 | + } |
| 36 | + |
| 37 | + [MethodImpl(MethodImplOptions.NoInlining)] |
| 38 | + private static uint AndNot(uint x, uint y) => x & (~y); // bmi1 andn |
| 39 | + |
| 40 | + [MethodImpl(MethodImplOptions.NoInlining)] |
| 41 | + private static uint ExtractLowestSetIsolatedBit(uint x) => (uint)(x & (-x)); // bmi1 blsi |
| 42 | + |
| 43 | + [MethodImpl(MethodImplOptions.NoInlining)] |
| 44 | + private static uint ResetLowestSetBit(uint x) => x & (x - 1); // bmi1 blsr |
| 45 | + |
| 46 | + [MethodImpl(MethodImplOptions.NoInlining)] |
| 47 | + private static uint GetMaskUpToLowestSetBit(uint x) => (uint)(x ^ (-x)); // bmi1 blmsk |
| 48 | + |
| 49 | + [MethodImpl(MethodImplOptions.NoInlining)] |
| 50 | + private static void Test(uint input, uint output, uint expected,string callerName) |
| 51 | + { |
| 52 | + if (output != expected) |
| 53 | + { |
| 54 | + Console.WriteLine($"{callerName} failed."); |
| 55 | + Console.WriteLine($"Input: {input:X}"); |
| 56 | + Console.WriteLine($"Output: {output:X}"); |
| 57 | + Console.WriteLine($"Expected: {expected:X}"); |
| 58 | + |
| 59 | + _errorCode++; |
| 60 | + } |
| 61 | + } |
| 62 | + } |
| 63 | +} |
0 commit comments