GCC creates memcpy when accessing an array

GCC creates memcpy when accessing an array

#include<bits/stdc++.h>
using namespace std;
int n,a[300005],b[300005];
vector<int> ans;
int main(){
  ans.reserve(300005);
  cin>>n;
  for(int i=0;i<n;++i)cin>>a[i];
  for(int i=0;i<n;++i)cin>>b[i];
  for(int i=0;i<n;++i){
    int v=i[ans.size()&1?a:b];
    //int v=ans.size()&1?a[i]:b[i];
    ans.push_back(v);
  }
  cout<<ans.size();
  for(int x:ans)cout<<' '<<x;
}

For the above code, for line int v=i[ans.size()&1?a:b]; it generates (with -std=c++20 -O2, the following is from 14.1, memcpy is observed with 12.4 and newer):

.L25:
        mov     r12, rbx
        mov     r13, QWORD PTR ans[rip+16]
        mov     edx, 1200020
        sub     r12, r15
        mov     rax, r12
        sar     rax, 2
        mov     QWORD PTR [rsp+8], rax
        test    r12b, 4
        jne     .L49
        mov     esi, OFFSET FLAT:b
        mov     rdi, r14
        call    memcpy

i.e. it copies the whole array just to add an element to it. I am not filing a bug as I didn't come up with a strong enough use case for it to persuade someone to fix.


Deducing this and CRTP Bedrock coding agent 配置