[clang] [clang] Add comment about misleading alloc_size argument names (PR #134899)

via cfe-commits cfe-commits at lists.llvm.org
Tue Apr 8 11:14:06 PDT 2025


llvmbot wrote:


<!--LLVM PR SUMMARY COMMENT-->

@llvm/pr-subscribers-clang

Author: Jann (thejh)

<details>
<summary>Changes</summary>

Attr.td names the first alloc_size argument "ElemSizeParam" and the second optional argument "NumElemsParam"; but the semantics of how the two-argument version is used in practice is the opposite of that.

glibc declares calloc() like this, so the second alloc_size argument is the element size:
```
extern void *calloc (size_t __nmemb, size_t __size)
__THROW __attribute_malloc__ __attribute_alloc_size__ ((1, 2)) __wur;
```

The Linux kernel declares array allocation functions like `kmalloc_array_noprof()` the same way.

Add a comment explaining that the names used inside clang are misleading.

---
Full diff: https://github.com/llvm/llvm-project/pull/134899.diff


1 Files Affected:

- (modified) clang/include/clang/Basic/Attr.td (+7) 


``````````diff
diff --git a/clang/include/clang/Basic/Attr.td b/clang/include/clang/Basic/Attr.td
index fd9e686485552..b7ad432738b29 100644
--- a/clang/include/clang/Basic/Attr.td
+++ b/clang/include/clang/Basic/Attr.td
@@ -1709,6 +1709,13 @@ def EmptyBases : InheritableAttr, TargetSpecificAttr<TargetMicrosoftCXXABI> {
 def AllocSize : InheritableAttr {
   let Spellings = [GCC<"alloc_size">];
   let Subjects = SubjectList<[HasFunctionProto]>;
+  // The parameter names here are a bit misleading.
+  // When used with a single argument, the first argument is obviously the
+  // allocation size; but when used with two arguments, the first argument is
+  // usually the number of elements, while the second argument is usually the
+  // element size - the reverse of how they are named here.
+  // The documentation of both GCC and clang does not describe any semantic
+  // difference between the first and second argument.
   let Args = [ParamIdxArgument<"ElemSizeParam">,
               ParamIdxArgument<"NumElemsParam", /*opt*/ 1>];
   let TemplateDependent = 1;

``````````

</details>


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


More information about the cfe-commits mailing list