[Support][Error] Add a 'cantFail' utility function for known-safe calls to
fallible functions.
Some fallible functions (those returning Error or Expected<T>) may only fail
for a subset of their inputs. For example, a "safe" square root function will
succeed for all finite positive inputs:
Expected<double> safeSqrt(double d) {
if (d < 0 && !isnan(d) && !isinf(d))
return make_error<...>("Cannot sqrt -ve values, nans or infs");
return sqrt(d);
}
At a safe callsite for such a function, checking the error return value is
redundant:
if (auto ValOrErr = safeSqrt(42.0)) {
// use *ValOrErr.
} else
llvm_unreachable("safeSqrt should always succeed for +ve values");
The cantFail function wraps this check and extracts the contained value,
simplifying control flow:
double Result = cantFail(safeSqrt(42.0));
This function should be used with care: it is a programmatic error to wrap a
call with cantFail if it can in fact fail. For debug builds this will
result in llvm_unreachable being called. For release builds the behavior is
undefined.
Use of this function is likely to be rare in library code, but more common
for tool and unit-test code where inputs and mock functions may be known to be
safe.
llvm-svn: 296384