<table border="1" cellspacing="0" cellpadding="8">
    <tr>
        <th>Issue</th>
        <td>
            <a href=https://github.com/llvm/llvm-project/issues/108600>108600</a>
        </td>
    </tr>

    <tr>
        <th>Summary</th>
        <td>
            [libc++] The representation of bounded iterators inhibits Clang vectorization
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            libc++,
            hardening
      </td>
    </tr>

    <tr>
      <th>Assignees</th>
      <td>
      </td>
    </tr>

    <tr>
      <th>Reporter</th>
      <td>
          ldionne
      </td>
    </tr>
</table>

<pre>
    With test code like this:

```
template <class Span>
__attribute__((noinline)) int testForLoop(Span span) {
  int sum = 0;
  for (auto it = span.begin() + 1; it < span.end(); ++it) {
 sum += *it - *(it - 1);
  }
  return sum;
}
```

Without bounded iterators, Clang vectorizes this code. When we enable bounded iterators though, Clang isn't able to vectorize anymore.

For information, the current representation of `__bounded_iter` is as follows:

```
_Iterator __current_;       // current iterator
_Iterator __begin_, __end_; // valid range represented as [begin, end]
```

I played around with changing the representation of `__bounded_iter` to see if that could make any difference, and it looks like the following representation instead allows Clang to vectorize this code:

```
size_t __current_;       // current index inside [begin, end]
_Iterator __begin_, __end_; // valid range represented as [begin, end]
```

Funnily enough, it seems that this representation leads to *better* code than the version that doesn't use bounded iterators!

Godbolt with a pointer (status quo): https://godbolt.org/z/efa77anqK
Godbolt with the index: https://godbolt.org/z/f9n5zs8sv
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJy8VU1v4zYQ_TX0ZbCGNPKHdNAhtuti0d5aYI8CJY4kNjTpJUdOk19fkLKTbJJuc2oQSLKG8-bxPc5IhqAHS1SL9U6sDws58eh8bZR21tKideqx_qZ5BKbA0DlFYPQ9AY86iOJOZAeR3a6b7PqffjKdzkYygSj2nZEhwB9naUXxyxxuGsnsdTsxNY3AUmBpnbZGWxJYCaxAW05Vj87_7txZYBkBIEQUrEBsdzMSpJVhOoEoDpCJ4vl97zwILOXEDjSncMxetjRom2pWIHAHuSh284L9vICsmsMx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