> You can tell the compiler that this is safe either by loading both values before the if

As I mentioned in my other email, this is true (and I believe the best work around). My two objections are that it's now two more lines of code. The other is that taking both paths is no longer an available optimization, but instead part of the code. So, even when it doesn't vectorize, there's now an additional load that happens for all compilations.

On Thu, Oct 31, 2024 at 1:15 PM Jeremy Rifkin <rifkin.jer@gmail.com> wrote:
Hi,

> In this code, if the compiler knew that accessing array[i + 1] on the false path of conditionwas safe

You can tell the compiler that this is safe either by loading both values before the if or by using std::assume (or various built-ins before C++23). I am dubious, though, that a compiler would or could vectorize the example you provided even with this information.

Cheers
Jeremy


On Thu, Oct 31, 2024 at 13:40 Matthew Kolbe via Std-Proposals <std-proposals@lists.isocpp.org> wrote:
I am proposing an attribute to aid compilers in vectorizing conditional code more effectively. In current scenarios, compilers sometimes hesitate to vectorize code containing conditional branches, as they cannot guarantee that accessing data on the “false path” won’t trigger undefined behavior (UB). This results in missed vectorization opportunities, particularly when working with SIMD operations, where executing both branches and blending the result is often optimal.

Here's an example

```cpp
int a;
if (condition) {
    a = array[i];
} else {
    a = array[i+1]
}
```

In this code, if the compiler knew that accessing array[i + 1] on the false path of condition was safe—even if that path isn’t executed—it could vectorize this operation by evaluating both paths and blending the results. However, the lack of clarity regarding UB in these cases can prevent this optimization.

Proposed Solution:

To resolve this, I propose a new attribute, [[false_path_is_defined_behavior]], which would guarantee that accessing the false path’s value does not invoke UB, thereby enabling compilers to vectorize more confidently.

Example with the proposed attribute:


```cpp
int a;
if (condition) [[false_path_is_defined_behavior]] {
    a = array[i];
} else {
    a = array[i+1]
}
```

This attribute would provide compilers the information needed to safely perform vectorization in SIMD-friendly loops, improving performance without additional programmer intervention.

I would be grateful for any feedback from the committee on this concept and its feasibility.

Thank you very much for your time and consideration.


Best,



--
Matthew P. Kolbe
--
Std-Proposals mailing list
Std-Proposals@lists.isocpp.org
https://lists.isocpp.org/mailman/listinfo.cgi/std-proposals


--
Matthew P. Kolbe
(312) 218-6595
matthew.kolbe@gmail.com