[clang] [CodeGen] Revamp counted_by calculations (PR #70606)

Bill Wendling via cfe-commits cfe-commits at lists.llvm.org
Fri Nov 3 12:23:10 PDT 2023


bwendling wrote:

> ```
> #include <stdio.h>
> #include <stdlib.h>
> struct flex {
>     int c;
>     int fam[] __attribute__((counted_by(c)));
> };
> 
> int main() {
>     struct flex *p = (struct flex *)malloc(sizeof(struct flex) + sizeof(int) * 10);
>     p->c = 100;
>     printf("%lu\n", __builtin_dynamic_object_size(&p->fam[0], 0)); // 40 : size from malloc, but it only contains the array part. Shouldn't it be 44 to include the entire object size?
>     printf("%lu\n", __builtin_dynamic_object_size(&p->fam[0], 1)); // 40 : size from malloc;
>     printf("%lu\n", __builtin_dynamic_object_size(p, 0));          // 404 : size from counted_by
> }
> ```
> 
> @bwendling It could be tracked as a separate issue, but there seems to be some inconsistencies in where bdos is derived from. For `p` it seems the counted_by wins over malloc. But for `&->fam[0]` malloc seems to win.
> 
> https://godbolt.org/z/G7WfY4faE

I think the first two `printf` s in your code seem correct with 40, because they're both looking at only the FAM, not the entire struct. The fact that they're not reporting 400 here is because godbolt doesn't have this PR. With this PR I get:

```
$ clang -O2 ~/llvm/bdos.c
$ ./a.out
400
400
404
```

Which seems correct to me, given the incorrect value in `p->c`. The documentation does make it very clear that the user is responsible for supplying the correct value to the FAM counter. The GCC people are making that language even stricter, so I'll do that as well. (They also have a dependency issue between the FAM and the counter field that they're solving with a compiler-only pseudo-function call. I'll create an intrinsic on our side to do the same once they land on a solution.)

https://github.com/llvm/llvm-project/pull/70606


More information about the cfe-commits mailing list