Enhance Clang Diagnostics: Lessons from Landing Warnings Upstream
Over the past six months, I worked on Clang diagnostics as a CppAlliance Fellow with my mentors Vassil Vassilev and Aaron Jomy. My introductory post laid out the goal: close diagnostic gaps in Clang so the compiler catches more bugs out of the box, with fewer false positives and silent surprises.
By the end of the fellowship, 31 of my pull requests in llvm/llvm-project had
merged, with 3 more still in review, and five long-standing diagnostic issues
were closed, including one dating back to the Bugzilla era. I also presented
this work at CompilerResearchCon 2026. Here is how the four main
tracks turned out, including what shipped, what got reverted, and what comes
next.
Enabling -Wunused-template under -Wall and chasing down its false positives
-Wunused-template has existed in Clang since 2017
(D29877), but it lived as DefaultIgnore,
commented out of -Wunused with a stale note saying to clean up libc++
first. libc++ had already been cleaned up years ago
(D144667).
The warning catches unused function and variable templates with internal
linkage. In a header, a static or anonymous-namespace function template gives
every translation unit its own copy, which is a latent ODR violation when
referenced from another inline function or template. Enabling it under -Wall
(#202945) surfaces that
pattern before it spreads.
Cleaning up the monorepo
Before flipping the switch, the LLVM tree itself had to build clean. Turning on the flag surfaced 652 raw warnings across 46 unique sites in LLVM and Clang alone, plus more across the runtimes. Almost every warning fell into one of three buckets:
staticor anonymous-namespace templates in headers: drop the internal linkage (templates are implicitly inline).- Dead templates in
.cppfiles: never instantiated anywhere, so delete them. - Templates used only in
assert()orLLVM_DEBUG(): annotate with[[maybe_unused]]so release builds stay quiet.
That turned into 22 merged NFC cleanup PRs across LLVM core, Clang, MLIR,
and the runtimes (compiler-rt, libc, scudo, flang-rt, and openmp).
After a quick revert of the initial enable
(#206123, reverted in
#207848 over flang-rt
unit tests), I fixed the remaining runtime hits and relanded the switch in
#208001.
-Wunused-template shipped enabled under -Wall in Clang 23.1.0.
Wild impact and the revert
Once it was live, the warning did real work both inside and outside LLVM. Other contributors extended the cleanup to BOLT (#222439), MLIR (#221480), LLDB (#221815), and TSan (#209621). Downstream, it surfaced dead or mis-linked templates in Bitcoin Core (bitcoin#35679, bitcoin#35737) and minisketch (minisketch#102), while also exposing friction in projects like HarfBuzz (harfbuzz#6059), which opted to silence the warning on internal function objects that intentionally expose multiple template overloads.
On August 25, however, the enable was reverted (#218638, backported to 23.1.1+) for two reasons: the disruption landed close to the release branch, and real false positives showed up in the wild. All 22 cleanup PRs stayed in.
Investigating the false positives
Two main false positives surfaced after the warning shipped, and they turned out to be very different kinds of problems.
1. Templates used in unevaluated operands (#218429): a Sema bug we can fix
static void O(char) {}
static void O(int) {}
template <typename T>
static void A(T) {}
template <typename T>
static constexpr bool BT = requires {
A<void(*)(T)>(O);
};
int main() {
if constexpr (BT<int>) { O('x'); O(42); }
}
// warning: unused function template 'A' [-Wunused-template]
ShouldRemoveFromUnused only counted a template as used if a specialization
was odr-used or had its definition instantiated. When a template is only named
in an unevaluated operand (such as a C++20 requires-expression, decltype,
sizeof, or noexcept), Clang implicitly instantiates the declaration and
marks it referenced, but never instantiates a body. So Clang warned that A
was unused even though it decided the result of BT<int>.
I opened #234168 to count a referenced implicit specialization as a use of its template; it is currently in review with changes requested.
2. GPU kernel stubs generated by nvcc
(#219968): not completely under our control
The second major false-positive report came from header-only GPU libraries such
as NVIDIA’s CCCL compiled with nvcc using Clang as the host compiler
(-ccbin=clang++). Even though the original kernel declarations in those
headers are not static, nvcc’s preprocessing pass synthesizes static host
stub templates (such as __wrapper__device_stub_transform_kernel) for every
kernel exposed in the header. By the time Clang sees the preprocessed output,
those generated stubs look like ordinary unused internal-linkage templates,
flooding -Werror builds with warnings:
// Synthesized by nvcc during preprocessing (not written as static in user code):
__attribute((__visibility__("hidden")))
static void __wrapper__device_stub_transform_kernel(...);
// warning: unused function template '__wrapper__device_stub_transform_kernel' [-Wunused-template]
What makes this case tricky is that it is not completely under Clang’s control.
Clang is faithfully diagnosing the preprocessed C++ handed to it, and the
reporter noted the warning did catch genuine static inline issues elsewhere
in their codebase. However, library authors cannot edit intermediate compiler
output, and when raised with the NVCC team, they treated it as a host-compiler
issue with no immediate plans to stop emitting static on kernel stubs. Because
neither Clang nor library authors can easily change nvcc’s output, this turns
from a Sema bug into a policy question for code owners before re-enabling in
Clang 24: whether -Wunused-template belongs in -Wall or
-Wextra.
Separately, #152395
tracks a pre-existing Sema design question: an anonymous-namespace template
referenced only by another uninstantiated template (which also affects
-Wunused-function). That will need its own answer alongside the re-enable
proposal.
Conflicting internal and external linkage in C (WG14 N3410)
In C, declaring the same identifier with both internal and external linkage in the same translation unit is undefined behavior (C2y 6.2.2p4, clarified by WG14 N3410):
static int x; // internal linkage
void f(void) {
int x; // no linkage, shadows file-scope x
{
extern int x; // external linkage: conflicts with file-scope static x!
}
}
Clang previously stayed silent on this pattern
(#54215). My first patch
(#192116) landed and was
reverted after review uncovered a subtle C vs. C++ difference: in C++,
P1787R6 ([dcl.meaning.general]/3.5) gives different semantics where no
linkage conflict exists.
The reland (#193567)
excluded C++, restored the C2y citation, and merged in August, closing #54215.
I also filed follow-up #199658
to extend the same check to static-then-extern function declarations.
Fixing long-standing clang:diagnostics bugs
Alongside the larger campaigns, I triaged the clang:diagnostics backlog for
well-scoped false positives and false negatives in Sema and fixed them one PR
at a time:
| PR | Issue | Status | Fix |
|---|---|---|---|
| #204944 | #46362 | Merged | Look through function references (void (&f)()) in DiagnoseAlwaysNonNullPointer so -Wtautological-pointer-compare and -Wpointer-bool-conversion warn just as they do for bare function names. |
| #217342 | #161689 | Merged | Remove the stale !CPlusPlus20 guard left behind by explicit(bool) so -Wc++98-compat warns on explicit conversion functions in C++20 and later. |
| #217465 | #28328 | Merged | Stop -Wpointer-arith from diagnosing pointer subtraction on a VLA (int[n]) as a zero-size type; warn only when the pointee size is provably zero (int[0], empty structs). Closed a Bugzilla-era report. |
| #222047 | #65524 | Merged | Skip -Wdelete-abstract-non-virtual-dtor when C++20 destroying operator delete is selected ([expr.delete]p3), since the destructor is never invoked by the delete expression. ::delete and delete[] keep warning. |
| #220573 | #185400 | In review | Make CheckCommaOperand check each branch of a conditional right operand ((f(), c ? A : B)) individually so -Wimplicit-int-enum-cast stops claiming valid C++ is invalid. |
A quick look at #204944 shows the kind of gap these patches close:
void foo();
void (&f)() = foo;
if (foo != nullptr) {} // warned before: always true
if (f != nullptr) {} // silent before; now warns under -Wtautological-pointer-compare
And #217465 is a good example of how review improves a fix: instead of simply
special-casing VLAs out of -Wpointer-arith, reviewer feedback reshaped the
check to test whether the pointee size is provably zero, keeping the warning
accurate for genuinely empty types without falsely flagging runtime-sized ones.
Bringing clang-tidy’s memcmp check into Clang
Passing a struct with padding bytes or floating-point fields to memcmp is a
classic bug (EXP42-C,
FLP37-C):
padding bytes are indeterminate, and floating-point values do not map
one-to-one to their byte representations (-0.0 vs +0.0, NaN).
Clang’s CheckMemaccessArguments already warns on suspicious memset and
memcpy calls, but memcmp fell right through. clang-tidy has caught this
since 2021 with bugprone-suspicious-memory-comparison
(D89651), but only for users who opt into
running clang-tidy.
Bringing that check into Clang proper split into two PRs:
- Fixing
_Atomicin__has_unique_object_representations(#212768, merged): Before warning in Clang itself, a known false positive had to go.__has_unique_object_representations(_Atomic(int))wrongly returnedfalsebecauseAtomicTypehad been left on a FIXME list since the trait was first implemented, and it failed the trivial-copyability check up front. That exact bug was pinned as a FIXME in theclang-tidytests sinceD89651. The merged fix handlesAtomicTypeexplicitly:_Atomic(T)has unique object representations iffTdoes and its size was not rounded up to a power of two (which introduces padding). - Adding
-Wsuspicious-memcmp(#214218, open): HooksmemcmpandbcmpintoCheckMemaccessArgumentsunder-Wsuspicious-memaccess, usingASTContext::hasUniqueObjectRepresentationswhen a constant size covers the full object. For intentional raw-byte comparisons, casting an argument to(void *)silences the warning, and a fix-it suggests doing so.
What’s next
Three open PRs carry the work past the fellowship:
- Address the review comments on
#234168, then propose
re-enabling
-Wunused-templatefor Clang 24 once the-Wallvs.-Wextraplacement question is settled with code owners. - Rebase #214218
(
-Wsuspicious-memcmp) ontomainnow that its_Atomicprerequisite#212768has landed, and drive it through review. - Finish review on #220573
(
-Wimplicit-int-enum-cast) and pick up #199658 for the N3410 function-declaration follow-up.
Related links
- Announcement blog post
- Project proposal
- Fellowship initial presentation
- Fellowship midterm presentation
- Fellowship end-term presentation (to be updated)
- CompilerResearchCon 2026 (slides)
- My GitHub profile
Thanks
Thank you to my mentors, Vassil Vassilev and Aaron Jomy, for their steady
guidance throughout the fellowship. Thanks as well to the LLVM reviewers
(Aaron Ballman, Corentin Jabot, Vlad Serebrennikov, Shafik Yaghmour, Oliver
Hunt, Younan Zhang, Maksim Levental, Sirraide, and zeyi2) for feedback that
made these patches far better than their first drafts, and to the C++ Alliance
for supporting the fellowship.