[clang] [Clang][Sema] Support 'counted_by' attribute on FAM/pointers in anonymous unions (PR #171996)

Henrik G. Olsson via cfe-commits cfe-commits at lists.llvm.org
Fri Jan 9 17:00:10 PST 2026


================
@@ -221,3 +221,49 @@ struct on_void_ty {
   // expected-error at +1{{field has incomplete type 'void'}}
   void wrong_ty __counted_by(count);
 };
+
+//==============================================================================
+// __counted_by on pointer members in unions
+//==============================================================================
+
+// Pointer in anonymous union with count in parent struct - OK
+struct ptr_in_anon_union_count_in_parent {
+  int count;
+  union {
+    int a;
+    struct size_known *buf __counted_by(count);
+  };
+};
----------------
hnrklssn wrote:

I'm curious on how assignment analysis would work for this case, as well as the case of:
```
struct ptr_in_anon_union_count_in_parent2 {
  int count;
  union {
    int *buf1 __counted_by(count);
    struct size_known *buf2 __counted_by(count);
  };
};
```

In the case of full `-fbounds-safety`, what are intended the compile-time restrictions when assigning to `count` for each of these structs? Normally when assigning to a count field we stipulate that the user **must** assign to each field referring to that count. In the case of `ptr_in_anon_union_count_in_parent2`, it's obviously not reasonable to assign to both `buf1` and `buf2`. In the case of `ptr_in_anon_union_count_in_parent`, is the user allowed to use the `count` field when the `buf` field isn't used? That would make it impossible to prevent `count` from falling out of sync with `buf`, in the case when `buf` is actually used. But if `count` is useless when `buf` isn't used, then the user may as well put them in a struct in the union:
```
struct ptr_in_anon_union_count_in_parent3 {
  union {
    int a;
    struct {
      int count;
      struct size_known *buf __counted_by(count);
    };
  };
};
```

CC @rapidsna 

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


More information about the cfe-commits mailing list