646 Commits

Author SHA1 Message Date
Krystian Stasiowski
c5f461918c
[Clang][Parse] Diagnose member template declarations with multiple declarators (#78243)
According to [temp.pre] p5:
> In a template-declaration, explicit specialization, or explicit instantiation the init-declarator-list in the declaration shall contain at most one declarator. 

A member-declaration that is a template-declaration or explicit-specialization contains a declaration, even though it declares a member. This means it _will_ contain an init-declarator-list (not a member-declarator-list), so [temp.pre] p5 applies.

This diagnoses declarations such as:
```
struct A
{
    template<typename T>
    static const int x = 0, f(); // error: a template declaration can only declare a single entity

    template<typename T>
    static const int g(), y = 0; // error: a template declaration can only declare a single entity
};
```
The diagnostic messages are the same as those of the equivalent namespace scope declarations.

Note: since we currently do not diagnose declarations with multiple abbreviated function template declarators at namespace scope e.g., `void f(auto), g(auto);`, so this patch does not add diagnostics for the equivalent member declarations.

This patch also refactors `ParseSingleDeclarationAfterTemplate` (now named `ParseDeclarationAfterTemplate`) to call `ParseDeclGroup` and return the resultant `DeclGroup`.
2024-02-01 11:19:04 -05:00
cor3ntin
ad1a65fcac
[Clang][C++26] Implement Pack Indexing (P2662R3). (#72644)
Implements https://isocpp.org/files/papers/P2662R3.pdf

The feature is exposed as an extension in older language modes.
Mangling is not yet supported and that is something we will have to do before release.
2024-01-27 10:23:38 +01:00
Egor Zhdan
77d21e758e
[APINotes] Upstream dependencies of Sema logic to apply API Notes to decls
This upstreams more of the Clang API Notes functionality that is
currently implemented in the Apple fork:
https://github.com/apple/llvm-project/tree/next/clang/lib/APINotes

This is the largest chunk of the API Notes functionality in the
upstreaming process. I will soon submit a follow-up patch to actually
enable usage of this functionality by having a Clang driver flag that
enables API Notes, along with tests.
2024-01-17 13:13:10 +00:00
Kazu Hirata
f3dcc2351c
[clang] Use StringRef::{starts,ends}_with (NFC) (#75149)
This patch replaces uses of StringRef::{starts,ends}with with
StringRef::{starts,ends}_with for consistency with
std::{string,string_view}::{starts,ends}_with in C++20.

I'm planning to deprecate and eventually remove
StringRef::{starts,ends}with.
2023-12-13 08:54:13 -08:00
Zahira Ammarguellat
b40c534656
[clang] Add support for -fcx-limited-range, #pragma CX_LIMITED_RANGE and -fcx-fortran-rules. (#70244)
This patch adds the #pragma CX_LIMITED_RANGE defined in the C
specification.
It also adds the options -f[no]cx-limited-range and
-f[no]cx-fortran-rules.
-fcx-limited-range enables algebraic formulas for complex multiplication
and division. This option is enabled with -ffast-math.
-fcx-fortran-rules enables algebraic formulas for complex multiplication
and enables Smith’s algorithm for complex division (SMITH, R. L.
Algorithm 116: Complex division. Commun. ACM 5, 8 (1962)).

---------

Signed-off-by: Med Ismail Bennani <ismail@bennani.ma>
Co-authored-by: Joseph Huber <jhuber6@vols.utk.edu>
Co-authored-by: Guray Ozen <guray.ozen@gmail.com>
Co-authored-by: Nishant Patel <nishant.b.patel@intel.com>
Co-authored-by: Jessica Clarke <jrtc27@jrtc27.com>
Co-authored-by: Petr Hosek <phosek@google.com>
Co-authored-by: Joseph Huber <35342157+jhuber6@users.noreply.github.com>
Co-authored-by: Craig Topper <craig.topper@sifive.com>
Co-authored-by: Alexander Yermolovich <43973793+ayermolo@users.noreply.github.com>
Co-authored-by: Usama Hameed <u_hameed@apple.com>
Co-authored-by: Philip Reames <preames@rivosinc.com>
Co-authored-by: Evgenii Kudriashov <evgenii.kudriashov@intel.com>
Co-authored-by: Fangrui Song <i@maskray.me>
Co-authored-by: Aart Bik <39774503+aartbik@users.noreply.github.com>
Co-authored-by: Valentin Clement <clementval@gmail.com>
Co-authored-by: Youngsuk Kim <youngsuk.kim@hpe.com>
Co-authored-by: Arthur Eubanks <aeubanks@google.com>
Co-authored-by: Jan Svoboda <jan_svoboda@apple.com>
Co-authored-by: Walter Erquinigo <a20012251@gmail.com>
Co-authored-by: Eric <eric@efcs.ca>
Co-authored-by: Fazlay Rabbi <106703039+mdfazlay@users.noreply.github.com>
Co-authored-by: Pete Lawrence <plawrence@apple.com>
Co-authored-by: Jonas Devlieghere <jonas@devlieghere.com>
Co-authored-by: Adrian Prantl <aprantl@apple.com>
Co-authored-by: Owen Pan <owenpiano@gmail.com>
Co-authored-by: LLVM GN Syncbot <llvmgnsyncbot@gmail.com>
Co-authored-by: Med Ismail Bennani <ismail@bennani.ma>
Co-authored-by: Congcong Cai <congcongcai0907@163.com>
Co-authored-by: Rik Huijzer <github@huijzer.xyz>
Co-authored-by: Wang Pengcheng <wangpengcheng.pp@bytedance.com>
Co-authored-by: Yuanfang Chen <tabloid.adroit@gmail.com>
Co-authored-by: Kazu Hirata <kazu@google.com>
Co-authored-by: Mehdi Amini <joker.eph@gmail.com>
Co-authored-by: Aiden Grossman <agrossman154@yahoo.com>
Co-authored-by: Rana Pratap Reddy <109514914+ranapratap55@users.noreply.github.com>
Co-authored-by: Yingwei Zheng <dtcxzyw2333@gmail.com>
Co-authored-by: Piotr Zegar <me@piotrzegar.pl>
Co-authored-by: KAWASHIMA Takahiro <t-kawashima@fujitsu.com>
Co-authored-by: Tobias Hieta <tobias@hieta.se>
Co-authored-by: Luke Lau <luke@igalia.com>
Co-authored-by: Shivam Gupta <shivam98.tkg@gmail.com>
Co-authored-by: cor3ntin <corentinjabot@gmail.com>
Co-authored-by: Yeting Kuo <46629943+yetingk@users.noreply.github.com>
Co-authored-by: Stanislav Mekhanoshin <rampitec@users.noreply.github.com>
Co-authored-by: David Spickett <david.spickett@linaro.org>
Co-authored-by: Matthew Devereau <matthew.devereau@arm.com>
Co-authored-by: Martin Storsjö <martin@martin.st>
Co-authored-by: Qiu Chaofan <qiucofan@cn.ibm.com>
Co-authored-by: Pierre van Houtryve <pierre.vanhoutryve@amd.com>
Co-authored-by: Mikael Holmen <mikael.holmen@ericsson.com>
Co-authored-by: Uday Bondhugula <uday@polymagelabs.com>
Co-authored-by: Nikita Popov <npopov@redhat.com>
Co-authored-by: Johannes Reifferscheid <jreiffers@google.com>
Co-authored-by: Benjamin Kramer <benny.kra@googlemail.com>
Co-authored-by: Oliver Stannard <oliver.stannard@arm.com>
Co-authored-by: Dmitry Vyukov <dvyukov@google.com>
Co-authored-by: Benjamin Maxwell <benjamin.maxwell@arm.com>
Co-authored-by: Piotr Sobczak <piotr.sobczak@amd.com>
Co-authored-by: Simon Pilgrim <llvm-dev@redking.me.uk>
Co-authored-by: Timm Bäder <tbaeder@redhat.com>
Co-authored-by: Sunil Kuravinakop <koops@hpe.com>
Co-authored-by: zhongyunde 00443407 <zhongyunde@huawei.com>
Co-authored-by: Christudasan Devadasan <Christudasan.Devadasan@amd.com>
Co-authored-by: bjacob <jacob.benoit.1@gmail.com>
Co-authored-by: Weining Lu <luweining@loongson.cn>
Co-authored-by: Andrzej Warzyński <andrzej.warzynski@arm.com>
Co-authored-by: Jay Foad <jay.foad@amd.com>
Co-authored-by: Markus Mützel <markus.muetzel@gmx.de>
Co-authored-by: Erik Jonsson <erik.j.jonsson@ericsson.com>
Co-authored-by: Pete Steinfeld <47540744+psteinfeld@users.noreply.github.com>
Co-authored-by: Alexey Bataev <a.bataev@outlook.com>
Co-authored-by: Louis Dionne <ldionne.2@gmail.com>
Co-authored-by: Qizhi Hu <836744285@qq.com>
2023-12-11 10:03:27 -05:00
Erich Keane
64b6ef02e2
[OpenACC] Implement initial parsing for parallel construct (#72661)
As the first real parsing effort for the OpenACC implementation effort,
this implements the parsing for first construct/directive name. This
does not do any semantic analysis, nor any of the clauses. Those will
come in a future patch.

For the time being, we warn when we hit a point that we don't implement
the parsing for either of these situations.
2023-11-17 10:47:42 -08:00
erichkeane
7d1a9e81b0 [OpenACC] Rename ParseOpenACCDirective to ParseOpenACCDirectiveDecl
The former name is more useful as a callee of the function in a future
patch, so as suggested in that review, move the rename here.
2023-11-17 07:28:33 -08:00
Erich Keane
ff219ea9ca
[OpenACC] Initial commits to support OpenACC (#70234)
Initial commits to support OpenACC.  This patchset:

adds a clang-command line argument '-fopenacc', and starts
 to define _OPENACC, albeit to '1' instead of the standardized
value (since we don't properly implement OpenACC yet).

The OpenACC spec defines `_OPENACC` to be equal to the latest standard
implemented. However, since we're not done implementing any standard,
we've defined this by default to be `1`. As it is useful to run our
compiler against existing OpenACC workloads, we're providing a
temporary override flag to change the `_OPENACC` value to be any
entirely digit value, permitting testing against any existing OpenACC
project.

Exactly like the OpenMP parser, the OpenACC pragma parser needs to
consume and reprocess the tokens. This patch sets up the infrastructure
to do so by refactoring the OpenMP version of this into a more general
version that works for OpenACC as well.

Additionally, this adds a few diagnostics and token kinds to get us
started.
2023-11-17 06:29:02 -08:00
Ying Yi
700d93b058 Add two time-trace scope variables.
A time trace scope variable of `ParseDeclarationOrFunctionDefinition`
with the function's source location is added to record the time spent
parsing the function's declaration or definition. Another time trace
scope variable of `ParseFunctionDefinition` is also added to record the
name of the defined function. A release note is added as well.

Reviewed by: Aaron Ballman
Pull request: #65268
2023-11-01 13:37:52 +00:00
Nikita Popov
03ec84a00b Revert "Add two time-trace scope variables."
This reverts commit 33b85867e30e1adc2ff2173039c199b81c10f52b.

This causes a large compile-time regression (about 1% for unoptimized
builds).
2023-10-31 10:46:49 +01:00
Ying Yi
33b85867e3 Add two time-trace scope variables.
A time trace scope variable of `ParseDeclarationOrFunctionDefinition`
with the function's source location is added to record the time spent
parsing the function's declaration or definition. Another time trace
scope variable of `ParseFunctionDefinition` is also added to record the
name of the defined function. A release note is added as well.

Reviewed by: Aaron Ballman
Pull request: #65268
2023-10-31 09:16:06 +00:00
Timm Bäder
b406819832 [clang][Parser][NFC] Reformat if statement
Pull the nested if statement into the outer one.
2023-09-28 12:32:30 +02:00
Chuanqi Xu
f9558c6911 [C++20] [Modules] Handle import decl before module declaration without being in GMF
Close https://github.com/llvm/llvm-project/issues/67627

In a module unit, all the declaration before the modoule declaration
should live in the GMF.
2023-09-28 10:24:50 +08:00
Ben Barham
265d48a02d
Re-apply "[Parse] Split incremental-extensions" (#66446)
Re-applies #65683 with a fix to always run
`Actions.ActOnEndOfTranslationUnit` regardless of incremental
processing.
2023-09-20 23:35:34 -07:00
Ben Barham
f8ced20ad3
Revert "[Parse] Split incremental-extensions" (#66281)
This reverts commit c2fb112021529c635cccd8bb9d846b2c64fc291d, which
breaks:
```
lldb-api.commands/expression/diagnostics.TestExprDiagnostics.py
lldb-api.lang/objc/modules.TestObjCModules.py
lldb-api.lang/objc/modules-incomplete.TestIncompleteModules.py
lldb-api.lang/objc/modules-non-objc-target.TestObjCModulesNonObjCTarget.py
lldb-api.lang/objc/modules-objc-property.TestModulesObjCProperty.py
```
2023-09-13 14:55:01 -07:00
Ben Barham
4c264c26d7
[Parse] Split incremental-extensions (#65683)
The preprocessor `IncrementalProcessing` option was being used to
control whether or not to teardown the lexer or run the end of
translation unit action. In D127284 this was merged with
`-fincremental-extensions`, which also changes top level parsing.

Split these again so that the former behavior can be achieved without
the latter (ie. to allow managing lifetime without also changing
parsing).

Resolves rdar://113406310.
2023-09-11 17:40:43 -07:00
Fred Fu
79af92bb99 Reland "[clang-repl] support code completion at a REPL."
Original commit message:
"
This patch enabled code completion for ClangREPL. The feature was built upon
three existing Clang components: a list completer for LineEditor, a
CompletionConsumer from SemaCodeCompletion, and the ASTUnit::codeComplete method.
The first component serves as the main entry point of handling interactive inputs.

Because a completion point for a compiler instance has to be unchanged once it
is set, an incremental compiler instance is created for each code
completion. Such a compiler instance carries over AST context source from the
main interpreter compiler in order to obtain declarations or bindings from
previous input in the same REPL session.

The most important API codeComplete in Interpreter/CodeCompletion is a thin
wrapper that calls with ASTUnit::codeComplete with necessary arguments, such as
a code completion point and a ReplCompletionConsumer, which communicates
completion results from SemaCodeCompletion back to the list completer for the
REPL.

In addition, PCC_TopLevelOrExpression and CCC_TopLevelOrExpression` top levels
were added so that SemaCodeCompletion can treat top level statements like
expression statements at the REPL. For example,

clang-repl> int foo = 42;
clang-repl> f<tab>

From a parser's persective, the cursor is at a top level. If we used code
completion without any changes, PCC_Namespace would be supplied to
Sema::CodeCompleteOrdinaryName, and thus the completion results would not
include foo.

Currently, the way we use PCC_TopLevelOrExpression and
CCC_TopLevelOrExpression is no different from the way we use PCC_Statement
and CCC_Statement respectively.

Differential revision: https://reviews.llvm.org/D154382
"

The new patch also fixes clangd and several memory issues that the bots reported
and upload the missing files.
2023-08-28 20:09:03 +00:00
Vassil Vassilev
752f87cd6a Revert "Reland "[clang-repl] support code completion at a REPL.""
This reverts commit 5ab25a42ba70c4b50214b0e78eaaccd30696fa09 due to forgotten
files.
2023-08-28 20:05:14 +00:00
Fred Fu
5ab25a42ba Reland "[clang-repl] support code completion at a REPL."
Original commit message:
"
This patch enabled code completion for ClangREPL. The feature was built upon
three existing Clang components: a list completer for LineEditor, a
CompletionConsumer from SemaCodeCompletion, and the ASTUnit::codeComplete method.
The first component serves as the main entry point of handling interactive inputs.

Because a completion point for a compiler instance has to be unchanged once it
is set, an incremental compiler instance is created for each code
completion. Such a compiler instance carries over AST context source from the
main interpreter compiler in order to obtain declarations or bindings from
previous input in the same REPL session.

The most important API codeComplete in Interpreter/CodeCompletion is a thin
wrapper that calls with ASTUnit::codeComplete with necessary arguments, such as
a code completion point and a ReplCompletionConsumer, which communicates
completion results from SemaCodeCompletion back to the list completer for the
REPL.

In addition, PCC_TopLevelOrExpression and CCC_TopLevelOrExpression` top levels
were added so that SemaCodeCompletion can treat top level statements like
expression statements at the REPL. For example,

clang-repl> int foo = 42;
clang-repl> f<tab>

From a parser's persective, the cursor is at a top level. If we used code
completion without any changes, PCC_Namespace would be supplied to
Sema::CodeCompleteOrdinaryName, and thus the completion results would not
include foo.

Currently, the way we use PCC_TopLevelOrExpression and
CCC_TopLevelOrExpression is no different from the way we use PCC_Statement
and CCC_Statement respectively.

Differential revision: https://reviews.llvm.org/D154382
"

The new patch also fixes clangd and several memory issues that the bots reported.
2023-08-28 19:59:56 +00:00
Vassil Vassilev
f94a937cb3 Revert "[clang-repl] support code completion at a REPL."
This reverts commit eb0e6c3134ef6deafe0a4958e9e1a1214b3c2f14 due to failures in
clangd such as https://lab.llvm.org/buildbot/#/builders/57/builds/29377
2023-08-23 14:46:15 +00:00
Fred Fu
eb0e6c3134 [clang-repl] support code completion at a REPL.
This patch enabled code completion for ClangREPL. The feature was built upon
three existing Clang components: a list completer for LineEditor, a
CompletionConsumer from SemaCodeCompletion, and the ASTUnit::codeComplete method.
The first component serves as the main entry point of handling interactive inputs.

Because a completion point for a compiler instance has to be unchanged once it
is set, an incremental compiler instance is created for each code
completion. Such a compiler instance carries over AST context source from the
main interpreter compiler in order to obtain declarations or bindings from
previous input in the same REPL session.

The most important API codeComplete in Interpreter/CodeCompletion is a thin
wrapper that calls with ASTUnit::codeComplete with necessary arguments, such as
a code completion point and a ReplCompletionConsumer, which communicates
completion results from SemaCodeCompletion back to the list completer for the
REPL.

In addition, PCC_TopLevelOrExpression and CCC_TopLevelOrExpression` top levels
were added so that SemaCodeCompletion can treat top level statements like
expression statements at the REPL. For example,

clang-repl> int foo = 42;
clang-repl> f<tab>

From a parser's persective, the cursor is at a top level. If we used code
completion without any changes, PCC_Namespace would be supplied to
Sema::CodeCompleteOrdinaryName, and thus the completion results would not
include foo.

Currently, the way we use PCC_TopLevelOrExpression and
CCC_TopLevelOrExpression is no different from the way we use PCC_Statement
and CCC_Statement respectively.

Differential revision: https://reviews.llvm.org/D154382
2023-08-23 14:00:59 +00:00
Aaron Ballman
0ce056a814 [C23] Rename C2x -> C23; NFC
This does the rename for most internal uses of C2x, but does not rename
or reword diagnostics (those will be done in a follow-up).

I also updated standards references and citations to the final wording
in the standard.
2023-08-11 07:43:43 -04:00
Corentin Jabot
a8bef8865e [Clang] Implement P2169 A nice placeholder with no name
This is a C++ feature that allows the use of `_` to
declare multiple variable of that name in the same scope;
these variables can then not be referred to.

In addition, while P2169 does not extend to parameter
declarations, we stop warning on unused parameters of that name,
for consistency.

The feature is backported to all C++ language modes.

Reviewed By: #clang-language-wg, aaron.ballman

Differential Revision: https://reviews.llvm.org/D153536
2023-08-04 16:51:15 +02:00
Richard Sandiford
33ee5c4663 [clang] Add Parse and Sema support for RegularKeyword attributes
This patch adds the Parse and Sema support for RegularKeyword attributes,
following on from a previous patch that added Attr.td support.

The patch is quite large.  However, nothing outside the tests is
specific to the first RegularKeyword attribute (__arm_streaming).
The patch should therefore be a one-off, up-front cost.  Other
attributes just need an entry in Attr.td and the usual Sema support.

The approach taken in the patch is that the keywords can be used with
any language version.  If standard attributes were added in language
version Y, the keyword rules for version X<Y are the same as they were
for version Y (to the extent possible).  Any extensions beyond Y are
handled in the same way for both keywords and attributes.  This ensures
that existing C++11 successors like C++17 are not treated differently
from versions that have yet to be defined.

Some notes on the implementation:

* The patch emits errors rather than warnings for diagnostics that
relate to keywords.

* Where possible, the patch drops “attribute” from diagnostics
relating to keywords.

* One exception to the previous point is that warnings about C++
extensions do still mention attributes.  The use there seemed OK
since the diagnostics are noting a change in the production rules.

* If a diagnostic string needs to be different for keywords and
attributes, the patch standardizes on passing the attribute/
name/token followed by 0 for attributes and 1 for keywords.

* Although the patch updates warn_attribute_wrong_decl_type_str,
warn_attribute_wrong_decl_type, and warn_attribute_wrong_decl_type,
only the error forms of these strings are used for keywords.

* I couldn't trigger the warnings in checkUnusedDeclAttributes,
even for existing attributes.  An assert on the warnings caused
no failures in the testsuite.  I think in practice all standard
attributes would be diagnosed before this.

* The patch drops a call to standardAttributesAllowed in
ParseFunctionDeclarator.  This is because MaybeParseCXX11Attributes
checks the same thing itself, where appropriate.

* The new tests are based on c2x-attributes.c and
cxx0x-attributes.cpp.  The C++ test also incorporates a version of
cxx11-base-spec-attributes.cpp.  The FIXMEs are carried across from
the originals.

Differential Revision: https://reviews.llvm.org/D148702
2023-05-31 10:43:10 +01:00
Corentin Jabot
1b0ba1c12f [Clang] Fix parsing of (auto(x)).
Allow auto(x) to appear in a parenthesis
expression.

The pattern (auto( can appear as part of a declarator,
so the parser is modified to avoid the ambiguity,
in a way consistent with the proposed resolution to CWG1223.

Reviewed By: aaron.ballman, #clang-language-wg

Differential Revision: https://reviews.llvm.org/D149276
2023-05-20 13:22:58 +02:00
Jun Zhang
247fa04116
[clang] Add a new annotation token: annot_repl_input_end
This patch is the first part of the below RFC:
https://discourse.llvm.org/t/rfc-handle-execution-results-in-clang-repl/68493

It adds an annotation token which will replace the original EOF token
when we are in the incremental C++ mode. In addition, when we're
parsing an ExprStmt and there's a missing semicolon after the
expression, we set a marker in the annotation token and continue
parsing.

Eventually, we propogate this info in ParseTopLevelStmtDecl and are able
to mark this Decl as something we want to do value printing. Below is a
example:

clang-repl> int x = 42;
clang-repl> x
// `x` is a TopLevelStmtDecl and without a semicolon, we should set
// it's IsSemiMissing bit so we can do something interesting in
// ASTConsumer::HandleTopLevelDecl.

The idea about annotation toke is proposed by Richard Smith, thanks!

Signed-off-by: Jun Zhang <jun@junz.org>

Differential Revision: https://reviews.llvm.org/D148997
2023-05-16 20:10:43 +08:00
Corentin Jabot
d4a6e4c1ee Revert "[Clang] Fix parsing of (auto(x))."
This reverts commit ef47318ec3615e83c328b07341046dfb9d869414.

This patch breaks valid code https://reviews.llvm.org/D149276#4345620
2023-05-16 13:56:33 +02:00
Corentin Jabot
ef47318ec3 [Clang] Fix parsing of (auto(x)).
Allow auto(x) to appear in a parenthesis
expression.

The pattern (auto( can appear as part of a declarator,
so the parser is modified to avoid the ambiguity,
in a way consistent with the proposed resolution to CWG1223.

Reviewed By: aaron.ballman, #clang-language-wg

Differential Revision: https://reviews.llvm.org/D149276
2023-05-16 08:13:54 +02:00
Corentin Jabot
abf4a8cb15 [Clang] Improve diagnostics when using a concept as template argument
When using the name of a template variable or concept in places
where an expression was expected, Clang would drop the cxxscope token
preceeding it, if any.

This leads to subpar diagnostics - complaining about the
identifier being undeclared as clang would not know to look into a
non-global scope.

We make sure the scope is preserved.

When encountering `ns::Concept foo x;`, Clang would also fail
to provide the same quality as it does at global scope.

Reviewed By: aaron.ballman, erichkeane

Differential Revision: https://reviews.llvm.org/D146719
2023-03-30 16:30:23 +02:00
Alex Lorenz
c8b37e48f6 [clang] extend external_source_symbol attribute with USR clause
Allow the user to specify a concrete USR in the external_source_symbol attribute.
That will let Clang's indexer to use Swift USRs for Swift declarations that are
represented with C++ declarations.

This new clause is used by Swift when generating a C++ header representation
of a Swift module:
https://github.com/apple/swift/pull/63002

Differential Revision: https://reviews.llvm.org/D141324
2023-02-23 14:59:26 -08:00
Chuanqi Xu
612f3ac26f [Modules] Remove -fmodules-ts
As the diagnostic message shows, we should remove -fmodules-ts flag in
clang/llvm17. Since clang/llvm16 is already branched. We can remove the
depreacared flag now.
2023-02-16 14:40:32 +08:00
Chuanqi Xu
10d85dc754 [C++20] [Modules] Pop Expression Evaluation Context when we skip its body during parsing
Close https://github.com/llvm/llvm-project/issues/60275

The root cause of issue 60275 is the imbalance of
PushExpressionEvaluationContext() and PopExpressionEvaluationContext().

See
f1c4f927f7/clang/lib/Parse/Parser.cpp (L1396-L1437)

We will PushExpressionEvaluationContext() in ActOnStartOfFunctionDef()
in line 1396 and we should pop it in ActOnFinishFunctionBody later.
However if we skip the function body in line 1402, the expression
evaluation context will not be popped. Then here is the issue report. I
fix the issue by inserting codes to pop the expression evaluation
context explicitly if the function body is skipped. Maybe this looks
like an ad-hoc fix. But if we want to fix this in a pretty way, we
should refactor the current framework for pushing and popping expression
evaluation contexts. Currently there are 23
PushExpressionEvaluationContext() callsities and 21
PopExpressionEvaluationContext() callsites in the code. And it seems not
easy to balance them well and fast. So I suggest to land this fix first.
At least it can prevent the crash.

Reviewed By: cor3ntin

Differential Revision: https://reviews.llvm.org/D143053
2023-02-03 10:27:02 +08:00
Iain Sandoe
53a1314ed1 [C++20][Modules] Fix named module import diagnostics.
We have been incorrectly disallowing imports of named modules in the
global and private module fragments.

This addresses: https://github.com/llvm/llvm-project/issues/59688

Differential Revision: https://reviews.llvm.org/D140927
2023-01-22 10:22:36 +00:00
Kazu Hirata
5891420e68 [clang] Use std::nullopt instead of None (NFC)
This patch mechanically replaces None with std::nullopt where the
compiler would warn if None were deprecated.  The intent is to reduce
the amount of manual work required in migrating from Optional to
std::optional.

This is part of an effort to migrate from llvm::Optional to
std::optional:

https://discourse.llvm.org/t/deprecating-llvm-optional-x-hasvalue-getvalue-getvalueor/63716
2022-12-03 11:54:46 -08:00
Vassil Vassilev
dc4889357a [clang-repl] Support statements on global scope in incremental mode.
This patch teaches clang to parse statements on the global scope to allow:
```
./bin/clang-repl
clang-repl> int i = 12;
clang-repl> ++i;
clang-repl> extern "C" int printf(const char*,...);
clang-repl> printf("%d\n", i);
13
clang-repl> %quit
```

Generally, disambiguating between statements and declarations is a non-trivial
task for a C++ parser. The challenge is to allow both standard C++ to be
translated as if this patch does not exist and in the cases where the user typed
a statement to be executed as if it were in a function body.

Clang's Parser does pretty well in disambiguating between declarations and
expressions. We have added DisambiguatingWithExpression flag which allows us to
preserve the existing and optimized behavior where needed and implement the
extra rules for disambiguating. Only few cases require additional attention:
  * Constructors/destructors -- Parser::isConstructorDeclarator was used in to
    disambiguate between ctor-looking declarations and statements on the global
    scope(eg. `Ns::f()`).
  * The template keyword -- the template keyword can appear in both declarations
    and statements. This patch considers the template keyword to be a declaration
    starter which breaks a few cases in incremental mode which will be tackled
    later.
  * The inline (and similar) keyword -- looking at the first token in many cases
    allows us to classify what is a declaration.
  * Other language keywords and specifiers -- ObjC/ObjC++/OpenCL/OpenMP rely on
    pragmas or special tokens which will be handled in subsequent patches.

The patch conceptually models a "top-level" statement into a TopLevelStmtDecl.
The TopLevelStmtDecl is lowered into a void function with no arguments.
We attach this function to the global initializer list to execute the statement
blocks in the correct order.

Differential revision: https://reviews.llvm.org/D127284
2022-12-03 07:18:07 +00:00
Saleem Abdulrasool
b78d5380da parse: process GNU and standard attributes on top-level decls
We would previously reject valid input where GNU attributes preceded the
standard attributes on top-level declarations. A previous attribute
handling change had begun rejecting this whilst GCC does honour this
layout. In practice, this breaks use of `extern "C"` attributed
functions which use both standard and GNU attributes as experienced by
the Swift runtime.

Objective-C deserves an honourable mention for requiring some additional
special casing. Because attributes on declarations and definitions
differ in semantics, we need to replicate some of the logic for
detecting attributes to declarations to which they appertain cannot be
attributed. This should match the existing case for the application of
GNU attributes to interfaces, protocols, and implementations.

Take the opportunity to split out the tooling tests into two cases: ones
which process macros and ones which do not.

Special thanks to Aaron Ballman for the many hints and extensive rubber
ducking that was involved in identifying the various places where we
accidentally dropped attributes.

Differential Revision: https://reviews.llvm.org/D137979
Fixes: #58229
Reviewed By: aaron.ballman, arphaman
2022-11-21 22:34:50 +00:00
Jialun Hu
94e8bd002c
[clang] Fix crash upon stray coloncolon token in C2x mode
The parser assumes that the lexer never emits coloncolon token for C code, but this assumption no longer holds in C2x attribute namespaces. As a result, stray coloncolon tokens out of attributes cause assertion failures and hangs in release build, which this patch tries to handle.

Crash input minimal example: `T n::v`

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D133248
2022-10-18 21:57:32 +08:00
Nicolas Lesser
4848f3bf2f [C++2a] P0634r3: Down with typename!
This patch implements P0634r3 that removes the need for 'typename' in certain contexts.

For example,

```
template <typename T>
using foo = T::type; // ok
```

This is also allowed in previous language versions as an extension, because I think it's pretty useful. :)

Reviewed By: #clang-language-wg, erichkeane

Differential Revision: https://reviews.llvm.org/D53847
2022-09-28 09:50:19 -07:00
Xiang Li
782ac2182c [HLSL] Support cbuffer/tbuffer for hlsl.
This is first part for support cbuffer/tbuffer.

The format for cbuffer/tbuffer is
BufferType [Name] [: register(b#)] { VariableDeclaration [: packoffset(c#.xyzw)]; ... };

More details at https://docs.microsoft.com/en-us/windows/win32/direct3dhlsl/dx-graphics-hlsl-constants

New keyword 'cbuffer' and 'tbuffer' are added.
New AST node HLSLBufferDecl is added.
Build AST for simple cbuffer/tbuffer without attribute support.

The special thing is variables declared inside cbuffer is exposed into global scope.
So isTransparentContext should return true for HLSLBuffer.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D129883
2022-09-21 10:07:43 -07:00
Fangrui Song
3f18f7c007 [clang] LLVM_FALLTHROUGH => [[fallthrough]]. NFC
With C++17 there is no Clang pedantic warning or MSVC C5051.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D131346
2022-08-08 09:12:46 -07:00
Muhammad Usman Shahid
76476efd68 Rewording "static_assert" diagnostics
This patch rewords the static assert diagnostic output. Failing a
_Static_assert in C should not report that static_assert failed. This
changes the wording to be more like GCC and uses "static assertion"
when possible instead of hard coding the name. This also changes some
instances of 'static_assert' to instead be based on the token in the
source code.

Differential Revision: https://reviews.llvm.org/D129048
2022-07-25 07:22:54 -04:00
Erich Keane
1da3119025 Revert "Rewording the "static_assert" to static assertion"
Looks like we again are going to have problems with libcxx tests that
are overly specific in their dependency on clang's diagnostics.

This reverts commit 6542cb55a3eb115b1c3592514590a19987ffc498.
2022-07-21 06:40:14 -07:00
Muhammad Usman Shahid
6542cb55a3 Rewording the "static_assert" to static assertion
This patch is basically the rewording of the static assert statement's
output(error) on screen after failing. Failing a _Static_assert in C
should not report that static_assert failed. It’d probably be better to
reword the diagnostic to be more like GCC and say “static assertion”
failed in both C and C++.

consider a c file having code

_Static_assert(0, "oh no!");

In clang the output is like:

<source>:1:1: error: static_assert failed: oh no!
_Static_assert(0, "oh no!");
^              ~
1 error generated.
Compiler returned: 1

Thus here the "static_assert" is not much good, it will be better to
reword it to the "static assertion failed" to more generic. as the gcc
prints as:

<source>:1:1: error: static assertion failed: "oh no!"
    1 | _Static_assert(0, "oh no!");
          | ^~~~~~~~~~~~~~
          Compiler returned: 1

The above can also be seen here. This patch is about rewording
the static_assert to static assertion.

Differential Revision: https://reviews.llvm.org/D129048
2022-07-21 06:34:14 -07:00
Mitch Phillips
041d4012e4 Revert "Rewording "static_assert" diagnostics"
This reverts commit b7e77ff25fb2412f6ab6d6cc756666b0e2f97bd3.

Reason: Broke sanitizer builds bots + libcxx. 'static assertion
expression is not an integral constant expression'. More details
available in the Phabricator review: https://reviews.llvm.org/D129048
2022-07-14 10:59:20 -07:00
Muhammad Usman Shahid
b7e77ff25f Rewording "static_assert" diagnostics
This patch rewords the static assert diagnostic output. Failing a
_Static_assert in C should not report that static_assert failed. This
changes the wording to be more like GCC and uses "static assertion"
when possible instead of hard coding the name. This also changes some
instances of 'static_assert' to instead be based on the token in the
source code.

Differential Revision: https://reviews.llvm.org/D129048
2022-07-14 07:47:37 -04:00
Iain Sandoe
af2d11b1d5 [C++20][Modules] Implement include translation.
This addresses [cpp.include]/7

(when encountering #include header-name)

If the header identified by the header-name denotes an importable header, it
is implementation-defined whether the #include preprocessing directive is
instead replaced by an import directive.

In this implementation, include translation is performed _only_ for headers
in the Global Module fragment, so:
```
module;
 #include "will-be-translated.h" // IFF the header unit is available.

export module M;
 #include "will-not-be-translated.h" // even if the header unit is available
```
The reasoning is that, in general, includes in the module purview would not
be validly translatable (they would have to immediately follow the module
decl and without any other intervening decls).  Otherwise that would violate
the rules on contiguous import directives.

This would be quite complex to track in the preprocessor, and for relatively
little gain (the user can 'import "will-not-be-translated.h";' instead.)

TODO: This is one area where it becomes increasingly difficult to disambiguate
clang modules in C++ from C++ standard modules.  That needs to be addressed in
both the driver and the FE.

Differential Revision: https://reviews.llvm.org/D128981
2022-07-10 11:06:51 +01:00
Corentin Jabot
a9a60f20e6 [Clang] Rename StringLiteral::isAscii() => isOrdinary() [NFC]
"Ascii" StringLiteral instances are actually narrow strings
that are UTF-8 encoded and do not have an encoding prefix.
(UTF8 StringLiteral are also UTF-8 encoded strings, but with
the u8 prefix.

To avoid possible confusion both with actuall ASCII strings,
and with future works extending the set of literal encodings
supported by clang, this rename StringLiteral::isAscii() to
isOrdinary(), matching C++ standard terminology.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D128762
2022-06-29 18:28:51 +02:00
Martin Boehme
86866107b8 [Clang] Fix: Restore warning inadvertently removed by D126061.
Before D126061, Clang would warn about this code

```
struct X {
    [[deprecated]] struct Y {};
};
```

with the warning

    attribute 'deprecated' is ignored, place it after "struct" to apply attribute to type declaration

D126061 inadvertently caused this warning to no longer be emitted. This patch
restores the previous behavior.

The reason for the bug is that after D126061, C++11 attributes applied to a
member declaration are no longer placed in `DS.getAttributes()` but are instead
tracked in a separate list (`DeclAttrs`). In the case of a free-standing
decl-specifier-seq, we would simply ignore the contents of this list. Instead,
we now pass the list on to `Sema::ParsedFreeStandingDeclSpec()` so that it can
issue the appropriate warning.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D128499
2022-06-28 08:52:58 +02:00
Martin Boehme
8c7b64b5ae [clang] Reject non-declaration C++11 attributes on declarations
For backwards compatiblity, we emit only a warning instead of an error if the
attribute is one of the existing type attributes that we have historically
allowed to "slide" to the `DeclSpec` just as if it had been specified in GNU
syntax. (We will call these "legacy type attributes" below.)

The high-level changes that achieve this are:

- We introduce a new field `Declarator::DeclarationAttrs` (with appropriate
  accessors) to store C++11 attributes occurring in the attribute-specifier-seq
  at the beginning of a simple-declaration (and other similar declarations).
  Previously, these attributes were placed on the `DeclSpec`, which made it
  impossible to reconstruct later on whether the attributes had in fact been
  placed on the decl-specifier-seq or ahead of the declaration.

- In the parser, we propgate declaration attributes and decl-specifier-seq
  attributes separately until we can place them in
  `Declarator::DeclarationAttrs` or `DeclSpec::Attrs`, respectively.

- In `ProcessDeclAttributes()`, in addition to processing declarator attributes,
  we now also process the attributes from `Declarator::DeclarationAttrs` (except
  if they are legacy type attributes).

- In `ConvertDeclSpecToType()`, in addition to processing `DeclSpec` attributes,
  we also process any legacy type attributes that occur in
  `Declarator::DeclarationAttrs` (and emit a warning).

- We make `ProcessDeclAttribute` emit an error if it sees any non-declaration
  attributes in C++11 syntax, except in the following cases:
  - If it is being called for attributes on a `DeclSpec` or `DeclaratorChunk`
  - If the attribute is a legacy type attribute (in which case we only emit
    a warning)

The standard justifies treating attributes at the beginning of a
simple-declaration and attributes after a declarator-id the same. Here are some
relevant parts of the standard:

- The attribute-specifier-seq at the beginning of a simple-declaration
  "appertains to each of the entities declared by the declarators of the
  init-declarator-list" (https://eel.is/c++draft/dcl.dcl#dcl.pre-3)

- "In the declaration for an entity, attributes appertaining to that entity can
  appear at the start of the declaration and after the declarator-id for that
  declaration." (https://eel.is/c++draft/dcl.dcl#dcl.pre-note-2)

- "The optional attribute-specifier-seq following a declarator-id appertains to
  the entity that is declared."
  (https://eel.is/c++draft/dcl.dcl#dcl.meaning.general-1)

The standard contains similar wording to that for a simple-declaration in other
similar types of declarations, for example:

- "The optional attribute-specifier-seq in a parameter-declaration appertains to
  the parameter." (https://eel.is/c++draft/dcl.fct#3)

- "The optional attribute-specifier-seq in an exception-declaration appertains
  to the parameter of the catch clause" (https://eel.is/c++draft/except.pre#1)

The new behavior is tested both on the newly added type attribute
`annotate_type`, for which we emit errors, and for the legacy type attribute
`address_space` (chosen somewhat randomly from the various legacy type
attributes), for which we emit warnings.

Depends On D111548

Reviewed By: aaron.ballman, rsmith

Differential Revision: https://reviews.llvm.org/D126061
2022-06-15 11:58:26 +02:00
Aaron Ballman
2cb2cd242c Change the behavior of implicit int diagnostics
C89 allowed a type specifier to be elided with the resulting type being
int, aka implicit int behavior. This feature was subsequently removed
in C99 without a deprecation period, so implementations continued to
support the feature. Now, as with implicit function declarations, is a
good time to reevaluate the need for this support.

This patch allows -Wimplicit-int to issue warnings in C89 mode (off by
default), defaults the warning to an error in C99 through C17, and
disables support for the feature entirely in C2x. It also removes a
warning about missing declaration specifiers that really was just an
implicit int warning in disguise and other minor related cleanups.
2022-05-04 08:35:47 -04:00