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

    <tr>
        <th>Summary</th>
        <td>
            Clang frontend generates unnecessary memcpy (that is optimized to load/store) for an empty class
        </td>
    </tr>

    <tr>
      <th>Labels</th>
      <td>
            new issue
      </td>
    </tr>

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

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

<pre>
    Hi all,

I found out that clang codegen emits an unnecessary memcpy for an empty class with an empty struct. I don't know if other (more common) cases are effected.

The code following code

```
struct a {
  struct {};
} b;
a c;
int main() { b = c; }
```

generates the LLVM IR (see https://godbolt.org/z/4hjx8xxqf)

```
define dso_local noundef i32 @main() #0 {
  call void @llvm.memcpy.p0.p0.i64(ptr align 1 @b, ptr align 1 @c, i64 1, i1 false), !tbaa.struct !6
  ret i32 0
}

...

!6 = !{}
```

Interestingly, the memcpy is generated with an empty tbaa.struct metadata, indicating that the memcpy is copying nothing.

During IR optimization the memcpy is optimized to a load/store.

```
define dso_local noundef i32 @main() local_unnamed_addr #0 {
  %1 = load i8, ptr @c, align 1
  store i8 %1, ptr @b, align 1
  ret i32 0
}
```

The problem is within the CodeGenFunction::EmitAggregateCopy function in clang\lib\CodeGen\CGExprAgg.cpp. The function only checks if the record is empty using `Record->isEmpty()`. Either isEmpty is wrong in that case or the calculated data layout of the record is a better choice to skip memcpy emission.
</pre>
<img width="1px" height="1px" alt="" src="http://email.email.llvm.org/o/eJysVVFzozgM_jXOi2YZMCHAAw9t0uxlZu-lc3OvHWML8NbYnG22zf76GxvSptnuPd1MhoAkS5_0STJzTvYasSHFPSkOGzb7wdjGeStHk5fVpjXi3PwhgSlF6J6kB5LeLc8TdGbWAszswQ_MA1dM98CNwB414Ci9A6Zh1ho5OsfsGUYc-XSGztigwXHy53DMOXiRfniXOW9n7hM4gTCa0NLDszYvIDswfkALhF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