Undefined behavior in combination of apply_scalar_binary/make_holder/to_ref_if
This issue is to collect information from https://github.com/stan-dev/math/pull/3203 in one place.
Basic summary:
On GCC, since c71dd3e (#2642), both ./test/prob/poisson/poisson_ccdf_log_00000_generated_v_test and ./test/prob/loglogistic/loglogistic_cdf_00001_generated_ffv_test fail due to taking a reference to something on the stack. The first fails under normal optimization settings consistently, the second is sporadic but can be made consistent by compiling with ASAN.
ASAN specifically blames https://github.com/stan-dev/math/blob/3a196d410415ee2cc56c0e51ec73a2e1970a08a4/stan/math/prim/prob/poisson_lccdf.hpp#L55-L57
and
https://github.com/stan-dev/math/blob/3a196d410415ee2cc56c0e51ec73a2e1970a08a4/stan/math/prim/prob/loglogistic_cdf.hpp#L116
as the problematic lines.
The discussion in https://github.com/stan-dev/math/pull/2414#issuecomment-1853299106 seems relevant, as @bgoodri was running into segfaults with a similar line in poisson_lcdf.
There are shockingly few places where we use to_ref_if on an expression which is the result of an apply_scalar_binary call, I believe it is only in:
stan/math/prim/prob/loglogistic_cdf.hpp stan/math/prim/prob/loglogistic_lpdf.hpp stan/math/prim/prob/pareto_type_2_lcdf.hpp stan/math/prim/prob/poisson_cdf.hpp stan/math/prim/prob/poisson_lccdf.hpp stan/math/prim/prob/poisson_lcdf.hpp stan/math/prim/prob/weibull_lpdf.hpp
@SteveBronder believes the correct fix is probably to make the apply_scalar_ functions and all callsites thereof into perfect forwarding templates. The other solution involves materializing a signficant number of copies which would have a performance impact