aboutsummaryrefslogtreecommitdiff
path: root/clang/lib/Sema
AgeCommit message (Collapse)AuthorFilesLines
2025-07-16[Clang] FunctionEffects: Make a separate diagnostic group for ↵Doug Wyatt1-1/+9
redeclarations/overrides where effects are implicit. (#148690) The current function effect diagnostics include these behaviors: When you declare a function `nonblocking` (typically in a header) and then omit the attribute on the implementation (or any other redeclaration), Clang warns: attribute 'nonblocking' on function does not match previous declaration. But if a `nonblocking` function is a C++ virtual method, then overrides are implicitly nonblocking; the attribute doesn't need to be explicitly stated. These behaviors are arguably inconsistent -- and also, both, more pedantic than the rest of the function effect diagnostics. This PR accomplishes two things: - Separates the diagnostic on a redeclaration into a new group, `-Wfunction-effect-redeclarations`, so it can be disabled independently. - Adds a second diagnostic to this new group, for the case of an override method missing the attribute. (This helps in a situation where I'm trying to add `nonblocking` via a macro that does other things and I want to know that the macro is missing on an override declaration.) --------- Co-authored-by: Doug Wyatt <dwyatt@apple.com> Co-authored-by: Sirraide <aeternalmail@gmail.com>
2025-07-16[clang][amdgpu] Add builtin for struct buffer lds load (#148950)zGoldthorpe1-0/+1
This is essentially just a revision of #137678 which only exposes a builtin for the intrinsic `llvm.amdgcn.struct.ptr.buffer.load.lds`, which expects an `__amdgpu_buffer_rsrc_t` rather than a `v4i32` as its first argument. The reason for excluding the other intrinsics exposed by the cited PR is because the intrinsics taking a `v4i32` are legacy and should be deprecated.
2025-07-16Thread Safety Analysis: Fix pointer handling of variables with deprecated ↵Marco Elver1-5/+20
attributes (#148974) de10e44b6fe7 ("Thread Safety Analysis: Support warning on passing/returning pointers to guarded variables") added checks for passing pointer to guarded variables. While new features do not necessarily need to support the deprecated attributes (`guarded_var`, and `pt_guarded_var`), we need to ensure that such features do not cause the compiler to crash. As such, code such as this: struct { int v __attribute__((guarded_var)); } p; int *g() { return &p.v; // handleNoMutexHeld() with POK_ReturnPointer } Would crash in debug builds with the assertion in handleNoMutexHeld() triggering. The assertion is meant to capture the fact that this helper should only be used for warnings on variables (which the deprecated attributes only applied to). To fix, the function handleNoMutexHeld() should handle all POK cases that apply to variables explicitly, and produce a best-effort warning. We refrain from introducing new warnings to avoid unnecessary code bloat for deprecated features. Fixes: https://github.com/llvm/llvm-project/issues/140330
2025-07-15[Sema] Remove unnecessary casts (NFC) (#148871)Kazu Hirata4-4/+4
getArgAsExpr already returns Expr *.
2025-07-15[NFC] Remove getDefaultCallingConvention IsBuiltin (#145904)Harald van Dijk3-4/+5
ASTContext::getDefaultCallingConvention() was documented as returning "the default calling convention for the current target", but did not do this, and was never intended to do this, it has always been controlled by command-line options to deviate from the target default. This commit changes ASTContext::getDefaultCallingConvention() to reflect the fact that it returns the context's default calling convention, not the target's default calling convention. The IsBuiltin parameter, which was used to return the target's default calling convention rather than the context's, is removed in favor of getTargetInfo().getDefaultCallingConv() which is more explicit of the intent.
2025-07-15[NFC][SemaHLSL] Fix typo causing float to double conversion (#148941)Finn Plummer1-1/+1
- it was noted, [here](https://github.com/llvm/llvm-project/pull/145795#discussion_r2208118547), that by accidently not specifying this explicitly as a float it will cause a build warning on MSVC - this commit resolves this by explicitly specifying it as a float
2025-07-15[C++] Fix a failed assertion with nullability checking (#148881)Aaron Ballman1-3/+8
This fixes a failed assertion with an operator call expression which comes from a macro expansion when performing analysis for nullability attributes. Fixes #138371
2025-07-15[Clang] Remove explicit object from non member function. (#148807)Corentin Jabot1-1/+3
To avoid crashing later (as we assume only member functions can have explicit object parameters) Fixes #113185
2025-07-15[Clang] Do not treat Foo -> const Foo conversion sequences as perfect (#148613)Corentin Jabot1-1/+13
For implicit object arguments. This fixes a regression introduced by the "perfect match" overload resolution mechanism introduced in 8c5a307. Note that GCC allows the ambiguity between a const and non-const candidate to be resolved. But this patch focuses on restoring the Clang 20 behavior, and to fix the cases which we did resolve incorrectly. Fixes #147374
2025-07-15[Analysis] Avoid some warnings about exit from noreturn function (#144408)Serge Pavlov1-0/+150
Compiler sometimes issues warnings on exit from 'noreturn' functions, in the code like: [[noreturn]] extern void nonreturnable(); void (*func_ptr)(); [[noreturn]] void foo() { func_ptr = nonreturnable; (*func_ptr)(); } where exit cannot take place because the function pointer is actually a pointer to noreturn function. This change introduces small data analysis that can remove some of the warnings in the cases when compiler can prove that the set of reaching definitions consists of noreturn functions only.
2025-07-14[Sema] Remove unnecessary casts (NFC) (#148762)Kazu Hirata1-2/+2
getAsmLabel() already returns Expr *.
2025-07-14[clang][ObjC][PAC] Add ptrauth protections to objective-c (#147899)Oliver Hunt2-0/+17
This PR introduces the use of pointer authentication to objective-c[++]. This includes: * __ptrauth qualifier support for ivars * protection of isa and super fields * protection of SEL typed ivars * protection of class_ro_t data * protection of methodlist pointers and content
2025-07-14[clang] Update diagnostics and documentation for type aware allocators (#148576)Oliver Hunt1-6/+2
Alas reflection pushed p2719 out of C++26, so this PR changes the diagnostics to reflect that for now type aware allocation is functionally a clang extension.
2025-07-14[clang] Add -Wuninitialized-const-pointer (#148337)Igor Kudrin1-4/+16
This option is similar to -Wuninitialized-const-reference, but diagnoses the passing of an uninitialized value via a const pointer, like in the following code: ``` void foo(const int *); void test() { int v; foo(&v); } ``` This is an extract from #147221 as suggested in [this comment](https://github.com/llvm/llvm-project/pull/147221#discussion_r2190998730).
2025-07-14[clang] Fix suppressing diagnostics for uninitialized variables (#148336)Igor Kudrin1-40/+48
When one kind of diagnostics is disabled, this should not preclude other diagnostics from displaying, even if they have lower priority. For example, this should print a warning about passing an uninitialized variable as a const reference: ``` > cat test.cpp void foo(const int &); int f(bool a) { int v; if (a) { foo(v); v = 5; } return v; } > clang test.cpp -fsyntax-only -Wuninitialized -Wno-sometimes-uninitialized ```
2025-07-14[clang] Build argument string for clang::warn_unused_result (#148090)zebullax1-21/+30
Preserve the argument-clause for `warn-unused-result` when under clang:: scope. We are not touching gnu:: scope for now as it's an error for GCC to have that string. Personally I think it would be ok to relax it here too as we are not introducing breakage to currently passing code, but feedback is to go slowly about it.
2025-07-14[Clang] Do not emit -Wmissing-noreturn when [[noreturn]] is present (#148552)Corentin Jabot1-1/+1
Fix a false positve warning which was introduced by #146234.
2025-07-14[Clang] Consider default template arguments when synthesizing CTAD guides ↵Younan Zhang1-3/+22
(#147675) We copy arguments from different template parameter lists depending on the deducibility of the template parameters. In particular, we may lose the default template argument from the original alias declaration, and this patch helps preserve that. Fixes https://github.com/llvm/llvm-project/issues/133132
2025-07-13[Sema] Remove an unnecessary cast (NFC) (#148531)Kazu Hirata1-2/+1
Dtor is already of CXXDestructorDecl *.
2025-07-13[HLSL][RootSignature] Add basic parameter validations of Root Elements (#145795)Finn Plummer1-1/+92
In this pr we go through and enforce the various bounded parameter values for non-flag values and the valid flag combinations for `RootDescriptor` and `DescriptorRange` flags. For reference of the required checks, please see here: https://github.com/llvm/wg-hlsl/blob/main/proposals/0002-root-signature-in-clang.md#validations-in-sema. - Updates `SemaHLSL` to iterate through `RootElement`s and verify that all non-flag parameters are within their bounds - Updates `SemaHLSL` to iterate through `RootElement`s and verify that all flag parameters are a valid combination - Extends `RootSignature-err.hlsl` with testcases for all invalid specifications - Adds `RootSignature-flags-err.hlsl` with testcase for invalid flag specifications Resolves: https://github.com/llvm/llvm-project/issues/129940
2025-07-13[Clang][P1061] Fix template arguments in local classes (#121225)Jason Rice1-1/+5
In the development of P1061 (Structured Bindings Introduce a Patch), I found this bug in the template instantiation of a local class. The issue is caused by the instantiation of the original template and not the partially instantiated template. In the example (sans the fix) the instantiation uses the first template parameter from the previous instantiation and not the current one so the error hits an assertion when it is expecting an NTTP. If they were both types then it might gladly accept the type from the wrong template which is kind of scary. In the test, the reference to `i` is substituted with a placeholder AST object that represents the resolved value when instantiating `g`. However, since the old template is used, the instantiation sees an AST object that only contains the template argument index in the context of instantiating the lambda which has a type template parameter (ie auto). I question if we should use `getTemplateInstantiationPattern` at all here. Other errors involving local classes in nested templates could also be caused by the misuse of this function (because it gets the uninstantiated template).
2025-07-12[Sema] Remove unnecessary casts (NFC) (#148338)Kazu Hirata2-3/+3
NumElts, a member variable of ArrayTypeInfo, is already of Expr *.
2025-07-12[Clang][AST][NFC] (`RecordDecl` -> `CXXRecordDecl`)`::isInjectedClassName` ↵Yanzuo Liu1-1/+2
(#148195) Move `RecordDecl::isInjectedClassName` to `CXXRecordDecl::isInjectedClassName`. C language doesn't have the term "injected class name". Co-authored-by: Matheus Izvekov <mizvekov@gmail.com>
2025-07-12[Clang] Improve diagnostics for 'placement new' with const storage argument ↵Baranov Victor1-1/+11
(#144270) Before this patch, the following code gave misleading diagnostics about absence of `#include <new>`: ```cpp #include <new> struct X { int n; }; int foo() { const X cx = {5}; // error: no matching 'operator new' function for non-allocating placement new expression; include <new> (void)new(&cx) X{10}; }; ``` Now it gives correct diagnostics about constness of passed argument: ```cpp #include <new> struct X { int n; }; int foo() { const X cx = {5}; // error: placement new expression with a const-qualified argument of type 'const X *' is not allowed (void)new(&cx) X{10}; }; ``` Fixes https://github.com/llvm/llvm-project/issues/143708. --------- Co-authored-by: Corentin Jabot <corentinjabot@gmail.com>
2025-07-11[HLSL][RootSignature] Retain `SourceLocation` of `RootElement` for ↵Finn Plummer1-19/+73
`SemaHLSL` diagnostics (#147115) At the moment, when we report diagnostics from `SemaHLSL` we only provide the source location of the root signature attr. This allows for significantly less helpful diagnostics (for eg. reporting resource range overlaps). This pr implements a way to retain the source location of a root element when it is parsed, so that we can output the `SourceLocation` of each root element that causes the overlap in the diagnostics during semantic analysis. This pr defines a wrapper struct `clang::hlsl::RootSignatureElement` in `SemaHLSL` that will contain the underlying `RootElement` and can hold any additional diagnostic information. This struct will be what is used in `HLSLRootSignatureParser` and in `SemaHLSL`. Then the diagnostic information will be stripped and the underlying element will be stored in the `RootSignatureDecl`. For the reporting of diagnostics, we can now use the retained `SourceLocation` of each `RootElement` when reporting the range overlap, and we can add a `note` diagnostic to highlight the other root element as well. - Defines `RootSignatureElement` in the `hlsl` namespace in `SemaHLSL` (defined in `SemaHLSL` because `Parse` has a dependency on `Sema`) - Updates parsing logic to construct `RootSignatureElement`s and retain the source loction in `ParseHLSLRootSignature` - Updates `SemaHLSL` when it constructs the `RootSignatureDecl` to take the new `RootSignatureElement` and store the underlying `RootElement` - Updates the current tests to ensure the new `note` diagnostic is produced and that the `SourceLocation` is seen - Slight update to the `RootSignatureValidations` api to ensure the caller sorts and owns the memory of the passed in `RangeInfo` - Adds a test to demonstrate the `SourceLocation` of both elements being correctly pointed out Resolves: https://github.com/llvm/llvm-project/issues/145819
2025-07-11[HLSL] Disallow writing to readonly resources (#147806)Ashley Coleman2-3/+12
Fixes #141842 Only add the non-const subscript operator to write resources
2025-07-11Remove some FIXMEs that no longer apply; NFCAaron Ballman1-7/+3
Noticed these while doing a review on changes in the area, but C23 added support for nodiscard with a message, so it's not an extension we need to diagnose.
2025-07-11[C23] Accept an _Atomic underlying type (#147802)Aaron Ballman2-2/+50
The underlying type of an enumeration is the non-atomic, unqualified version of the specified type. Clang was rejecting such enumerations, with a hard error, but now has the ability to downgrade the error into a warning. Additionally, we diagnose (as a warning) dropping other qualifiers. _Atomic is special given that an atomic type need not have the same size as its non-atomic counterpart, and that the C++ version of <stdatomic.h> defines _Atomic to std::atomic for easing cross- language atomic use and std::atomic is an invalid enum base in C++. (Note: we expose _Atomic in C++ even without including <stdatomic,h>.) Fixes #147736
2025-07-11[OpenMP][clang] 6.0: parsing/sema for message/severity for parallel (#146093)Robert Imschweiler1-2/+2
Implement parsing and semantic analysis support for the message and severity clauses that have been added to the parallel directive in OpenMP 6.0, 12.1.
2025-07-11[clang] Fix static_cast bypassing access control (#132285)offsetof1-13/+11
Fix access and ambiguity checks not being performed when converting to an rvalue reference to a base class type with `static_cast`. Fixes #121429 --------- Co-authored-by: Corentin Jabot <corentinjabot@gmail.com>
2025-07-10[clang] Combine ConstRefUse with other warnings for uninitialized values ↵Igor Kudrin1-41/+13
(#147898) This helps to avoid duplicating warnings in cases like: ``` > cat test.cpp void bar(int); void foo(const int &); void test(bool a) { int v = v; if (a) bar(v); else foo(v); } > clang++.exe test.cpp -fsyntax-only -Wuninitialized test.cpp:4:11: warning: variable 'v' is uninitialized when used within its own initialization [-Wuninitialized] 4 | int v = v; | ~ ^ test.cpp:4:11: warning: variable 'v' is uninitialized when used within its own initialization [-Wuninitialized] 4 | int v = v; | ~ ^ 2 warnings generated. ```
2025-07-10[Clang] Mark a concept as being invalid if the constraint is invalid (#147938)Oliver Hunt1-1/+3
Make sure to mark a concept decl as being invalid if the constraint is invalid. Fixes #138823
2025-07-10[LifetimeSafety] Introduce intra-procedural analysis in Clang (#142313)Utkarsh Saxena1-0/+10
This patch introduces the initial implementation of the intra-procedural, flow-sensitive lifetime analysis for Clang, as proposed in the recent RFC: https://discourse.llvm.org/t/rfc-intra-procedural-lifetime-analysis-in-clang/86291 The primary goal of this initial submission is to establish the core dataflow framework and gather feedback on the overall design, fact representation, and testing strategy. The focus is on the dataflow mechanism itself rather than exhaustively covering all C++ AST edge cases, which will be addressed in subsequent patches. #### Key Components * **Conceptual Model:** Introduces the fundamental concepts of `Loan`, `Origin`, and `Path` to model memory borrows and the lifetime of pointers. * **Fact Generation:** A frontend pass traverses the Clang CFG to generate a representation of lifetime-relevant events, such as pointer assignments, taking an address, and variables going out of scope. * **Testing:** `llvm-lit` tests validate the analysis by checking the generated facts. ### Next Steps *(Not covered in this PR but planned for subsequent patches)* The following functionality is planned for the upcoming patches to build upon this foundation and make the analysis usable in practice: * **Dataflow Lattice:** A dataflow lattice used to map each pointer's symbolic `Origin` to the set of `Loans` it may contain at any given program point. * **Fixed-Point Analysis:** A worklist-based, flow-sensitive analysis that propagates the lattice state across the CFG to a fixed point. * **Placeholder Loans:** Introduce placeholder loans to represent the lifetimes of function parameters, forming the basis for analysis involving function calls. * **Annotation and Opaque Call Handling:** Use placeholder loans to correctly model **function calls**, both by respecting `[[clang::lifetimebound]]` annotations and by conservatively handling opaque/un-annotated functions. * **Error Reporting:** Implement the final analysis phase that consumes the dataflow results to generate user-facing diagnostics. This will likely require liveness analysis to identify live origins holding expired loans. * **Strict vs. Permissive Modes:** Add the logic to support both high-confidence (permissive) and more comprehensive (strict) warning levels. * **Expanded C++ Coverage:** Broaden support for common patterns, including the lifetimes of temporary objects and pointers within aggregate types (structs/containers). * Performance benchmarking * Capping number of iterations or number of times a CFGBlock is processed. --------- Co-authored-by: Baranov Victor <bar.victor.2002@gmail.com>
2025-07-10[APINotes] Add support for capturing all possible versioned APINotes without ↵Artem Chikin1-76/+137
applying them Swift-versioned API notes get applied at PCM constrution time relying on '-fapinotes-swift-version=X' argument to pick the appropriate version. This change adds a new APINotes application mode with '-fswift-version-independent-apinotes' which causes *all* versioned API notes to get recorded into the PCM wrapped in 'SwiftVersionedAttr' instances. The expectation in this mode is that the Swift client will perform the required transformations as per the API notes on the client side, when loading the PCM, instead of them getting applied on the producer side. This will allow the same PCM to be usable by Swift clients building with different language versions. In addition to versioned-wrapping the various existing API notes annotations which are carried in declaration attributes, this change adds a new attribute for two annotations which were previously applied directly to the declaration at the PCM producer side: 1) Type and 2) Nullability annotations with 'SwiftTypeAttr' and 'SwiftNullabilityAttr', respectively. The logic to apply these two annotations to a declaration is refactored into API.
2025-07-10[Clang] Fix a crash when diagnosing wrong conversion to explicit object ↵Corentin Jabot1-3/+3
parameter (#147996) When an overload is invalid, we try to initialize each conversion sequence for the purpose of diagmostics, but we failed to initialize explicit objects, leading to a crash Fixes #147121
2025-07-10[Clang] fixed false positive redeclaration error for using enum in nested ↵Oleksandr T.1-1/+1
scopes (#147711) Fixes #147495 --- This patch addresses the issue of false-positive redeclaration errors that occur for `using enum` declarations in nested class scopes ```cpp struct S { enum class E { A }; using enum E; struct S1 { using enum E; // no error }; }; ```
2025-07-10[Clang] Correctly handle taking the address of an explicit object member ↵Corentin Jabot2-50/+82
function template (#147046) When implementing #93430, I failed to consider some cases involving function templates. ``` struct A { template <typename T> void a(this T self); }; (&A::a<A>)(A{}); ``` This fixes that
2025-07-10[Clang] Fix the template argument collection after CWG2369 (#147894)Younan Zhang2-25/+33
Since the function template isn't instantiated before constraint checking, we'll not be able to find the outer template arguments through function specialization when evaluating the inner constraint that is nested within a larger constraint expression. The only practical solution is to get them back through the code synthesis context, which also allows us to eliminate an overload of getTemplateInstantiationArgs. No release note because it's a regression on trunk. Fixes https://github.com/llvm/llvm-project/issues/147772
2025-07-10[Sema] Fix lifetime extension for temporaries in range-based for loops in ↵Marco Vitale2-6/+15
C++23 (#145164) C++23 mandates that temporaries used in range-based for loops are lifetime-extended to cover the full loop. This patch adds a check for loop variables and compiler- generated `__range` bindings to apply the correct extension. Includes test cases based on examples from CWG900/P2644R1. Fixes https://github.com/llvm/llvm-project/issues/109793
2025-07-09Address a handful of C4146 compiler warnings where literals can be replaced ↵Alex Sepkowski1-2/+4
with std::numeric_limits (#147623) This PR addresses instances of compiler warning C4146 that can be replaced with std::numeric_limits. Specifically, these are cases where a literal such as '-1ULL' was used to assign a value to a uint64_t variable. The intent is much cleaner if we use the appropriate std::numeric_limits value<Type>::max() for these cases. Addresses #147439
2025-07-10[Clang] Do not skip over `RequiresExprBodyDecl` when creating lambdas (#147764)Corentin Jabot1-2/+0
When we create a lambda, we would skip over declaration contexts representing a require expression body, which would lead to wrong lookup. Note that I wasn't able to establish why the code in `Sema::createLambdaClosureType` was there to begin with (it's not exactly recent) The changes to mangling only ensure the status quo is preserved and do not attempt to address the known issues of mangling lambdas in require clauses. In particular the itanium mangling is consistent with Clang before this patch but differs from GCC's. Fixes #147650
2025-07-09Include [[clang::require_explicit_initialization]] warnings in system ↵higher-performance1-5/+9
headers (#141133) Fixes #141103
2025-07-08[NFC][HLSL] Move resource range logic from `SemaHLSL` to ↵Finn Plummer1-91/+10
`RootSignatureValidations` (#147117) This pr abstracts out the logic of detecting resource range overlap from `SemaHLSL` into the `RootSignatureValidations` library. For more context see linked issue. - Moves the validation logic from `SemaHLSL` to `RootSignatureValidations` - Updates `SemaHLSL` to use the new interface for the validations Resolves: https://github.com/llvm/llvm-project/issues/146393
2025-07-08[clang] Consistently handle consteval constructors for variables. (#144970)Eli Friedman4-26/+25
443377a9d1a8d4a69a317a1a892184c59dd0aec6 handled simple variable definitions, but it didn't handle uninitialized variables with a consteval constructor, and it didn't handle template instantiation. Fixes #135281 .
2025-07-08[Sema] Remove an unnecessary cast (NFC) (#147546)Kazu Hirata1-1/+1
D is already of CXXMethodDecl *.
2025-07-08[Clang] Do not mark ambiguous specialization invalid. (#147275)Corentin Jabot1-1/+0
When a specialization was ambiguous, we would mark it as invalid, even if the specialization occured in an immediate context. This would subsequently lead to scenarios where invalid specialization produced no diagnostics, causing crashes during codegen. Fixes #51866
2025-07-08[Clang][SME] Refactor checkArmStreamingBuiltin. (#145941)Paul Walker1-21/+26
Rather than filtering the calling function's features the PR splits the builtin guard into distinct non-streaming and streaming guards that are compared to the active features in full.
2025-07-08[Clang] Fix template arguments collection for out-of-line declarations (#147463)Younan Zhang1-1/+1
We were using the lexical DC as the starting point of template argument collection when comparing declarations. This caused an issue that template arguments from out-of-line declarations are ignored when substituting into the constraints, which in turn led to expression mismatching. Fixes https://github.com/llvm/llvm-project/issues/145521
2025-07-08[libc++][Clang] Added explanation why is_constructible evaluated to false. ↵Shamshura Egor1-2/+70
Updated the diagnostics checks in libc++ tests. (#144220) Added explanation why a is constructible evaluated to false. Also fixed problem with ExtractTypeTraitFromExpression. In case std::is_xxx_v<> with variadic pack it tries to get template argument, but fails in expression Arg.getAsType() due to Arg.getKind() == TemplateArgument::ArgKind::Pack, but not TemplateArgument::ArgKind::Type. Reverts #144127 Fixies https://github.com/llvm/llvm-project/pull/143309#issuecomment-2970012054
2025-07-08[Clang] include attribute scope in diagnostics (#144619)Oleksandr T.2-13/+20
This patch updates diagnostics to print fully qualified attribute names, including scope when present.