For non-SSE code, as answered in the following question (No overflow exception for int in C#?) adding a checked
section around addition, throws an overflow exception when adding Int64.MaxValue and 1. However, surrounding SSE addition with checked
section does not seem to throw an overflow exception for long[] arrLong = new long[] { 5, 7, 16, Int64.MaxValue, 3, 1 };
. I believe most SSE instructions use saturate math, where they reach Int64.MaxValue
and don't go past it and never wrap around to negatives. Is there any way in C# to throw an overflow exception for SSE addition, or is it not possible because the CPU may not support raising a an overflow flag?
The code below shows my C# SSE implementation of summation of long[] using SSE. The result is a negative number for the array above, as positives wrap around and do not saturate, as C# must be using that version of the SSE instruction (as there are two versions: one that wraps and one that saturates). Don't know if C# allows developers to choose which version to use. Only the serial code portion of the code below throws an overflow exception, but the SSE portion doesn't.
using System.Numerics;
private static long SumSseInner(this long[] arrayToSum, int l, int r)
{
var sumVector = new Vector<long>();
int sseIndexEnd = l + ((r - l + 1) / Vector<long>.Count) * Vector<long>.Count;
int i;
for (i = l; i < sseIndexEnd; i += Vector<long>.Count)
{
var inVector = new Vector<long>(arrayToSum, i);
checked
{
sumVector += inVector;
}
}
long overallSum = 0;
for (; i <= r; i++)
{
checked
{
overallSum += arrayToSum[i];
}
}
for (i = 0; i < Vector<long>.Count; i++)
{
checked
{
overallSum += sumVector[i];
}
}
return overallSum;
}