[clang] Diagnose problematic uses of constructor/destructor attribute (PR #67360)

Aaron Ballman via cfe-commits cfe-commits at lists.llvm.org
Tue Sep 26 07:01:48 PDT 2023


================
@@ -171,6 +171,11 @@ Attribute Changes in Clang
   automatic diagnostic to use parameters of types that the format style
   supports but that are never the result of default argument promotion, such as
   ``float``. (`#59824: <https://github.com/llvm/llvm-project/issues/59824>`_)
+- The ``constructor`` and ``destructor`` attributes now diagnose when:
+  - the priority is not between 101 and 65535, inclusive,
+  - the function it is applied to accepts arguments or has a non-void return
----------------
AaronBallman wrote:

> I'm more considering a case where someone wants to use an otherwise 'normal' function as their constructor/destructor, where the return value is perhaps useful if the program is continuing (but then obviously not when it is not). I would think that the RETURN should at minimum be only a warning (or perhaps warning-as-error?), since this is otherwise a breaking change.

That was the case that concerned me as well, but I've not seen any evidence of such code existing in the wild.

> The params list being nothing makes sense, because there is no valid code generation that did that before AFAIK, but an ignorable return type is meaningful. In your func case, I don't see a problem with that, presume the 1st line was something like:
> ```
> if (!GlobalAllocator) InitAllocator(GlobalAllocator);
> ```
> and they were using the constructor call to initialize that (and not caring about the object it was returning). This would cause this error to be breaking.

Look at the codegen for my example and that should make it more clear why it's an issue: https://godbolt.org/z/qncWqqovb

The problem is that there's no way to return from that function without inducing UB. You either return a value (and the hidden pointer is invalid so you just did an out of bounds write somewhere) or you don't return any value (no out of bounds write to the hidden pointer, but oops, UB to fall off the end of the function that way).

You can devise circumstances where it's safe, but unless there's evidence that people use the attribute this way, I don't see a compelling reason to give people a gun to point at their feet.

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


More information about the cfe-commits mailing list