2665 Commits

Author SHA1 Message Date
Gedare Bloom
e0a21e23a7
[clang-format] Add BinPackLongBracedList style option (#112482)
The use of Cpp11BracedListStyle with BinPackArguments=False avoids bin
packing until reaching a hard-coded limit of 20 items. This is an
arbitrary choice. Introduce a new style option to allow disabling this
limit.
2025-02-07 22:10:35 -08:00
Jameson Nash
9b8297bc7e
[analyzer] Do not destruct fields of unions (#122330)
The C++ standard prohibits this implicit destructor call, leading to
incorrect reports from clang-analyzer. This causes projects that use
std::option (including llvm) to fail the cplusplus.NewDelete test
incorrectly when run through the analyzer.

Fixes #119415
2025-02-07 08:01:39 +01:00
David Pagan
a5fc7c3ac1
[clang][OpenMP] New OpenMP 6.0 assumption clause, 'no_openmp_constructs' (#125933)
Add initial parsing/sema support for new assumption clause so clause can
be specified. For now, it's ignored, just like the others.

Added support for 'no_openmp_construct' to release notes.

Testing
- Updated appropriate LIT tests.
- Testing: check-all
2025-02-06 12:41:10 -08:00
Donát Nagy
6e17ed9b04
[analyzer] Consolidate array bound checkers (#125534)
Before this commit, there were two alpha checkers that used different
algorithms/logic for detecting out of bounds memory access: the old
`alpha.security.ArrayBound` and the experimental, more complex
`alpha.security.ArrayBoundV2`.

After lots of quality improvement commits ArrayBoundV2 is now stable
enough to be moved out of the alpha stage. As indexing (and dereference)
are common operations, it still produces a significant amount of false
positives, but not much more than e.g. `core.NullDereference` or
`core.UndefinedBinaryOperatorResult`, so it should be acceptable as a
non-`core` checker.

At this point `alpha.security.ArrayBound` became obsolete (there is a
better tool for the same task), so I'm removing it from the codebase.
With this I can eliminate the ugly "V2" version mark almost everywhere
and rename `alpha.security.ArrayBoundV2` to `security.ArrayBound`.

(The version mark is preserved in the filename "ArrayBoundCheckerV2", to
ensure a clear git history. I'll rename it to "ArrayBoundChecker.cpp" in
a separate commit.)

This commit adapts the unit tests of `alpha.security.ArrayBound` to
testing the new `security.ArrayBound` (= old ArrayBoundV2). Currently
the names of the test files are very haphazard, I'll probably create a
separate followup commit that consolidates this.
2025-02-06 17:45:42 +01:00
Nikolas Klauser
9598f74133
[Clang] Remove __is_referenceable builtin (#123078)
`__is_referenceable` is almost unused in the wild, and the few cases I
was able to find had checks around them. Since the places in the
standard library where `__is_referenceable` is used have bespoke
builtins, it doesn't make a ton of sense to keep this builtin around.

`__is_referenceable` has been documented as deprecated in Clang 20.
2025-02-06 15:04:23 +01:00
leijurv
d2b45ce100
[clang-format] Add BreakBeforeTemplateCloser option (#118046)
In clang-format, multiline templates have the `>` on the same line as
the last parameter:

```c++
template <
    typename Foo,
    typename Bar>
void foo() {
```

I would like to add an option to put the `>` on the next line, like
this:

```c++
template <
    typename Foo,
    typename Bar
>
void foo() {
```

An example of a large project that uses this style is NVIDIA's CUTLASS,
here is an example:


https://github.com/NVIDIA/cutlass/blob/main/include/cutlass/epilogue/dispatch_policy.hpp#L149-L156

My reasoning is that it reminds me of this style of braces:

```c++
if (foo()) {
    bar();
    baz();}
```

Most people agree this is better:

```c++
if (foo()) {
    bar();
    baz();
}
```

---------

Co-authored-by: Owen Pan <owenpiano@gmail.com>
2025-02-06 01:15:47 -08:00
Saleem Abdulrasool
1901f4ac8e
CodeGen: support static linking for libclosure (#125384)
When building on Windows, dealing with the BlocksRuntime is slightly
more complicated. As we are not guaranteed a formward declaration for
the blocks runtime ABI symbols, we may generate the declarations for
them. In order to properly link against the well-known types, we always
annotated them as `__declspec(dllimport)`. This would require the
dynamic linking of the blocks runtime under all conditions. However,
this is the only the only possible way to us the library. We may be
building a fully sealed (static) executable. In such a case, the well
known symbols should not be marked as `dllimport` as they are assumed to
be statically available with the static linking to the BlocksRuntime.

Introduce a new driver/cc1 option `-static-libclosure` which mirrors the
myriad of similar options (`-static-libgcc`, `-static-libstdc++`,
-static-libsan`, etc).
2025-02-05 15:15:36 -08:00
Matheus Izvekov
346077aaa6
Reland: [clang] Track function template instantiation from definition (#125266) 2025-02-05 14:12:12 -03:00
Joseph Huber
cd754af55f
[Clang] Permit both gnu and clang prefixes on some attributes (#125796)
Summary:
Some attributes have gnu extensions that share names with clang
attributes. If these imply the same thing, we can specially declare this
to be an alternate but equivalent spelling. This patch enables this for
`no_sanitize` and provides the infrastructure for more to be added if
needed.

Discussions welcome on whether or not we want to bind ourselves to GNU
behavior, since theoretically it's possible for GNU to silently change
the semantics away from our implementation, but I'm not an expert.

Fixes: https://github.com/llvm/llvm-project/issues/125760
2025-02-05 08:16:00 -06:00
nerix
7d669b7c25
[Clang][Comments] Allow HTML tags across multiple lines (#120843)
HTML starting tags that span multiple lines were previously not allowed
(or rather, only the starting line was lexed as HTML). Doxygen allows
those tags.

This PR allows the starting tags to span multiple lines. They can't span
multiple (C-)Comments, though (it's likely a user-error). Multiple BCPL
comments are fine as those are single lines (shown below).

Example:

```c
/// <a
///     href="foo"
/// >Aaa</a>b
int Test;
```

Fixes #28321.
2025-02-05 08:46:14 -05:00
Pranav Kant
e8a486ea97
[clang] Return larger CXX records in memory (#120670)
We incorrectly return CXX records in AVX registers when they should be
returned in memory. This is violation of x86-64 psABI.

Detailed discussion is here:
https://groups.google.com/g/x86-64-abi/c/BjOOyihHuqg/m/KurXdUcWAgAJ
2025-02-04 09:42:12 -08:00
Timm Baeder
227b32f6a1
[clang] Remove an incorrect assertion in ConstantFoldAttrs (#105789)
Evaluating the attribute expression can be successful without resulting
in a value. Namely, when the expression is of type void.

Fixes https://github.com/llvm/llvm-project/issues/119125
2025-02-04 12:58:44 +01:00
Ikhlas Ajbar
1abe7e8deb
[Hexagon][Docs] document the change in the default target (#125584) 2025-02-03 16:43:27 -06:00
Devon Loehr
dfc28736d4
Warn when unique objects might be duplicated in shared libraries (#125526)
This is attempt 2 to merge this, the first one is #117622. This properly
disables the tests when building for playstation, since the warning is
disabled there.

When a hidden object is built into multiple shared libraries, each
instance of the library will get its own copy. If
the object was supposed to be globally unique (e.g. a global variable or
static data member), this can cause very subtle bugs.

An object might be incorrectly duplicated if it:

Is defined in a header (so it might appear in multiple TUs), and
Has external linkage (otherwise it's supposed to be duplicated), and
Has hidden visibility (or else the dynamic linker will handle it)
The duplication is only a problem semantically if one of the following
is true:

The object is mutable (the copies won't be in sync), or
Its initialization has side effects (it may now run more than once), or
The value of its address is used (different copies have different
addresses).
To detect this, we add a new -Wunique-object-duplication warning. It
warns on cases (1) and (2) above. To be conservative, we only warn in
case (2) if we are certain the initializer has side effects, and we
don't warn on new because the only side effect is some extra memory
usage.

We don't currently warn on case (3) because doing so is prone to false
positives: there are many reasons for taking the address which aren't
inherently problematic (e.g. passing to a function that expects a
pointer). We only run into problems if the code inspects the value of
the address.

The check is currently disabled for windows, which uses its own analogue
of visibility (declimport/declexport). The check is also disabled inside
templates, since it can give false positives if a template is never
instantiated.

Resolving the warning
The warning can be fixed in several ways:

If the object in question doesn't need to be mutable, it should be made
const. Note that the variable must be completely immutable, e.g. we'll
warn on const int* p because the pointer itself is mutable. To silence
the warning, it should instead be const int* const p.
If the object must be mutable, it (or the enclosing function, in the
case of static local variables) should be made visible using
__attribute((visibility("default")))
If the object is supposed to be duplicated, it should be be given
internal linkage.
Testing
I've tested the warning by running it on clang itself, as well as on
chromium. Compiling clang resulted in [10 warnings across 6
files](https://github.com/user-attachments/files/17908069/clang-warnings.txt),
while Chromium resulted in [160 warnings across 85
files](https://github.com/user-attachments/files/17908072/chromium-warnings.txt),
mostly in third-party code. Almost all warnings were due to mutable
variables.

I evaluated the warnings by manual inspection. I believe all the
resulting warnings are true positives, i.e. they represent
potentially-problematic code where duplication might cause a problem.
For the clang warnings, I also validated them by either adding const or
visibility annotations as appropriate.

Limitations
I am aware of four main limitations with the current warning:

We do not warn when the address of a duplicated object is taken, since
doing so is prone to false positives. I'm hopeful that we can create a
refined version in the future, however.
We only warn for side-effectful initialization if we are certain side
effects exist. Warning on potential side effects produced a huge number
of false positives; I don't expect there's much that can be done about
this in modern C++ code bases, since proving a lack of side effects is
difficult.
Windows uses a different system (declexport/import) instead of
visibility. From manual testing, it seems to behave analogously to the
visibility system for the purposes of this warning, but to keep things
simple the warning is disabled on windows for now.
We don't warn on code inside templates. This is unfortuate, since it
masks many real issues, e.g. a templated variable which is implicitly
instantiated the same way in multiple TUs should be globally unique, but
may accidentally be duplicated. Unfortunately, we found some potential
false positives during testing that caused us to disable the warning for
now.
2025-02-03 21:20:47 +01:00
Brian Foley
39879e4f40
[Sema] Note member decl when initializer list default constructs member (#121854)
Recently I had a scenario where I had:
1. A class C with many members m_1...m_n of the same type T
2. T's default constructor was deleted
3. I accidentally omitted an explicitly constructed member in the
initializer list C() : m_1(foo), m_2(bar), ... { }

Clang told me that T's default constructor was deleted, and told me that
the call to T() was in C() (which it implicitly was), but didn't tell me
which member was being default constructed.

It was difficult to fix this problem because I had no easy way to list
all the members of type T in C and C's superclasses which would have let
me find which member was missing,

clang/test/CXX/class/class.init/p1.cpp is a simplified version of this
problem (a2 is missing from the initializer list of B)
2025-02-03 19:57:37 +01:00
Hans Wennborg
90e0dd15ff Revert "[Analyzer][CFG] Correctly handle rebuilt default arg and default init expression (#117437)"
This caused assertion failures:

  clang/lib/Analysis/CFG.cpp:822:
  void (anonymous namespace)::CFGBuilder::appendStmt(CFGBlock *, const Stmt *):
  Assertion `!isa<Expr>(S) || cast<Expr>(S)->IgnoreParens() == S' failed.

See comment on the PR.

This reverts commit 44aa618ef67d302f5ab77cc591fb3434fe967a2e.
2025-02-03 15:52:04 +01:00
Hans Wennborg
cdeeb390a9 Revert "Warn when unique objects might be duplicated in shared libraries (#117622)"
There are some buildbot breakages, see the PR. Reverting for now.

This reverts commit d5684b8402d2175e80a2792db58e9a8e960a8544.
2025-02-03 13:56:46 +01:00
Devon Loehr
d5684b8402
Warn when unique objects might be duplicated in shared libraries (#117622)
When a hidden object is built into multiple shared libraries, each
instance of the library will get its own copy. If
the object was supposed to be globally unique (e.g. a global variable or
static data member), this can cause very subtle bugs.

An object might be incorrectly duplicated if it:
- Is defined in a header (so it might appear in multiple TUs), and
- Has external linkage (otherwise it's supposed to be duplicated), and
- Has hidden visibility (or else the dynamic linker will handle it)

The duplication is only a problem semantically if one of the following
is true:
1. The object is mutable (the copies won't be in sync), or
2. Its initialization has side effects (it may now run more than once),
or
3. The value of its address is used (different copies have different
addresses).

To detect this, we add a new -Wunique-object-duplication warning. It
warns on cases (1) and (2) above. To be conservative, we only warn in
case (2) if we are certain the initializer has side effects, and we
don't warn on `new` because the only side effect is some extra memory
usage.

We don't currently warn on case (3) because doing so is prone to false
positives: there are many reasons for taking the address which aren't
inherently problematic (e.g. passing to a function that expects a
pointer). We only run into problems if the code inspects the value of
the address.

The check is currently disabled for windows, which uses its own analogue
of visibility (declimport/declexport). The check is also disabled inside
templates, since it can give false positives if a template is never
instantiated.

### Resolving the warning
The warning can be fixed in several ways:
- If the object in question doesn't need to be mutable, it should be
made const. Note that the variable must be completely immutable, e.g.
we'll warn on `const int* p` because the pointer itself is mutable. To
silence the warning, it should instead be `const int* const p`.
- If the object must be mutable, it (or the enclosing function, in the
case of static local variables) should be made visible using
`__attribute((visibility("default")))`
- If the object is supposed to be duplicated, it should be be given
internal linkage.

### Testing
I've tested the warning by running it on clang itself, as well as on
chromium. Compiling clang resulted in [10 warnings across 6
files](https://github.com/user-attachments/files/17908069/clang-warnings.txt),
while Chromium resulted in [160 warnings across 85
files](https://github.com/user-attachments/files/17908072/chromium-warnings.txt),
mostly in third-party code. Almost all warnings were due to mutable
variables.

I evaluated the warnings by manual inspection. I believe all the
resulting warnings are true positives, i.e. they represent
potentially-problematic code where duplication might cause a problem.
For the clang warnings, I also validated them by either adding `const`
or visibility annotations as appropriate.

### Limitations
I am aware of four main limitations with the current warning:
1. We do not warn when the address of a duplicated object is taken,
since doing so is prone to false positives. I'm hopeful that we can
create a refined version in the future, however.
2. We only warn for side-effectful initialization if we are certain side
effects exist. Warning on potential side effects produced a huge number
of false positives; I don't expect there's much that can be done about
this in modern C++ code bases, since proving a lack of side effects is
difficult.
3. Windows uses a different system (declexport/import) instead of
visibility. From manual testing, it seems to behave analogously to the
visibility system for the purposes of this warning, but to keep things
simple the warning is disabled on windows for now.
4. We don't warn on code inside templates. This is unfortuate, since it
masks many real issues, e.g. a templated variable which is implicitly
instantiated the same way in multiple TUs should be globally unique, but
may accidentally be duplicated. Unfortunately, we found some potential
false positives during testing that caused us to disable the warning for
now.
2025-02-03 13:20:52 +01:00
yronglin
44aa618ef6
[Analyzer][CFG] Correctly handle rebuilt default arg and default init expression (#117437)
Clang currently support extending lifetime of object bound to reference
members of aggregates, that are created from default member initializer.
This PR address this change and updaye CFG and ExprEngine.

This PR reapply https://github.com/llvm/llvm-project/pull/91879.
Fixes https://github.com/llvm/llvm-project/issues/93725.

---------

Signed-off-by: yronglin <yronglin777@gmail.com>
2025-02-01 16:58:05 +08:00
Aaron Ballman
ef91caec2c
Allow 'inline' on some declarations in MS compatibility mode (#125250)
Microsoft allows the 'inline' specifier on a typedef of a function type
in C modes. This is used by a system header (ufxclient.h), so instead
of giving a hard error, we diagnose with a warning. C++ mode and non-
Microsoft compatibility modes are not impacted.

Fixes https://github.com/llvm/llvm-project/issues/124869
2025-01-31 13:50:01 -05:00
Nikolas Klauser
74d7f43b98
[Clang] Fix __{add,remove}_pointer in Objective-C++ (#123678)
This aligns the builtins with how implementations work which don't use
the buitins.
2025-01-30 20:34:29 +01:00
Phoebe Wang
9ebfee9d68
[X86][AVX10] Disable m[no-]avx10.1 and switch m[no-]avx10.2 to alias of 512 bit options (#124511)
Per the feedback we got, we’d like to switch m[no-]avx10.2 to alias of
512 bit options and disable m[no-]avx10.1 due to they were alias of 256
bit options.

We also change -mno-avx10.[1,2]-512 to alias of 256 bit options to
disable both 256 and 512 instructions.
2025-01-30 21:13:49 +08:00
Martin Storsjö
5c24847e7d Revert "[clang] Track function template instantiation from definition (#112241)"
This reverts commit 07a0e2be86f33beb6d519a3d466b95c2257e93cb.

This change broke compiling Qt; see
https://github.com/llvm/llvm-project/pull/112241 for details.
2025-01-30 12:05:56 +02:00
Sirraide
c4a019747c
[Clang] Remove ARCMigrate (#119269)
In the discussion around #116792, @rjmccall mentioned that ARCMigrate
has been obsoleted and that we could go ahead and remove it from Clang,
so this patch does just that.
2025-01-30 05:32:25 +01:00
Matheus Izvekov
07a0e2be86
[clang] Track function template instantiation from definition (#112241)
This fixes instantiation of definition for friend function templates,
when the declaration found and the one containing the definition have
different template contexts.

In these cases, the the function declaration corresponding to the
definition is not available; it may not even be instantiated at all.

So this patch adds a bit which tracks which function template
declaration was instantiated from the member template. It's used to find
which primary template serves as a context for the purpose of
obtainining the template arguments needed to instantiate the definition.

Fixes #55509

Relanding patch, with no changes, after it was reverted due to revert of
commit this patch depended on.
2025-01-29 17:23:36 -03:00
Matheus Izvekov
8a334af417
[clang] Remove the deprecated flag -frelaxed-template-template-args. (#111894)
This flag has been deprecated since Clang 19, having been the default
since then.

It has remained because its negation was still useful to work around
backwards compatibility breaking changes from P0522.

However, in Clang 20 we have landed various changes which implemented
P3310R2 and beyond, which solve almost all of the expected issues, the
known remaining few being a bit obscure.

So this change removes the flag completely and all of its implementation
and support code.

Hopefully any remaining users can just stop using the flag. If there are
still important issues remaining, this removal will also shake the tree
and help us know.
2025-01-29 16:57:05 -03:00
Tom Stellard
3bd3e06f3f
Bump version to 21.0.0git (#124870)
Also clear the release notes.
2025-01-28 19:48:43 -08:00
Matheus Izvekov
2cbf2798ae
[clang] fix nondeduced mismatch with nullptr template arguments (#124498)
In deduction, when comparing template arguments of value kind, we should
check if the value matches. Values of different types can still match.
For example, `short(0)` matches `int(0)`.

Values of nullptr kind always match each other, since there is only one
such possible value. Similarly to integrals, the type does not matter.
2025-01-28 18:08:14 -03:00
Matheus Izvekov
b1972689a4
[clang] fix template argument conversion (#124386)
Converted template arguments need to be converted again, if the
corresponding template parameter changed, as different conversions might
apply in that case.
2025-01-28 17:25:05 -03:00
Oleksandr T.
5dab5bf085
[Clang] handle [[warn_unused]] attribute for unused private fields (#120734)
Fixes #62472
2025-01-28 22:19:12 +02:00
Matheus Izvekov
e29c085812
[clang] disallow narrowing when matching template template parameters (#124313)
This fixes the core issue described in P3579, following the design
intent of P0522 to not introduce any new cases where a template template
parameter match is allowed for a template which is not valid for all
possible uses.

With this patch, narrowing conversions are disallowed for TTP matching.

This reuses the existing machinery for diagnosing narrowing in a
converted constant expression.
Since P0522 is a DR and we apply it all the way back to C++98, this
brings that machinery to use in older standards, in this very narrow
scope of TTP matching.

This still doesn't solve the ambiguity when partial ordering NTTPs of
different integral types, this is blocked by a different bug which will
be fixed in a subsequent patch (but the test cases are added).
2025-01-28 15:51:17 -03:00
Stephen Tozer
822f74a911
[Clang] Cleanup docs and comments relating to -fextend-variable-liveness (#124767)
This patch contains a number of changes relating to the above flag;
primarily it updates comment references to the old flag names,
"-fextend-lifetimes" and "-fextend-this-ptr" to refer to the new names,
"-fextend-variable-liveness[={all,this}]". These changes are all NFC.

This patch also removes the explicit -fextend-this-ptr-liveness flag
alias, and shortens the help-text for the main flag; these are both
changes that were meant to be applied in the initial PR (#110000), but
due to some user-error on my part they were not included in the merged
commit.
2025-01-28 18:25:32 +00:00
cor3ntin
820c6ac7f5
[Clang] call HandleImmediateInvocation before checking for immediate escacalating expressions (reland) (#124708)
HandleImmediateInvocation can call MarkExpressionAsImmediateEscalating 
and should always be called before
CheckImmediateEscalatingFunctionDefinition.
    
However, we were not doing that in `ActFunctionBody`.

Fixes #119046
2025-01-28 15:18:38 +01:00
Wolfgang Pieb
71ab44a819 [Clang] Add "extend lifetime" flags and release note (#110000)
Following the commit that added the fake use intrinsic to LLVM, this patch
adds a pair of flags for the clang frontend that emit fake use intrinsics,
for the purpose of extending the lifetime of variables (either all source
variables, or just the `this` pointer). This patch does not implement the
fake use intrinsic emission of the flags themselves, it simply adds the flags,
the corresponding release note, and the attachment of the `has_fake_uses`
attribute to affected functions; the remaining functionality appears in the
next patch.

Co-authored-by: Stephen Tozer <stephen.tozer@sony.com>
2025-01-28 10:08:02 +00:00
Nikita Popov
1295aa2e81
[Clang] Add -fwrapv-pointer flag (#122486)
GCC supports three flags related to overflow behavior:
 * `-fwrapv`: Makes signed integer overflow well-defined.
 * `-fwrapv-pointer`: Makes pointer overflow well-defined.
* `-fno-strict-overflow`: Implies `-fwrapv -fwrapv-pointer`, making both
signed integer overflow and pointer overflow well-defined.

Clang currently only supports `-fno-strict-overflow` and `-fwrapv`, but
not `-fwrapv-pointer`.

This PR proposes to introduce `-fwrapv-pointer` and adjust the semantics
of `-fwrapv` to match GCC.

This allows signed integer overflow and pointer overflow to be
controlled independently, while `-fno-strict-overflow` still exists to
control both at the same time (and that option is consistent across GCC
and Clang).
2025-01-28 09:57:00 +01:00
Gedare Bloom
d50ebd47ae
[clang-format] Add style option PenaltyBreakBeforeMemberAccess (#118409)
The penalty for breaking before a member access is hard-coded to 150.
Add a configuration option to allow setting it.

---------

Co-authored-by: Owen Pan <owenpiano@gmail.com>
2025-01-27 21:40:17 -08:00
Aidan Goldfarb
7fd58339b4
[clang] Add __nullptr as a keyword to C (#123119)
This PR resolves #121503. 

---------

Co-authored-by: Aidan <aidan.goldfarb@mail.mcgill.ca>
Co-authored-by: Erich Keane <ekeane@nvidia.com>
Co-authored-by: Aaron Ballman <aaron@aaronballman.com>
2025-01-27 18:12:50 -05:00
cor3ntin
0e372c3ea3
Revert "[Clang] call HandleImmediateInvocation before checking for immediate escacalating expressions" (#124646)
Reverts llvm/llvm-project#124414

Turns out to be an important compile time regression, I'll come up with
a less disruptive approach
2025-01-27 23:51:19 +01:00
cor3ntin
5815a31105
[Clang] call HandleImmediateInvocation before checking for immediate escacalating expressions (#124414)
HandleImmediateInvocation can call MarkExpressionAsImmediateEscalating
and should always be called before
CheckImmediateEscalatingFunctionDefinition.

However, we were not doing that in `ActFunctionBody`.

We simply move CheckImmediateEscalatingFunctionDefinition to
PopExpressionEvaluationContext.

Fixes #119046
2025-01-27 22:21:48 +01:00
André Brand
e734f01bff
[clang] Prevent duplicated instantiation of enumerators of unscoped member enumerations (#124407)
This commit addresses a bug occurring when an unscoped member enumeration
of a class template is introduced with an opaque-enum-declaration and later
redeclared with an enum-specifier (per C++23 [class.mem] p6).
Previously, the enumerators, or EnumConstantDecl, of the enum-specifier
were instantiated at both declarations, leading to different issues:
* erroneous ambiguities when referencing the enumerators,
* duplicated diagnostics in the enumerator-list.

The issue is resolved by ensuring that enumerators are instantiated only
at the first instantiated declaration, analogous to nested classes.

Fixes #124405
2025-01-27 21:42:33 +01:00
cor3ntin
561132e71b
[Clang] Fix immediate escalation of template function specializations. (#124404)
We record whether an expression is immediate escalating in the
FunctionScope.
However, that only happen when parsing or transforming an expression.
This might not happen when transforming a non dependent expression.

This patch fixes that by considering a function immediate when
instantiated from an immediate function.

Fixes #123405
2025-01-27 15:50:51 +01:00
Dipesh Sharma
54928a10c8
[clang] __STDC_NO_THREADS__ is no longer necessary for VS 2022 1939 and above (#117149)
Since `__STDC_NO_THREADS__` is a reserved identifier,
- If `MSVC version < 17.9`
- C version < C11(201112L)
- When `<threads.h>` is unavailable `!__has_include(<threads.h>)` is
`__has_include` is defined.

Closes #115529
2025-01-27 09:30:53 -05:00
Robert Dazi
ddbfe6f7d2
[Sema] Fix __array_rank instantiation (#124491)
The type being queried was left as a template type parameter, making the
whole expression as dependent and thus not eligible to static_assert.

Fixes #123498

Co-authored-by: v01dxyz <v01dxyz@v01d.xyz>
Co-authored-by: cor3ntin <corentinjabot@gmail.com>
2025-01-27 12:43:37 +01:00
Manuel Sainz de Baranda y Goñi
33ad474c45
[Clang] Add predefined macros for integer constants (#123514)
This adds predefined macros for integer constants to implement section 7.18.4 of ISO/IEC 9899:1999 in `<stdint.h>` in a safe way:

```
__INT8_C(c)
__INT16_C(c)
__INT32_C(c)
__INT64_C(c)
__INTMAX_C(c)
__UINT8_C(c)
__UINT16_C(c)
__UINT32_C(c)
__UINT64_C(c)
__UINTMAX_C(c)
```

Which improves compatibility with GCC and makes it trivial to implement
section 7.18.4 of ISO/IEC 9899:1999.

Clang defines `__INT<N>_C_SUFFIX__`, `__UINT<N>_C_SUFFIX__`,
`__INTAX_C_SUFFIX__` and `__UINTMAX_C_SUFFIX__`, but these macros are
useless for this purpose.

Let's say, for example, that `__INT64_C_SUFFIX__` expands to `L` or
`LL`. If the user defines them as a macros, the compiler will produce
errors if `INT64_C` is implemented in `<stdint.h>` using
`__INT64_C_SUFFIX__`:

**minimal-test.c:**
```cpp
#if defined(__clang__) & !defined(__INT64_C)
#	pragma clang diagnostic push
#	pragma clang diagnostic ignored "-Wreserved-identifier"
#	define __PSTDC_INT_C_(literal, suffix) literal##suffix
#	define __PSTDC_INT_C(literal, suffix) __PSTDC_INT_C_(literal, suffix)
#	define INT64_C(literal) __PSTDC_INT_C(literal, __INT64_C_SUFFIX__)
#	pragma clang diagnostic pop
#elif defined(__GNUC__)
#	define INT64_C __INT64_C
#endif

typedef __INT64_TYPE__ int64_t;

#define L  "Make Clang produce an error"
#define LL "Make Clang produce an error"

int main(int argc, char **argv)
	{
	(void)argc; (void)argv;
	int64_t v = INT64_C(9223372036854775807);
	(void)v;
	return 0;
	}

```

<img width="697" alt="imagen"
src="https://github.com/user-attachments/assets/6df97af6-7cfd-4cf9-85b7-d7c854509325"
/>

**test.c:**
```cpp
#if defined(__clang__) && !defined(__INT8_C)
#	pragma clang diagnostic push
#	pragma clang diagnostic ignored "-Wreserved-identifier"

#	define __PSTDC_INT_C_(literal, suffix) literal##suffix
#	define __PSTDC_INT_C(literal, suffix) __PSTDC_INT_C_(literal, suffix)

#	define INT8_C(literal)    __PSTDC_INT_C(literal, __INT8_C_SUFFIX__)
#	define INT16_C(literal)   __PSTDC_INT_C(literal, __INT16_C_SUFFIX__)
#	define INT32_C(literal)   __PSTDC_INT_C(literal, __INT32_C_SUFFIX__)
#	define INT64_C(literal)   __PSTDC_INT_C(literal, __INT64_C_SUFFIX__)
#	define INTMAX_C(literal)  __PSTDC_INT_C(literal, __INTMAX_C_SUFFIX__)
#	define UINT8_C(literal)   __PSTDC_INT_C(literal, __UINT8_C_SUFFIX__)
#	define UINT16_C(literal)  __PSTDC_INT_C(literal, __UINT16_C_SUFFIX__)
#	define UINT32_C(literal)  __PSTDC_INT_C(literal, __UINT32_C_SUFFIX__)
#	define UINT64_C(literal)  __PSTDC_INT_C(literal, __UINT64_C_SUFFIX__)
#	define UINTMAX_C(literal) __PSTDC_INT_C(literal, __UINTMAX_C_SUFFIX__)

#	pragma clang diagnostic pop

#else
#	define INT8_C    __INT8_C
#	define INT16_C   __INT16_C
#	define INT32_C   __INT32_C
#	define INT64_C   __INT64_C
#	define INTMAX_C  __INTMAX_C
#	define UINT8_C   __UINT8_C
#	define UINT16_C  __UINT16_C
#	define UINT32_C  __UINT32_C
#	define UINT64_C  __UINT64_C
#	define UINTMAX_C __UINTMAX_C
#endif

typedef __INT8_TYPE__    int8_t;
typedef __INT16_TYPE__   int16_t;
typedef __INT32_TYPE__   int32_t;
typedef __INT64_TYPE__   int64_t;
typedef __INTMAX_TYPE__  intmax_t;
typedef __UINT8_TYPE__   uint8_t;
typedef __UINT16_TYPE__  uint16_t;
typedef __UINT32_TYPE__  uint32_t;
typedef __UINT64_TYPE__  uint64_t;
typedef __UINTMAX_TYPE__ uintmax_t;

#define L   "Make Clang produce an error"
#define LL  "Make Clang produce an error"
#define U   "Make Clang produce an error"
#define UL  "Make Clang produce an error"
#define ULL "Make Clang produce an error"

int main(int argc, char **argv)
	{
	(void)argc; (void)argv;

	int8_t    a = INT8_C   (127);
	int16_t   b = INT16_C  (32767);
	int32_t   c = INT32_C  (2147483647);
	int64_t   d = INT64_C  (9223372036854775807);
	intmax_t  e = INTMAX_C (9223372036854775807);
	uint8_t   f = UINT8_C  (255);
	uint16_t  g = UINT16_C (65535);
	uint32_t  h = UINT32_C (4294967295);
	uint64_t  i = UINT64_C (18446744073709551615);
	uintmax_t j = UINTMAX_C(18446744073709551615);

	(void)a; (void)b; (void)c; (void)d; (void)e;
	(void)f; (void)g; (void)h; (void)i; (void)j;
	return 0;
	}
```
2025-01-26 16:48:42 +01:00
cor3ntin
e4514293f9
[Clang] Correctly determine constexprness of dependent lambdas. (#124468)
We skipped checking if a lambda is constexpr if the parent context was
dependent, even if the lambda itself wasn't (and there is no other
opportunity to establish constexprness)


Fixes #114234
Fixes #97958
2025-01-26 16:17:21 +01:00
Valentyn Yukhymenko
f607e3fd23
[Clang][Sema] Reject declaring an alias template with the same name as its template parameter. (#123533)
The issue occurred because the template parameter scope was skipped
too early, before diagnosing the alias name shadowing.

To fix this, the patch moves it to after LookupName, such that the behavior
remains consistent with the typedef implementation.

Fixes llvm#123423
2025-01-25 15:01:40 +08:00
Matheus Izvekov
28ad8978ee
Reland: [clang] unified CWG2398 and P0522 changes; finishes implementation of P3310 (#124137)
This patch relands the following PRs:
* #111711
* #107350
* #111457

All of these patches were reverted due to an issue reported in
https://github.com/llvm/llvm-project/pull/111711#issuecomment-2406491485,
due to interdependencies.

---
[clang] Finish implementation of P0522

This finishes the clang implementation of P0522, getting rid
of the fallback to the old, pre-P0522 rules.

Before this patch, when partial ordering template template parameters,
we would perform, in order:
* If the old rules would match, we would accept it. Otherwise, don't
  generate diagnostics yet.
* If the new rules would match, just accept it. Otherwise, don't
  generate any diagnostics yet again.
* Apply the old rules again, this time with diagnostics.

This situation was far from ideal, as we would sometimes:
* Accept some things we shouldn't.
* Reject some things we shouldn't.
* Only diagnose rejection in terms of the old rules.

With this patch, we apply the P0522 rules throughout.

This needed to extend template argument deduction in order
to accept the historial rule for TTP matching pack parameter to non-pack
arguments.
This change also makes us accept some combinations of historical and P0522
allowances we wouldn't before.

It also fixes a bunch of bugs that were documented in the test suite,
which I am not sure there are issues already created for them.

This causes a lot of changes to the way these failures are diagnosed,
with related test suite churn.

The problem here is that the old rules were very simple and
non-recursive, making it easy to provide customized diagnostics,
and to keep them consistent with each other.

The new rules are a lot more complex and rely on template argument
deduction, substitutions, and they are recursive.

The approach taken here is to mostly rely on existing diagnostics,
and create a new instantiation context that keeps track of this context.

So for example when a substitution failure occurs, we use the error
produced there unmodified, and just attach notes to it explaining
that it occurred in the context of partial ordering this template
argument against that template parameter.

This diverges from the old diagnostics, which would lead with an
error pointing to the template argument, explain the problem
in subsequent notes, and produce a final note pointing to the parameter.

---
[clang] CWG2398: improve overload resolution backwards compat

With this change, we discriminate if the primary template and which partial
specializations would have participated in overload resolution prior to
P0522 changes.

We collect those in an initial set. If this set is not empty, or the
primary template would have matched, we proceed with this set as the
candidates for overload resolution.

Otherwise, we build a new overload set with everything else, and proceed
as usual.

---
[clang] Implement TTP 'reversed' pack matching for deduced function template calls.

Clang previously missed implementing P0522 pack matching
for deduced function template calls.
2025-01-23 20:37:33 -03:00
Oleksandr T.
4018317407
[Clang] restrict use of attribute names reserved by the C++ standard (#106036)
Fixes #92196

https://eel.is/c++draft/macro.names#2
> A translation unit shall not #define or #undef names lexically
identical to keywords, to the identifiers listed in Table
[4](https://eel.is/c++draft/lex.name#tab:lex.name.special), or to the
[attribute-token](https://eel.is/c++draft/dcl.attr.grammar#nt:attribute-token)s
described in [[dcl.attr]](https://eel.is/c++draft/dcl.attr), except that
the names likely and unlikely may be defined as function-like macros
([[cpp.replace]](https://eel.is/c++draft/cpp.replace))[.](https://eel.is/c++draft/macro.names#2.sentence-1)
2025-01-23 21:16:59 +02:00
cor3ntin
17756aa9c9
[Clang] [Release Notes] Implicit lifetimes are a C++23 feature 2025-01-23 12:19:52 +01:00
Dmitry Polukhin
cad6bbade0
[C++20][Modules] Fix crash/compiler error due broken AST links (#123648)
Summary:
This PR fixes bugreport
https://github.com/llvm/llvm-project/issues/122493 The root problem is
the same as before lambda function and DeclRefExpr references a variable
that does not belong to the same module as the enclosing function body.
Therefore iteration over the function body doesn’t visit the VarDecl.
Before this change RelatedDeclsMap was created only for canonical decl
but in reality it has to be done for the definition of the function that
does not always match the canonical decl.

Test Plan: check-clang
2025-01-23 10:35:58 +00:00