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U13w-L4t5HbEkwp2Qauzt-FY5MnkwWXRbS0IlrbOvQmoaPtUYYiGETjqF-ZoM2O_-O279dfyqK4wC7jyA_gbqyZU2>53367</a>
</td>
</tr>
<tr>
<th>Summary</th>
<td>
Fails to optimize nested array access p[i/N].data[i%N]
</td>
</tr>
<tr>
<th>Labels</th>
<td>
enhancement,
clang:codegen
</td>
</tr>
<tr>
<th>Assignees</th>
<td>
</td>
</tr>
<tr>
<th>Reporter</th>
<td>
Quuxplusone
</td>
</tr>
</table>
<pre>
Clang seems to be unable to optimize a nested array access of the form `p[i/N].data[i%N]` into a simple `((T*)p)[i]`. The C test case is
```
struct CChunk { char data[2]; };
char f(struct CChunk *p, unsigned i) { return p[i/2].data[i%2]; }
```
`clang -O2` currently produces:
```
movl %esi, %eax
andl $-2, %eax
andl $1, %esi
addq %rdi, %rax
movb (%rsi,%rax), %al
retq
```
but I would prefer it to produce:
```
movzbl (%rsi,%rdi), %eax
retq
```
A more exhaustive C++ test follows ([Godbolt](https://godbolt.org/z/3E1e6c5e3)) — GCC can optimize a few of these, but right now Clang can't optimize _any_ of these.
```
template<class T, int N>
struct Chunk {
T data[N];
};
template<class T, int N, class IndexType>
int f(Chunk<T, N> *p, IndexType i) {
return p[i/N].data[i%N];
}
template int f(Chunk<char,2>*, unsigned long long); // GCC wins
template int f(Chunk<char,4>*, unsigned long long); // GCC wins
template int f(Chunk<char,2>*, unsigned);
template int f(Chunk<char,4>*, unsigned);
template int f(Chunk<int,2>*, unsigned long long); // GCC wins
template int f(Chunk<int,4>*, unsigned long long);
template int f(Chunk<int,2>*, unsigned);
template int f(Chunk<int,4>*, unsigned);
```
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJy1VVuP2joQ_jXmZbQoOASShzwAXaq-bHUk3isnGYhPjU1tZ1n215-xQ1hKabunUiXnYo9n5pvLZ1emOZUrJfQOHOLegTdQIXRaVArDxBy83MtXBAEanccGhLXiBKKu0TkwW_AtwtbYPbBZcmDZUjK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