Commit Graph

95129 Commits

Author SHA1 Message Date
Ilya Biryukov 342e64979a [Sema] Fix assertion failure when instantiating requires expression
Fixes #54629.
The crash is is caused by the double template instantiation.
See the added test. Here is what happens:
- Template arguments for the partial specialization get instantiated.
- This causes instantitation into the corrensponding requires
  expression.
- `TemplateInsantiator` correctly handles instantiation of parameters
  inside `RequiresExprBody` and instantiates the constraint expression
  inside the `NestedRequirement`.
- To build the substituted `NestedRequirement`, `TemplateInsantiator`
  calls `Sema::BuildNestedRequirement` calls
  `CheckConstraintSatisfaction`, which results in another template
  instantiation (with empty template arguments). This seem to be an
  implementation detail to handle constraint satisfaction and is not
  required by the standard.
- The recursive template instantiation tries to find the parameter
  inside `RequiresExprBody` and fails with the corresponding assertion.

Note that this only happens as both instantiations happen with the class
partial template specialization set as `Sema.CurContext`, which is
considered a dependent `DeclContext`.

To fix the assertion, avoid doing the recursive template instantiation
and instead evaluate resulting expressions in-place.

Reviewed By: erichkeane

Differential Revision: https://reviews.llvm.org/D127487
2022-06-23 16:20:30 +02:00
Jeroen Dobbelaere 8999b745bc Revert "[tbaa] Handle base classes in struct tbaa"
This reverts commit cdc59e2202.

The Verifier finds a problem in a stage2 build. Reverting so Bruno can investigate.
2022-06-23 14:18:49 +02:00
Paulo Matos 0fdfeb0847 [WebAssembly] Update test to run it in opaque pointers mode
When opaque pointers was enabled, -no-opaque-pointers were added to some tests in order not to change behaviour. We now revert this and fix the test.

Reviewed By: asb, tlively

Differential Revision: https://reviews.llvm.org/D128282
2022-06-23 14:16:33 +02:00
Tobias Hieta b6a33cec38 [NFC] remove trailing whitespace 2022-06-23 14:04:23 +02:00
Bruno De Fraine cdc59e2202 [tbaa] Handle base classes in struct tbaa
This is a fix for the miscompilation reported in https://github.com/llvm/llvm-project/issues/55384

Not adding a new test case since existing test cases already cover base classes (including new-struct-path tbaa).

Reviewed By: jeroen.dobbelaere

Differential Revision: https://reviews.llvm.org/D126956
2022-06-23 13:39:49 +02:00
Nikita Popov 6f258c0fd3 [Clang] Don't test register allocation
This test was broken by 719658d078.

How did an assembly test get into clang/test?
2022-06-23 12:46:00 +02:00
isuckatcs 8ef628088b [analyzer] Structured binding to arrays
Introducing structured binding to data members and more.
To handle binding to arrays, ArrayInitLoopExpr is also
evaluated, which enables the analyzer to store information
in two more cases. These are:
  - when a lambda-expression captures an array by value
  - in the implicit copy/move constructor for a class
    with an array member

Differential Revision: https://reviews.llvm.org/D126613
2022-06-23 11:38:21 +02:00
Balázs Kéri 7dc81c6244 [clang][analyzer] Fix StdLibraryFunctionsChecker 'mkdir' return value.
The functions 'mkdir', 'mknod', 'mkdirat', 'mknodat' return 0 on success
and -1 on failure. The checker modeled these functions with a >= 0
return value on success which is changed to 0 only. This fix makes
ErrnoChecker work better for these functions.

Reviewed By: steakhal

Differential Revision: https://reviews.llvm.org/D127277
2022-06-23 11:27:26 +02:00
Fazlay Rabbi a35141d395 [OpenMP] Add handling cases when filter(tid) appears with default(none)
Differential Revision: https://reviews.llvm.org/D128397
2022-06-22 17:45:43 -07:00
Guillaume Gomez d0a4450ecd Rename GCCBuiltin into ClangBuiltin
This patch is needed because developers expect "GCCBuiltin" items to be the GCC intrinsics equivalent and not the Clang internals.

Reviewed By: #libc_abi, RKSimon, xbolva00

Differential Revision: https://reviews.llvm.org/D127460
2022-06-22 19:49:20 +01:00
Joseph Huber 7597988729 [LinkerWrapper][NFC] Change interface to use a StringRef to TempFiles
Summary:
Currently we use temporary files to write the intermediate results to.
However, these are stored as regular strings and we do a few unnecessary
copies and conversions of them. This patch simply replaces these strings
with a reference to the filename stored in the list of temporary files.
The temporary files will stay alive during the whole linking phase and
have stable pointers, so we should be able to cheaply pass references to
them rather than copying them every time.
2022-06-22 13:16:37 -04:00
Peixin Qiao 430841605d [flang][Driver] Refine _when_ driver diagnostics are formatted
This patch refines //when// driver diagnostics are formatted so that
`flang-new` and `flang-new -fc1` behave consistently with `clang` and
`clang -cc1`, respectively. This change only applies to driver diagnostics.
Scanning, parsing and semantic diagnostics are separate and not covered here.

**NEW BEHAVIOUR**
To illustrate the new behaviour, consider the following input file:
```! file.f90
program m
  integer :: i = k
end
```
In the following invocations, "error: Semantic errors in file.f90" _will be_
formatted:
```
$ flang-new file.f90
error: Semantic errors in file.f90
./file.f90:2:18: error: Must be a constant value
    integer :: i = k
$ flang-new -fc1 -fcolor-diagnostics file.f90
error: Semantic errors in file.f90
./file.f90:2:18: error: Must be a constant value
    integer :: i = k
```

However, in the following invocations, "error: Semantic errors in file.f90"
_will not be_ formatted:
```
$ flang-new -fno-color-diagnostics file.f90
error: Semantic errors in file.f90
./file.f90:2:18: error: Must be a constant value
    integer :: i = k
$ flang-new -fc1 file.f90
error: Semantic errors in file.f90
./file.f90:2:18: error: Must be a constant value
    integer :: i = k
```

Before this change, none of the above would be formatted. Note also that the
default behaviour in `flang-new` is different to `flang-new -fc1` (this is
consistent with Clang).

**NOTES ON IMPLEMENTATION**
Note that the diagnostic options are parsed in `createAndPopulateDiagOpt`s in
driver.cpp. That's where the driver's `DiagnosticEngine` options are set. Like
most command-line compiler driver options, these flags are "claimed" in
Flang.cpp (i.e.  when creating a frontend driver invocation) by calling
`getLastArg` rather than in driver.cpp.

In Clang's Options.td, `defm color_diagnostics` is replaced with two separate
definitions: `def fcolor_diagnostics` and def fno_color_diagnostics`. That's
because originally `color_diagnostics` derived from `OptInCC1FFlag`, which is a
multiclass for opt-in options in CC1. In order to preserve the current
behaviour in `clang -cc1` (i.e. to keep `-fno-color-diagnostics` unavailable in
`clang -cc1`) and to implement similar behaviour in `flang-new -fc1`, we can't
re-use `OptInCC1FFlag`.

Formatting is only available in consoles that support it and will normally mean that
the message is printed in bold + color.

Co-authored-by: Andrzej Warzynski <andrzej.warzynski@arm.com>

Reviewed By: rovka

Differential Revision: https://reviews.llvm.org/D126164
2022-06-22 23:56:34 +08:00
James Y Knight 17e2702528 Clang AttributeReference: emit entries for "Undocumented" attributes.
Almost all attributes currently marked `Undocumented` are user-facing
attributes which _ought_ to be documented, but nobody has written it
yet. This change ensures that we at least acknowledge that these
attributes exist in the documentation, even if we have no description
of their semantics.

A new category, `InternalOnly` has been added for those few attributes
which are not user-facing, and should remain omitted from the docs.
2022-06-22 09:55:05 -04:00
Joseph Huber a9fd8b9113 [LinkerWrapper] Fix calls to deleted Error constructor on older compilers
Summary:
A recent patch added some new code paths to the linker wrapper. Older
compilers seem to have problems with returning errors wrapped in
an Excepted type without explicitly moving them. This caused failures in
some of the buildbots. This patch fixes that.
2022-06-22 09:39:23 -04:00
Joseph Huber 21e29b6ce7 [Clang] Allow multiple comma separated arguments to `--offload-arch=`
This patch updates the `--[no-]offload-arch` command line arguments to
allow the user to pass in many architectures in a single argument rather
than specifying it multiple times. This means that the following command
line,
```
clang foo.cu --offload-arch=sm_70 --offload-arch=sm_80
```
can become:
```
clang foo.cu --offload-arch=sm_70,sm_80
```

Reviewed By: ye-luo

Differential Revision: https://reviews.llvm.org/D128206
2022-06-22 09:25:04 -04:00
Joseph Huber 958a885050 [LinkerWrapper] Rework the linker wrapper and use owning binaries
The linker wrapper currently eagerly extracts all identified offloading
binaries to a file. This isn't ideal because we will soon open these
files again to examine their symbols for LTO and other things.
Additionally, we may not use every extracted file in the case of static
libraries. This would be very noisy in the case of static libraries that
may contain code for several targets not participating in the current
link.

Recent changes allow us to treat an Offloading binary as a standard
binary class. So that allows us to use an OwningBinary to model the
file. Now we keep it in memory and only write it once we know which
files will be participating in the final link job. This also reworks a
lot of the structure around how we handle this by removing the old
DeviceFile class.

The main benefit from this is that the following doesn't output 32+ files and
instead will only output a single temp file for the linked module.
```
$ clang input.c -fopenmp --offload-arch=sm_70 -foffload-lto -save-temps
```

Reviewed By: JonChesterfield

Differential Revision: https://reviews.llvm.org/D127246
2022-06-22 09:24:10 -04:00
Serge Pavlov 706e89db97 Fix interaction of pragma FENV_ACCESS with other pragmas
Previously `#pragma STDC FENV_ACCESS ON` always set dynamic rounding
mode and strict exception handling. It is not correct in the presence
of other pragmas that also modify rounding mode and exception handling.
For example, the effect of previous pragma FENV_ROUND could be
cancelled, which is not conformant with the C standard. Also
`#pragma STDC FENV_ACCESS OFF` turned off only FEnvAccess flag, leaving
rounding mode and exception handling unchanged, which is incorrect in
general case.

Concrete rounding and exception mode depend on a combination of several
factors like various pragmas and command-line options. During the review
of this patch an idea was proposed that the semantic actions associated
with such pragmas should only set appropriate flags. Actual rounding
mode and exception handling should be calculated taking into account the
state of all relevant options. In such implementation the pragma
FENV_ACCESS should not override properties set by other pragmas but
should set them if such setting is absent.

To implement this approach the following main changes are made:

- Field `FPRoundingMode` is removed from `LangOptions`. Actually there
  are no options that set it to arbitrary rounding mode, the choice was
  only `dynamic` or `tonearest`. Instead, a new boolean flag
  `RoundingMath` is added, with the same meaning as the corresponding
  command-line option.

- Type `FPExceptionModeKind` now has possible value `FPE_Default`. It
  does not represent any particular exception mode but indicates that
  such mode was not set and default value should be used. It allows to
  distinguish the case:

    {
        #pragma STDC FENV_ACCESS ON
	...
    }

  where the pragma must set FPE_Strict, from the case:

    {
        #pragma clang fp exceptions(ignore)
        #pragma STDC FENV_ACCESS ON
        ...
    }

  where exception mode should remain `FPE_Ignore`.

  - Class `FPOptions` has now methods `getRoundingMode` and
  `getExceptionMode`, which calculates the respective properties from
  other specified FP properties.

  - Class `LangOptions` has now methods `getDefaultRoundingMode` and
  `getDefaultExceptionMode`, which calculates default modes from the
  specified options and should be used instead of `getRoundingMode` and
  `getFPExceptionMode` of the same class.

Differential Revision: https://reviews.llvm.org/D126364
2022-06-22 15:13:54 +07:00
Martin Boehme 0d300da799 [Clang] Fix compile time regression caused by D126061.
As noted by @nikic, D126061 causes a compile time regression of about
0.5% on -O0 builds:

http://llvm-compile-time-tracker.com/compare.php?from=7acc88be0312c721bc082ed9934e381d297f4707&to=8c7b64b5ae2a09027c38db969a04fc9ddd0cd6bb&stat=instructions

This happens because, in a number of places, D126061 creates an
additional local variable of type `ParsedAttributes`. In the large
majority of cases, no attributes are added to this `ParsedAttributes`,
but it turns out that creating an empty `ParsedAttributes`, then
destroying it is a relatively expensive operation.

The reason for this is because `AttributePool` uses a `TinyPtrVector` as
its underlying vector class, and the technique that `TinyPtrVector`
employs to achieve its extreme memory frugality makes the `begin()` and
`end()` member functions relatively slow. The `ParsedAttributes`
destructor iterates over the attributes in its `AttributePool`, and this
is a relatively expensive operation because `TinyPtrVector`'s `begin()` and
`end()` are relatively slow.

The fix for this is to replace `TinyPtrVector` in `ParsedAttributes` and
`AttributePool` with `SmallVector`. `ParsedAttributes` and
`AttributePool` objects are only ever allocated on the stack (they're
not part of the AST), and only a small number of these objects are live
at any given time, so they don't need the extreme memory frugality of
`TinyPtrVector`.

I've confirmed with valgrind that this patch does not increase heap
memory usage, and it actually makes compiles slightly faster than they
were before D126061.

Here are instruction count measurements (obtained with callgrind)
running `clang -c MultiSource/Applications/JM/lencod/parsetcommon.c`
(a file from llvm-test-suite that exhibited a particularly large
compile-time regression):

7acc88be03
(baseline one commit before D126061 landed)
102,280,068 instructions

8c7b64b5ae
(the patch that landed D126061)
103,289,454 instructions
(+0.99% relative to baseline)

This patch applied onto
8c7b64b5ae
101,117,584 instructions
(-1.14% relative to baseline)

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D128097
2022-06-21 23:15:43 +02:00
Haojian Wu 7b7166f1a2 Fix an unused-variable warning in release build, NFC. 2022-06-21 20:52:07 +02:00
Chris Bieneman 9f499d9d73 [HLSL] Support HLSL vector initializers
In HLSL vectors are ext_vectors in all respects except that they
support a constructor style syntax for initializing vectors. This
change adds a translation of vector constructor arguments into
initializer lists.

This supports two oddities of HLSL syntax:
(1) HLSL vectors support constructor syntax
(2) HLSL vectors are expanded to constituate components in constructors

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D127802
2022-06-21 12:33:42 -05:00
Matheus Izvekov 271cc58805
[NFC] clang: Implement tests for PR56099
Signed-off-by: Matheus Izvekov <mizvekov@gmail.com>

Differential Revision: https://reviews.llvm.org/D128112
2022-06-21 18:35:17 +02:00
Balázs Kéri 957014da2d [clang][Analyzer] Add errno state to standard functions modeling.
This updates StdLibraryFunctionsChecker to set the state of 'errno'
by using the new errno_modeling functionality.
The errno value is set in the PostCall callback. Setting it in call::Eval
did not work for some reason and then every function should be
EvalCallAsPure which may be bad to do. Now the errno value and state
is not allowed to be checked in any PostCall checker callback because
it is unspecified if the errno was set already or will be set later
by this checker.

Reviewed By: martong, steakhal

Differential Revision: https://reviews.llvm.org/D125400
2022-06-21 08:56:41 +02:00
Kazu Hirata ca4af13e48 [clang] Don't use Optional::getValue (NFC) 2022-06-20 22:59:26 -07:00
Kazu Hirata d66cbc565a Don't use Optional::hasValue (NFC) 2022-06-20 20:26:05 -07:00
Kazu Hirata 0916d96d12 Don't use Optional::hasValue (NFC) 2022-06-20 20:17:57 -07:00
Kazu Hirata 064a08cd95 Don't use Optional::hasValue (NFC) 2022-06-20 20:05:16 -07:00
Brad Smith 7c5957aedb [Driver] Pass -X to ld for riscv64-fuchsia
D127826, add support for Fuchsia which uses lld on riscv64

Reviewed By: MaskRay, phosek

Differential Revision: https://reviews.llvm.org/D128134
2022-06-20 21:05:01 -04:00
Kazushi (Jam) Marukawa 5ba0a9571b [Clang][VE] Add missing intrinsics
Add missing intrinsics and tests for them.  An expanding  macro
from _vel_pack_f32p to __builtin_ve_vl_pack_f32p and others is
already defined in clang/lib/Headers/velintrin.h.

Reviewed By: efocht

Differential Revision: https://reviews.llvm.org/D128120
2022-06-21 07:30:36 +09:00
Kazu Hirata ad7ce1e769 Don't use Optional::hasValue (NFC) 2022-06-20 11:49:10 -07:00
Kazu Hirata 5413bf1bac Don't use Optional::hasValue (NFC) 2022-06-20 11:33:56 -07:00
Kazu Hirata 452db157c9 [clang] Don't use Optional::hasValue (NFC) 2022-06-20 10:51:34 -07:00
Stanislav Gatev e363c5963d [clang][dataflow] Extend flow condition in the body of a do/while loop
Extend flow condition in the body of a do/while loop.

Differential Revision: https://reviews.llvm.org/D128183

Reviewed-by: gribozavr2, xazax.hun
2022-06-20 17:31:00 +00:00
Sven van Haastregt 8c3fa31701 [OpenCL][TableGen] Fix type extension guard emission
For certain cases (such as for the double subtype of AGenType), the
OpenCLBuiltinFileEmitterBase would not emit the extension #if-guard.
Fix that by looking at the extension of the actual type instead of the
argument type (which could be a GenType that does not carry any
extension information).
2022-06-20 10:07:34 +01:00
Jan Svoboda b02d970b43 [clang][sema] Generate builtin operator overloads for (volatile) _Atomic types
We observed a failed assert in overloaded compound-assignment operator resolution:

```
Assertion failed: (Result.isInvalid() && "C++ binary operator overloading is missing candidates!"), function CreateOverloadedBinOp, file SemaOverload.cpp, line 13944.
...
frame #4: clang` clang::Sema::CreateOverloadedBinOp(..., Opc=BO_OrAssign, ..., PerformADL=true, AllowRewrittenCandidates=false, ...) at SemaOverload.cpp:13943
frame #5: clang` BuildOverloadedBinOp(..., Opc=BO_OrAssign, ...) at SemaExpr.cpp:15228
frame #6: clang` clang::Sema::BuildBinOp(..., Opc=BO_OrAssign, ...) at SemaExpr.cpp:15330
frame #7: clang` clang::Sema::ActOnBinOp(..., Kind=pipeequal, ...) at SemaExpr.cpp:15187
frame #8: clang` clang::Parser::ParseRHSOfBinaryExpression(..., MinPrec=Assignment) at ParseExpr.cpp:629
frame #9: clang` clang::Parser::ParseAssignmentExpression(..., isTypeCast=NotTypeCast) at ParseExpr.cpp:176
frame #10: clang` clang::Parser::ParseExpression(... isTypeCast=NotTypeCast) at ParseExpr.cpp:124
frame #11: clang` clang::Parser::ParseExprStatement(...) at ParseStmt.cpp:464
```

A simple reproducer is:

```
_Atomic unsigned an_atomic_uint;

enum { an_enum_value = 1 };

void enum1() { an_atomic_uint += an_enum_value; }
```

This patch fixes the issue by generating builtin operator overloads for (volatile) _Atomic types.

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D125349
2022-06-20 11:03:29 +02:00
Balázs Kéri 60f3b07118 [clang][analyzer] Add checker for bad use of 'errno'.
Extend checker 'ErrnoModeling' with a state of 'errno' to indicate
the importance of the 'errno' value and how it should be used.
Add a new checker 'ErrnoChecker' that observes use of 'errno' and
finds possible wrong uses, based on the "errno state".
The "errno state" should be set (together with value of 'errno')
by other checkers (that perform modeling of the given function)
in the future. Currently only a test function can set this value.
The new checker has no user-observable effect yet.

Reviewed By: martong, steakhal

Differential Revision: https://reviews.llvm.org/D122150
2022-06-20 10:07:31 +02:00
Marco Antognini 0ad4f29b54 [analyzer] SATest: Weaken assumption about HTML files
Instead of assuming there is an HTML file for each diagnostics, consider
the HTML files only when they exist, individually of each other.

After generating the reference data, running

  python /scripts/SATest.py build --projects simbody

was resulting in this error:

    File "/scripts/CmpRuns.py", line 250, in read_single_file
      assert len(d['HTMLDiagnostics_files']) == 1
  KeyError: 'HTMLDiagnostics_files'

Reviewed By: steakhal

Differential Revision: https://reviews.llvm.org/D126197
2022-06-20 09:46:07 +02:00
Marco Antognini e15fef4170 [analyzer] SATest: Ensure Docker image can be built
Solve build issues occurring when running `docker build`.

Fix the version of cmake-data to solve the following issue:

  The following packages have unmet dependencies:
   cmake : Depends: cmake-data (= 3.20.5-0kitware1) but 3.23.1-0kitware1ubuntu18.04.1 is to be installed

Install libjpeg to solve this issue when installing Python
requirements:

  The headers or library files could not be found for jpeg,
  a required dependency when compiling Pillow from source.

Reviewed By: steakhal

Differential Revision: https://reviews.llvm.org/D126196
2022-06-20 09:43:21 +02:00
Diana Picus 26041e1700 Update link job for flang on windows
When linking a Fortran program, we need to add the runtime libraries to
the command line. This is exactly what we do for Linux/Darwin, but the
MSVC interface is slightly different (e.g. -libpath instead of -L).

We also remove oldnames and libcmt, since they're not needed at the
moment and they bring in more dependencies.

We also pass `/subsystem:console` to the linker so it can figure out the
right entry point. This is only needed for MSVC's `link.exe`. For LLD it
is redundant but doesn't hurt.

Differential Revision: https://reviews.llvm.org/D126291

Co-authored-by: Markus Mützel <markus.muetzel@gmx.de>
2022-06-20 07:25:10 +00:00
Stanislav Gatev 83232099cb [clang][dataflow] Extend flow condition in the body of a for loop
Extend flow condition in the body of a for loop.

Differential Revision: https://reviews.llvm.org/D128060
2022-06-20 05:48:45 +00:00
Kazu Hirata 05ff3790b3 [Basic] Use has_value (NFC) 2022-06-19 18:59:56 -07:00
Kazu Hirata c7987d4948 [ADT] Use value instead of getValue() (NFC)
Since Optional<clang::FileEntryRef> uses a custom storage class, this
patch adds value to MapEntryOptionalStorage.
2022-06-19 18:34:33 -07:00
Kazu Hirata 813f487228 [ADT] Use has_value (NFC)
This patch switches to has_value within Optional.

Since Optional<clang::FileEntryRef> uses custom storage class, this
patch adds has_entry to MapEntryOptionalStorage.
2022-06-19 18:10:13 -07:00
Kazu Hirata 97c87c6f7c [AST] Fix an unused variable warning
This paptch fixes:

  warning: unused variable ‘DD’ [-Wunused-variable]
2022-06-19 00:20:58 -07:00
Kazu Hirata 06decd0b41 [clang] Use value_or instead of getValueOr (NFC) 2022-06-18 23:21:34 -07:00
Fangrui Song 57e43ebc42 [Driver][Gnu] Don't passs --dynamic-linker in -r mode
No behavior change as GNU ld/gold/ld.lld ignore --dynamic-linker in -r mode.
This change makes the intention clearer as we already suppress --dynamic-linker
for -shared, -static, and -static-pie.
2022-06-18 23:13:19 -07:00
Kazu Hirata c5935af058 [Toolchains] Use llvm::is_contained (NFC) 2022-06-18 15:57:50 -07:00
Brad Smith 6dd094dd43 [Driver][OpenBSD] Use Arch reference instead of getArch(). NFC 2022-06-18 18:11:15 -04:00
Brad Smith 119a13199a [Driver] Pass -X to ld for riscv64-openbsd
Noticing D127826, add support for OpenBSD which uses lld on riscv64.

Reviewed By: MaskRay

Differential Revision: https://reviews.llvm.org/D128109
2022-06-18 17:58:58 -04:00
Roy Jacobson 21eb1af469 [Concepts] Implement overload resolution for destructors (P0848)
This patch implements a necessary part of P0848, the overload resolution for destructors.
It is now possible to overload destructors based on constraints, and the eligible destructor
will be selected at the end of the class.

The approach this patch takes is to perform the overload resolution in Sema::ActOnFields
and to mark the selected destructor using a new property in FunctionDeclBitfields.

CXXRecordDecl::getDestructor is then modified to use this property to return the correct
destructor.

This closes https://github.com/llvm/llvm-project/issues/45614.

Reviewed By: #clang-language-wg, erichkeane

Differential Revision: https://reviews.llvm.org/D126194
2022-06-19 00:30:37 +03:00
Fangrui Song af6d2a0b68 [docs] Re-generate ClangCommandLineReference.rst 2022-06-18 11:01:54 -07:00
Kazu Hirata 80c12bdb3b [clang] Call *set::insert without checking membership first (NFC) 2022-06-18 10:41:26 -07:00
Yuki Okushi 7eb046624f
Prefer `getCurrentFileOrBufferName` in `FrontendAction::EndSourceFile`
`getCurrentFile` here causes an assertion on some condition.
`getCurrentFileOrBufferName` is preferrable instead.

llvm#55950

Differential Revision: https://reviews.llvm.org/D127509
2022-06-18 23:48:30 +09:00
Jun Zhang cd64a427ef
Reland "[CodeGen] Keep track info of lazy-emitted symbols in ModuleBuilder"
This reverts commits:
d3ddc251ac
d90eecff5c

It turned out there're some options turned on that leaks the memory
intentionally, which fires the asan builds after the patch being
applied. The issue has been fixed in
7bc00ce5cd, so reland it.

Below is the original commit message:

The intent of this patch is to selectively carry some states over to
the Builder so we won't lose the information of the previous symbols.

This used to be several downstream patches of Cling, it aims to fix
errors in Clang Interpreter when trying to use inline functions.
Before this patch:

clang-repl> inline int foo() { return 42;}
clang-repl> int x = foo();

JIT session error: Symbols not found: [ _Z3foov ]
error: Failed to materialize symbols:
{ (main, { x, $.incr_module_1.__inits.0, __orc_init_func.incr_module_1 }) }

Co-authored-by: Axel Naumann <Axel.Naumann@cern.ch>
Signed-off-by: Jun Zhang <jun@junz.org>
2022-06-18 20:27:21 +08:00
Pavel Iliin 6e070c3c91 [NFC] Specifing clang namespace for builtins. 2022-06-18 10:44:25 +01:00
Akira Hatanaka 8fc3d719ee Stop wrapping GCCAsmStmts inside StmtExprs to destruct temporaries
Instead, just pop the cleanups at the end of the asm statement.

This fixes an assertion failure in BuildStmtExpr. It also fixes a bug
where blocks and C compound literals were destructed at the end of the
asm statement instead of at the end of the enclosing scope.

Differential Revision: https://reviews.llvm.org/D125936
2022-06-17 17:28:00 -07:00
Jan Svoboda 92c6ffa14c [clang][driver] Ensure we don't accumulate entries in -MJ files
Previously, each job would overwrite the -MJ file. This didn't quite work for Clang invocations with multiple architectures, which got fixed in D121997 by always appending to the -MJ file. That's not correct either, since the file would grow indefinitely on subsequent Clang invocations. This patch ensures the driver always removes the file before jobs fill it in by appending.

Reviewed By: MaskRay

Differential Revision: https://reviews.llvm.org/D128098
2022-06-18 00:00:43 +02:00
Sunho Kim 7bc00ce5cd [clang-repl] Remove memory leak of ASTContext/TargetMachine.
Removes memory leak of ASTContext and TargetMachine. When DisableFree is turned on, it intentionally leaks these instances as they can be trivially deallocated. This patch turns this off and delete Parser instance early so that they will not reference dangling pargma headers.

Asan shouldn't detect these as leaks normally, since burypointer is called for them. But, every invocation of incremental parser createa an additional leak of TargetMachine. If there are many invocations within a single test case, we easily reach number of leaks exceeding kGraveYardMaxSize (which is 12) and leaks start to get reported by asan buildbots.

Reviewed By: v.g.vassilev

Differential Revision: https://reviews.llvm.org/D127991
2022-06-18 06:36:25 +09:00
Chris Bieneman f9e49644f4 Revert "wip"
This reverts commit 0dd243fa8a.

I accidentally pushed this! Oops!
2022-06-17 13:36:53 -05:00
Chris Bieneman 0dd243fa8a wip 2022-06-17 13:34:21 -05:00
isuckatcs e77ac66b8c [Static Analyzer] Structured binding to data members
Introducing structured binding to data members.

Differential Revision: https://reviews.llvm.org/D127643
2022-06-17 19:50:10 +02:00
Stanislav Gatev ba53906cef [clang][dataflow] Add support for comma binary operator
Add support for comma binary operator.

Differential Revision: https://reviews.llvm.org/D128013

Reviewed-by: ymandel, xazax.hun
2022-06-17 17:48:21 +00:00
isuckatcs 92bf652d40 [Static Analyzer] Small array binding policy
If a lazyCompoundVal to a struct is bound to the store, there is a policy which decides
whether a copy gets created instead.

This patch introduces a similar policy for arrays, which is required to model structured
binding to arrays without false negatives.

Differential Revision: https://reviews.llvm.org/D128064
2022-06-17 18:56:13 +02:00
isuckatcs fc6b2281bf [Static Analyzer][CFG] Introducing the source array in the CFG of DecompositionDecl
For DecompositionDecl, the array, which is being decomposed was not present in the
CFG, which lead to the liveness analysis falsely detecting it as a dead symbol.

Differential Revision: https://reviews.llvm.org/D127993
2022-06-17 18:34:34 +02:00
Ben Langmuir 4a3a9a5fa0 [clang][deps] Sort submodules when calculating dependencies
Dependency scanning does not care about the order of submodules for
correctness, so sort the submodules so that we get the same
command-lines to build the module across different TUs. The order of
inferred submodules can vary depending on the order of #includes in the
including TU.

Differential Revision: https://reviews.llvm.org/D128008
2022-06-17 07:55:27 -07:00
Kadir Cetinkaya 1a02c963e3
Revert "Revert "[clang] Dont print implicit forrange initializer""
This reverts commit 7aac15d5df.

Only updates the tests, as these statements are still part of the CFG
and its just the pretty printer policy that changes. Hopefully this
shouldn't affect any analysis.
2022-06-17 16:51:16 +02:00
Nico Weber 7aac15d5df Revert "[clang] Dont print implicit forrange initializer"
This reverts commit 32805e60c9.
Broke check-clang, see comments on https://reviews.llvm.org/D127863
2022-06-17 08:59:17 -04:00
Jolanta Jensen c80c57674e [Clang] Allow 'Complex float __attribute__((mode(HC)))'
Adding half float to types that can be represented by __attribute__((mode(xx))).
Original implementation authored by George Steed.

Differential Revision: https://reviews.llvm.org/D126479
2022-06-17 12:39:52 +01:00
Kadir Cetinkaya 32805e60c9
[clang] Dont print implicit forrange initializer
Fixes https://github.com/clangd/clangd/issues/1158

Differential Revision: https://reviews.llvm.org/D127863
2022-06-17 11:29:44 +02:00
Alexander Potapenko 7ab44b5c21 [msan] Allow KMSAN to use -fsanitize-memory-param-retval
Let -fsanitize-memory-param-retval be used together with
-fsanitize=kernel-memory, so that it can be applied when building the
Linux kernel.

Also add clang/test/CodeGen/kmsan-param-retval.c to ensure that
-fsanitize-memory-param-retval eliminates shadow accesses for parameters
marked as undef.

Reviewed By: eugenis, vitalybuka

Differential Revision: https://reviews.llvm.org/D127860
2022-06-17 10:54:20 +02:00
Sven van Haastregt 2d9c891cd9 [OpenCL] Fix atomic_fetch_add/sub half overloads
Some of the atomic_fetch_add and atomic_fetch_sub overloads intended
for atomic_half types accidentally had an atomic_float parameter.
2022-06-17 09:53:45 +01:00
Javier Alvarez 5ea341d7c4 [clang] Fix trivially copyable for copy constructor and copy assignment operator
From [class.copy.ctor]:

```
A non-template constructor for class X is a copy constructor if its first
parameter is of type X&, const X&, volatile X& or const volatile X&, and
either there are no other parameters or else all other parameters have
default arguments (9.3.4.7).

A copy/move constructor for class X is trivial if it is not user-provided and if:
- class X has no virtual functions (11.7.3) and no virtual base classes (11.7.2), and
- the constructor selected to copy/move each direct base class subobject is trivial, and
- or each non-static data member of X that is of class type (or array thereof),
  the constructor selected to copy/move that member is trivial;

otherwise the copy/move constructor is non-trivial.
```

So `T(T&) = default`; should be trivial assuming that the previous
provisions are met.

This works in GCC, but not in Clang at the moment:
https://godbolt.org/z/fTGe71b6P

Reviewed By: royjacobson

Differential Revision: https://reviews.llvm.org/D127593
2022-06-17 10:35:01 +03:00
Fangrui Song c324c938be [Driver] Pass -X to ld for riscv*-{elf,freebsd,linux}
GNU ld has a hack that defaults to -X (--discard-locals) in the emulation file
`riscvelf.em`. The recommended way, as gcc/config/arm does, is to let the
compiler driver pass -X to ld.
(The motivation is likely to discard a plethora of `.L` symbols due to linker
relaxation.)

lld default to --discard-none. To make clang+lld match GNU ld's behavior, pass
-X to ld.

Note: GNU ld has a special rule to treat ld -r -s as ld -r -S -x. With -X, driver `-r -Wl,-s`
will behave as ld `-r -S -X`. This removes fewer symbols than `-r -S -x` but is safe.

Differential Revision: https://reviews.llvm.org/D127826
2022-06-16 23:33:48 -07:00
Maryam Moghadas 711a71d1ab PowerPC] Emit warning for incompatible vector types that are currently diagnosed with -fno-lax-vector-conversions
This patch is the last prerequisite to switch the default behaviour to -fno-lax-vector-conversions in the future.
The first path ;D124093; fixed the altivec implicit castings.

Reviewed By: amyk

Differential Revision: https://reviews.llvm.org/D126540
2022-06-16 20:28:34 -05:00
Lei Huang febe4f650b [PowerPC][NFC] Undefine __XL_COMPAT_ALTIVEC__ in builtin lit test
Add defines and undefines of the __XL_COMPAT_ALTIVEC__ to ensure
consistent results regardless of the default for this macro.
2022-06-16 20:16:52 -05:00
Jennifer Yu bb83f8e70b [OpenMP] Initial parsing and sema for 'parallel masked' construct
Differential Revision: https://reviews.llvm.org/D127454
2022-06-16 18:01:15 -07:00
Fangrui Song 0e182469ee [sanitizer] Delete empty sanitizer_openbsd.cpp after D89759 2022-06-16 16:38:01 -07:00
Lei Huang dba2ff500d fix x86 sanitizer failure due to use of or 2022-06-16 17:20:31 -05:00
Mitch Phillips ee28837a1f [NFCI] Whitespace in SemaDeclAttr.cpp 2022-06-16 15:10:32 -07:00
Maryam Moghadas a9ddb7d54e [PowerPC] Fixing implicit castings in altivec for -fno-lax-vector-conversions
XL considers different vector types to be incompatible with each other.
For example assignment between variables of types vector float and vector
long long or even vector signed int and vector unsigned int are diagnosed.
clang, however does not diagnose such cases and does a simple bitcast between
the two types. This could easily result in program errors. This patch is to
fix the implicit casts in altivec.h so that there is no incompatible vector
type errors whit -fno-lax-vector-conversions, this is the prerequisite patch
to switch the default to -fno-lax-vector-conversions later.

Reviewed By: nemanjai, amyk

Differential Revision: https://reviews.llvm.org/D124093
2022-06-16 17:07:03 -05:00
Mitch Phillips 011e0604eb Add DWARF string debug to clang release notes.
D12353 added inline strings to the DWARF info produced by clang. This
turns out to break some debugging software that assumes that a
DW_TAG_variable *must* come with a DW_AT_name. Add a release note to
broadcast this change.

Reviewed By: paulkirth

Differential Revision: https://reviews.llvm.org/D126224
2022-06-16 14:54:12 -07:00
Joe Nash 2d43de13df [AMDGPU] gfx11 new dot instruction codegen support
Reviewed By: rampitec, #amdgpu

Differential Revision: https://reviews.llvm.org/D127904
2022-06-16 14:19:34 -04:00
Arthur Eubanks a70b39abff [clang] Don't emit type test/assume for virtual classes that should never participate in WPD
Reviewed By: pcc

Differential Revision: https://reviews.llvm.org/D127876
2022-06-16 09:38:14 -07:00
Alex Brachet f4f6adc451 [clang] Don't emit IFUNC when targeting Fuchsia
Fuchsia's dynamic linker does not and will never support IFUNC's.

Differential revision: https://reviews.llvm.org/D127933
2022-06-16 15:38:12 +00:00
Matheus Izvekov e35096ae96
cmake: configure clang lit to use hmaptool from source directly
Signed-off-by: Matheus Izvekov <mizvekov@gmail.com>

Reviewed By: dyung

Differential Revision: https://reviews.llvm.org/D127943
2022-06-16 13:08:50 +02:00
Michael Spencer 1694175315 [Clang][Modules] Merge availability attributes on imported decls
Currently we do not in general merge attributes when importing decls from modules. This patch handles availability, but long term we need to properly handle all attributes.

I tried to use Sema::mergeDeclAttributes, but it caused test crashes as I don't think it expects to be called in this context. We really shouldn't have duplicate code for merging attributes long term, but for now this fixes availability. There's already a TODO for this in the declaration of ASTDeclReader::mergeInheritableAttributes.

Differential Revision: https://reviews.llvm.org/D127182

rdar://85820301
2022-06-15 17:46:16 -07:00
Nico Weber 307109266f unbreak Modules/cxx20-export-import.cpp with LLVM_APPEND_VC_REV=OFF after 45d88cd008
See revision b8b7a9dcdc for prior art.
2022-06-15 17:42:35 -04:00
Sam Clegg 78747bd39a [clang][WebAssembly] Loosen restriction on `main` symbol mangling
Remove the `hasPrototype()` restriction so that old style K&R
declarations of main work too.

For example the following has 2 params but no prototype.

```
int main(argc, argv)
    int argc;
    char *argv[];
{
  return 0;
}
```

Also, use `getNumParams()` over `param_size()` which seems to be a more
direct way to get at the same information.

Also, add missing tests for this mangling.

Differential Revision: https://reviews.llvm.org/D127888
2022-06-15 13:56:05 -07:00
Fangrui Song c418d0f1be [Driver] Simplify -fno-builtin- handling. NFC 2022-06-15 13:35:08 -07:00
Ben Langmuir 509223da61 [clang][deps] Further canonicalize implicit modules options in dep scan
Disable or canonicalize compiler options that are not relevant in
explicit module builds, similar to what we already did for the modules
cache path. This reduces uninteresting differences between
command-lines, which is particularly useful if there is a tool that can
cache the compilations.

Differential Revision: https://reviews.llvm.org/D127883
2022-06-15 13:29:47 -07:00
owenca 2d82c9ccf3 [clang-format][NFC] Fix braces in ClangFormat.cpp
Differential Revision: https://reviews.llvm.org/D127827
2022-06-15 12:57:48 -07:00
Aaron Ballman 10822857b7 Rolling back tests for WG14 DR145
Several build bots are failing with surprising behavior, so it's less
clear whether we do or don't implement this DR properly.

https://lab.llvm.org/buildbot/#/builders/91/builds/10454
https://lab.llvm.org/buildbot/#/builders/109/builds/40668
https://lab.llvm.org/buildbot/#/builders/139/builds/23334
2022-06-15 15:37:14 -04:00
Aaron Ballman 61a649ca35 Update the status of more C DRs
This adds information for DRs 126 through 146.
2022-06-15 15:25:47 -04:00
Petr Hosek 55ba0830e4 [Clang] Let the linker choose shared or static libunwind unless specified
We shouldn't assume that libunwind.so is available. Rather can defer
the decision to the linker which defaults to libunwind.so, but if .so
isn't available, it'd pick libunwind.a. Users can use -static-libgcc
and -shared-libgcc to override this behavior and explicitly choose
the version they want.

Differential Revision: https://reviews.llvm.org/D127528
2022-06-15 18:22:13 +00:00
Mitch Phillips 45d88cd008 [clang] Add -fsanitize=memtag-globals (no-op).
Adds the -fsanitize plumbing for memtag-globals. Makes -fsanitize=memtag
imply -fsanitize=memtag-globals.

This has no effect on codegen for now.

Reviewed By: eugenis, aaron.ballman

Differential Revision: https://reviews.llvm.org/D127163
2022-06-15 10:07:53 -07:00
Stanislav Gatev 0c2edf27a2 [clang][dataflow] Make `Value` and `StorageLocation` non-copyable
This makes it harder to misuse APIs that return references by
accidentally copying the results which could happen when assigning the
them to variables declared as `auto`.

Differential Revision: https://reviews.llvm.org/D127865

Reviewed-by: ymandel, xazax.hun
2022-06-15 16:14:27 +00:00
Balazs Benics 929e60b6bd [analyzer] Relax constraints on const qualified regions
The arithmetic restriction seems to be artificial.
The comment below seems to be stale.
Thus, we remove both.

Depends on D127306.

Reviewed By: martong

Differential Revision: https://reviews.llvm.org/D127763
2022-06-15 17:08:27 +02:00
Balazs Benics f4fc3f6ba3 [analyzer] Treat system globals as mutable if they are not const
Previously, system globals were treated as immutable regions, unless it
was the `errno` which is known to be frequently modified.

D124244 wants to add a check for stores to immutable regions.
It would basically turn all stores to system globals into an error even
though we have no reason to believe that those mutable sys globals
should be treated as if they were immutable. And this leads to
false-positives if we apply D124244.

In this patch, I'm proposing to treat mutable sys globals actually
mutable, hence allocate them into the `GlobalSystemSpaceRegion`, UNLESS
they were declared as `const` (and a primitive arithmetic type), in
which case, we should use `GlobalImmutableSpaceRegion`.

In any other cases, I'm using the `GlobalInternalSpaceRegion`, which is
no different than the previous behavior.

---

In the tests I added, only the last `expected-warning` was different, compared to the baseline.
Which is this:
```lang=C++
void test_my_mutable_system_global_constraint() {
  assert(my_mutable_system_global > 2);
  clang_analyzer_eval(my_mutable_system_global > 2); // expected-warning {{TRUE}}
  invalidate_globals();
  clang_analyzer_eval(my_mutable_system_global > 2); // expected-warning {{UNKNOWN}} It was previously TRUE.
}
void test_my_mutable_system_global_assign(int x) {
  my_mutable_system_global = x;
  clang_analyzer_eval(my_mutable_system_global == x); // expected-warning {{TRUE}}
  invalidate_globals();
  clang_analyzer_eval(my_mutable_system_global == x); // expected-warning {{UNKNOWN}} It was previously TRUE.
}
```

---

Unfortunately, the taint checker will be also affected.
The `stdin` global variable is a pointer, which is assumed to be a taint
source, and the rest of the taint propagation rules will propagate from
it.
However, since mutable variables are no longer treated immutable, they
also get invalidated, when an opaque function call happens, such as the
first `scanf(stdin, ...)`. This would effectively remove taint from the
pointer, consequently disable all the rest of the taint propagations
down the line from the `stdin` variable.

All that said, I decided to look through `DerivedSymbol`s as well, to
acquire the memregion in that case as well. This should preserve the
previously existing taint reports.

Reviewed By: martong

Differential Revision: https://reviews.llvm.org/D127306
2022-06-15 17:08:27 +02:00
Balazs Benics 96ccb690a0 [analyzer][NFC] Prefer using isa<> instead getAs<> in conditions
Depends on D125709

Reviewed By: martong

Differential Revision: https://reviews.llvm.org/D127742
2022-06-15 16:58:13 +02:00
Balazs Benics 481f860324 [analyzer][NFC] Remove dead field of UnixAPICheckers
Initially, I thought there is some fundamental bug here by not using the
bool fields, but it turns out D55425 split this checker into two
separate ones; making these fields dead.

Depends on D127836, which uncovered this issue.

Reviewed By: martong

Differential Revision: https://reviews.llvm.org/D127838
2022-06-15 16:50:12 +02:00
Balazs Benics 6c4f9998ae [analyzer] Fix StreamErrorState hash bug
The `Profile` function was incorrectly implemented.
The `StreamErrorState` has an implicit `bool` conversion operator, which
will result in a different hash than faithfully hashing the raw value of
the enum.

I don't have a test for it, since it seems difficult to find one.
Even if we would have one, any change in the hashing algorithm would
have a chance of breaking it, so I don't think it would justify the
effort.

Depends on D127836, which uncovered this issue by marking the related
`Profile` function dead.

Reviewed By: martong, balazske

Differential Revision: https://reviews.llvm.org/D127839
2022-06-15 16:50:12 +02:00
Balazs Benics f1b18a79b7 [analyzer][NFC] Remove dead code and modernize surroundings
Thanks @kazu for helping me clean these parts in D127799.

I'm leaving the dump methods, along with the unused visitor handlers and
the forwarding methods.

The dead parts actually helped to uncover two bugs, to which I'm going
to post separate patches.

Reviewed By: martong

Differential Revision: https://reviews.llvm.org/D127836
2022-06-15 16:50:12 +02:00
Shao-Ce SUN e180cc5ff1 [Driver][test] Make RISCV tests robust with PATH=
When `riscv64-unknown-linux-gnu-ld` is in the PATH, `clang -### -fuse-ld=ld --target=riscv64-unknown-linux-gnu` will use unknown-linux-gnu-ld first, which causes the error in the lit test.

Reviewed By: MaskRay

Differential Revision: https://reviews.llvm.org/D127589
2022-06-15 22:25:22 +08:00
Krasimir Georgiev 8f2ba36336 Revert "[ARM][Thumb] Command-line option to ensure AAPCS compliant Frame Records AND [NFC][Thumb] Update frame-chain codegen test to use thumbv6m"
This reverts commit 7625e01d66 and
dependent cbcce82ef6.

Commit 7625e01d66 causes some new codegen test
failures under asan, e.g., CodeGen/ARM/execute-only.ll:
https://lab.llvm.org/buildbot/#/builders/5/builds/24659/steps/15/logs/stdio.
2022-06-15 16:10:02 +02:00
Gabor Marton f7a38eeccb [analyzer][NFC][test] Add new RUN line with support-symbolic-integer-casts=true to expr-inspection.cpp
Added a new run line to bolster gradual transition of handling cast operations,
see https://discourse.llvm.org/t/roadmap-of-modeling-symbolic-cast-operations/63107

Differential Revision: https://reviews.llvm.org/D127649
2022-06-15 16:06:53 +02:00
Timm Bäder c149fa1f5f [clang][sema] Provide better diagnostic for missing template arguments
Instead of just complaining that "x is not a class, namespace or
enumeration", mention that using x requires template arguments.

Differential Revision: https://reviews.llvm.org/D127638

Fixes https://github.com/llvm/llvm-project/issues/55962
2022-06-15 16:06:06 +02:00
Timm Bäder bce55d0690 [clang][NFC] Remove unused parameter from ActOnCXXNestedNameSpecifier 2022-06-15 16:06:06 +02:00
Furkan Usta 462def25ec
[clang] Use correct visibility parameters when following a Using declaration
Fixes https://github.com/clangd/clangd/issues/1137

Reviewed By: kadircet

Differential Revision: https://reviews.llvm.org/D127629
2022-06-15 15:52:59 +02:00
Gabor Marton 3605ebca32 [analyzer][NFC][test] Add new RUN lint with support-symbolic-integer-casts=true to svalbuilder-rearrange-comparisons.c
Added a new run line to bolster gradual transition of handling cast operations,
see https://discourse.llvm.org/t/roadmap-of-modeling-symbolic-cast-operations/63107

Differential Revision: https://reviews.llvm.org/D127646
2022-06-15 13:52:18 +02:00
Simon Pilgrim 43e7ba6495 Fix signed/unsigned comparison warning 2022-06-15 11:53:08 +01:00
Benjamin Kramer 170ca11aef [Sema] Remove unused function after 8c7b64b5ae 2022-06-15 12:20:44 +02:00
Stanislav Gatev 8fcdd62585 [clang][dataflow] Add support for correlated branches to optional model
Add support for correlated branches to the std::optional dataflow model.

Differential Revision: https://reviews.llvm.org/D125931

Reviewed-by: ymandel, xazax.hun
2022-06-15 10:00:44 +00: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
Sven van Haastregt 7acc88be03 [OpenCL] Reword unknown extension pragma diagnostic
For newer OpenCL extensions that do not require a pragma, such as
`cl_khr_subgroup_shuffle`, a user could still accidentally attempt to
use a pragma.  This would result in a warning
  "unknown OpenCL extension 'cl_khr_subgroup_shuffle' - ignoring"
which could be mistakenly interpreted as "clang does not support this
extension at all" instead of "clang does not require any pragma for
this extension".

Differential Revision: https://reviews.llvm.org/D126660
2022-06-15 10:54:46 +01:00
Martin Boehme 4c2bccfda3 [Clang] Documentation-only: Add missing closing `>` in AttrDocs.td 2022-06-15 10:59:07 +02:00
Martin Boehme 1784fe7be7 [Clang] Fix signed-unsigned comparison warning that breaks the ppc64 build. 2022-06-15 10:53:14 +02:00
Martin Boehme 665da187cc [Clang] Add the `annotate_type` attribute
This is an analog to the `annotate` attribute but for types. The intent is to allow adding arbitrary annotations to types for use in static analysis tools.

For details, see this RFC:

https://discourse.llvm.org/t/rfc-new-attribute-annotate-type-iteration-2/61378

Reviewed By: aaron.ballman

Differential Revision: https://reviews.llvm.org/D111548
2022-06-15 09:47:28 +02:00
owenca 07b3446d72 [clang-format] Never analyze insert/remove braces in the same pass
Turn off RemoveBracesLLVM while analyzing InsertBraces and vice
versa to avoid potential interference of each other and better the
performance.

Differential Revision: https://reviews.llvm.org/D127685
2022-06-14 22:42:54 -07:00
Ben Shi 753b915167 [Driver] Improve linking options for target AVR
1. Support user specified linker (-fuse-ld)
2. Support user specified linker script (-T)

Reviewed By: MaskRay, haowei

Differential Revision: https://reviews.llvm.org/D126192
2022-06-15 02:57:31 +00:00
Yaxun (Sam) Liu af9ee3357c [HIP] fix long double size
For amdgpu target long double type is the same as double type.
The width and align of long double type was incorrectly
overridden when copying aux target properties, which
caused assertion in codegen when emitting global
variables with long double type.

This patch fix that by saving and restoring width
and align of long double type.

Reviewed by: Artem Belevich

Differential Revision: https://reviews.llvm.org/D127771

Fixes: SWDEV-335515
2022-06-14 21:57:56 -04:00
Haowei Wu 7fae15f925 Revert "[Driver] Improve linking options for target AVR"
This reverts commit 3b6e166999 which
causes Clang Driver test failures on Fuchsia builders.
2022-06-14 17:53:46 -07:00
Wei Yi Tee 97d69cdaf3 [clang][dataflow] Rename `getPointeeLoc` to `getReferentLoc` for ReferenceValue.
We distinguish between the referent location for `ReferenceValue` and pointee location for `PointerValue`. The former must be non-empty but the latter may be empty in the case of a `nullptr`

Reviewed By: gribozavr2, sgatev

Differential Revision: https://reviews.llvm.org/D127745
2022-06-15 00:53:30 +02:00
Anders Waldenborg 657e954939 [clang] Add tests for statement expression in initializers
The commit 683e83c5
  [Clang][C++2b] P2242R3: Non-literal variables [...] in constexpr
fixed a code generation bug when using (C-extension) statement
expressions inside initializer expressions.

Before that commit a nested static initializer inside the statement
expression would not be emitted, causing it to be zero initialized.

It is a bit surprising (at least to me) that a commit implementing a new
C++ feature would fix this code generation bug. Zooming in it is the
change done in ExprConstant.cpp that helps. That changes so that
"ESR_Failed" is returned in more cases, causing the expression to not be
deemed constant. This fixes the code generation as instead the compiler
has to resort to generating a dynamic initializer.

That commit also meant that some statement expressions (in particular
the ones using static variables) that previously were accepted now are
errors due to not being constant (matching GCC behavior).

Given how a seemingly unrelated change caused this behavior to change,
it is probably a good thing to add at least some rudimentary tests for
these kind expressions.

Differential Revision: https://reviews.llvm.org/D127201
2022-06-14 23:16:41 +02:00
Joseph Huber c4a2674e21 [Clang] Simplify unifying target features
This patch simplifies how we unify target features. Now we simply
iterate the input in reverse and only insert the feature if it hasn't
been seen yet. The only reason we need to reverse this at the end is to
keep the features in order for the existing tests.

Reviewed By: tra

Differential Revision: https://reviews.llvm.org/D127707
2022-06-14 15:58:16 -04:00
Shivam 6ccc2733e7
Update ASTImportError.h 2022-06-15 00:45:07 +05:30
isuckatcs caf2767c47 [Clang][AST] Fixed BindingDecl AST-dump for tuple like structures
The AST of a BindingDecl in case of tuple like structures wasn't
properly printed. For these bidnings there is information stored
in BindingDecl::getHoldingVar(), and this information was't
printed in the AST-dump.

Differential Revision: https://reviews.llvm.org/D126131
2022-06-14 21:13:04 +02:00
phyBrackets 9d637956b7 [clang][NFC][AST] rename the ImportError to ASTImportError
this patch is the continuation of my previous patch regarding the ImportError in ASTImportError.h

Reviewed By: martong

Differential Revision: https://reviews.llvm.org/D125340
2022-06-15 00:40:32 +05:30
Balazs Benics 21ff652de9 [analyzer][NFC] Replace getLastArg with hasArg when applicable
Depends on D126215.
2022-06-14 19:28:44 +02:00
Petr Hosek 18a1fc8459 [CMake][compiler-rt] Provide a dedicated option for LLVM unwinder
This allows configuring LLVM unwinder separately from the C++ library
matching how we configure it in libcxx.

This also applies changes made to libunwind+libcxxabi+libcxx in D113253
to compiler-rt.

Differential Revision: https://reviews.llvm.org/D115674
2022-06-14 17:26:25 +00:00
Balazs Benics cf078adc90 [analyzer][NFC] Remove unused ExprEngine::evalBinOp functions
Reviewed By: martong

Differential Revision: https://reviews.llvm.org/D127732
2022-06-14 19:15:20 +02:00
Balazs Benics 40940fb2a6 [analyzer][NFC] Substitute the SVal::evalMinus and evalComplement functions
Depends on D126127

Reviewed By: martong

Differential Revision: https://reviews.llvm.org/D127734
2022-06-14 18:56:43 +02:00
Balazs Benics cfc915149c [analyzer][NFC] Relocate unary transfer functions
This is an initial step of removing the SimpleSValBuilder abstraction. The SValBuilder alone should be enough.

Reviewed By: martong

Differential Revision: https://reviews.llvm.org/D126127
2022-06-14 18:56:43 +02:00
Matheus Izvekov 671eb7dc1e
[clang] AST/Print: honor AlwaysIncludeTypeForTemplateArgument policy
This redoes D103040 in a way that `AlwaysIncludeTypeForTemplateArgument = false`
policy is honored for printing template specialization types.
This can be seen for example when printing a canonicalized
dependent TemplateSpecializationType which has integral arguments.

Signed-off-by: Matheus Izvekov <mizvekov@gmail.com>

Reviewed By: v.g.vassilev

Differential Revision: https://reviews.llvm.org/D126620
2022-06-14 18:18:24 +02:00
Serge Pavlov 6117784c5f [NFC] Remove unused function parameter 2022-06-14 22:00:59 +07:00
Shivam Gupta 48e1829874 [Diagnostics] Fix inconsistent shift-overflow warnings in C++20
This fixes https://github.com/llvm/llvm-project/issues/52873.
Don't warn in C++2A mode (and newer), as signed left shifts
always wrap and never overflow. Ref. -
https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2018/p1236r1.html.
2022-06-14 20:19:46 +05:30
Joseph Huber 6a6484c666 [OpenMP] Fix offload packager not writing to temps correctly
The offloading packager doesn't have a normal offloading kind. This
would result in its output being sent to the executable name when in
save-temps mode. This would then get overwritten by the actual output.
This patch adds specific checks to make sure that it gets the correct
name.

Reviewed By: tra

Differential Revision: https://reviews.llvm.org/D127673
2022-06-14 09:16:28 -04:00
Lucas Prates 7625e01d66 [ARM][Thumb] Command-line option to ensure AAPCS compliant Frame Records
Currently the a AAPCS compliant frame record is not always created for
functions when it should. Although a consistent frame record might not
be required in some cases, there are still scenarios where applications
may want to make use of the call hierarchy made available trough it.

In order to enable the use of AAPCS compliant frame records whilst keep
backwards compatibility, this patch introduces a new command-line option
(`-mframe-chain=[none|aapcs|aapcs+leaf]`) for Aarch32 and Thumb backends.
The option allows users to explicitly select when to use it, and is also
useful to ensure the extra overhead introduced by the frame records is
only introduced when necessary, in particular for Thumb targets.

Reviewed By: efriedma

Differential Revision: https://reviews.llvm.org/D125094
2022-06-14 13:37:51 +01:00
Jun Zhang 44f0a2658d
Revert "Reland "[CodeGen] Keep track info of lazy-emitted symbols in ModuleBuilder""
This reverts commit 781ee538da.

Asan build is still broken :(
2022-06-14 19:53:17 +08:00
Balazs Benics de6ba9704d [analyzer][Casting] Support isa, cast, dyn_cast of SVals
This change specializes the LLVM RTTI mechanism for SVals.
After this change, we can use the well-known `isa`, `cast`, `dyn_cast`.

Examples:

  // SVal V = ...;
  // Loc MyLoc = ...;

  bool IsInteresting = isa<loc::MemRegionVal, loc::GotoLabel>(MyLoc);
  auto MRV = cast<loc::MemRegionVal>(MyLoc);
  Optional<loc::MemRegionVal> MaybeMRV = dyn_cast<loc::MemRegionVal>(V)

The current `SVal::getAs` and `castAs` member functions are redundant at
this point, but I believe that they are still handy.

The member function version is terse and reads left-to-right, which IMO
is a great plus. However, we should probably add a variadic `isa` member
function version to have the same casting API in both cases.

Thanks for the extensive TMP help @bzcheeseman!

Reviewed By: bzcheeseman

Differential Revision: https://reviews.llvm.org/D125709
2022-06-14 13:43:04 +02:00
Guillaume Chatelet d9b8d13f8b [NFC][Alignment] Use MaybeAlign in CGCleanup/CGExpr 2022-06-14 10:56:36 +00:00
Jun Zhang 781ee538da
Reland "[CodeGen] Keep track info of lazy-emitted symbols in ModuleBuilder"
This reverts commits:
d3ddc251ac
d90eecff5c

This relands below commit with asan fix:

The intent of this patch is to selectively carry some states over to
the Builder so we won't lose the information of the previous symbols.

This used to be several downstream patches of Cling, it aims to fix
errors in Clang Interpreter when trying to use inline functions.
Before this patch:

clang-repl> inline int foo() { return 42;}
clang-repl> int x = foo();

JIT session error: Symbols not found: [ _Z3foov ]
error: Failed to materialize symbols:
{ (main, { x, $.incr_module_1.__inits.0, __orc_init_func.incr_module_1 }) }

Co-authored-by: Axel Naumann <Axel.Naumann@cern.ch>
Signed-off-by: Jun Zhang <jun@junz.org>

Differential Revision: https://reviews.llvm.org/D127730
2022-06-14 18:36:03 +08:00
Balazs Benics 9da697e1bc Reland "[analyzer] Deprecate the unused 'analyzer-opt-analyze-nested-blocks' cc1 flag"
It was previously reverted by 8406839d19.

---

This flag was introduced by
6818991d71
    commit 6818991d71
    Author: Ted Kremenek <kremenek@apple.com>
    Date:   Mon Dec 7 22:06:12 2009 +0000

  Add clang-cc option '-analyzer-opt-analyze-nested-blocks' to treat
  block literals as an entry point for analyzer checks.

The last reference was removed by this commit:
5c32dfc5fb

    commit 5c32dfc5fb
    Author: Anna Zaks <ganna@apple.com>
    Date:   Fri Dec 21 01:19:15 2012 +0000

  [analyzer] Add blocks and ObjC messages to the call graph.
  This paves the road for constructing a better function dependency graph.
  If we analyze a function before the functions it calls and inlines,
  there is more opportunity for optimization.
  Note, we add call edges to the called methods that correspond to
  function definitions (declarations with bodies).

Consequently, we should remove this dead flag.
However, this arises a couple of burning questions.
 - Should the `cc1` frontend still accept this flag - to keep
   tools/users passing this flag directly to `cc1` (which is unsupported,
   unadvertised) working.
 - If we should remain backward compatible, how long?
 - How can we get rid of deprecated and obsolete flags at some point?

Reviewed By: martong

Differential Revision: https://reviews.llvm.org/D126067
2022-06-14 10:22:37 +02:00
Balazs Benics 24bd47dc17 [analyzer][NFC] Inline AnalyzerOptions::getUserMode()
When I read the code I found it easier to reason about if `getUserMode`
is inlined. It might be a personal preference though.

Reviewed By: martong

Differential Revision: https://reviews.llvm.org/D127486
2022-06-14 09:42:58 +02:00
Balazs Benics ffe7950ebc Reland "[analyzer] Deprecate `-analyzer-store region` flag"
I'm trying to remove unused options from the `Analyses.def` file, then
merge the rest of the useful options into the `AnalyzerOptions.def`.
Then make sure one can set these by an `-analyzer-config XXX=YYY` style
flag.
Then surface the `-analyzer-config` to the `clang` frontend;

After all of this, we can pursue the tablegen approach described
https://discourse.llvm.org/t/rfc-tablegen-clang-static-analyzer-engine-options-for-better-documentation/61488

In this patch, I'm proposing flag deprecations.
We should support deprecated analyzer flags for exactly one release. In
this case I'm planning to drop this flag in `clang-16`.

In the clang frontend, now we won't pass this option to the cc1
frontend, rather emit a warning diagnostic reminding the users about
this deprecated flag, which will be turned into error in clang-16.

Unfortunately, I had to remove all the tests referring to this flag,
causing a mass change. I've also added a test for checking this warning.

I've seen that `scan-build` also uses this flag, but I think we should
remove that part only after we turn this into a hard error.

Reviewed By: martong

Differential Revision: https://reviews.llvm.org/D126215
2022-06-14 09:20:41 +02:00
Chuanqi Xu 735e6c40b5 [Coroutines] Convert coroutine.presplit to enum attr
This is required by @nikic in https://reviews.llvm.org/D127383 to
decrease the cost to check whether a function is a coroutine and this
fixes a FIXME too.

Reviewed By: rjmccall, ezhulenev

Differential Revision: https://reviews.llvm.org/D127471
2022-06-14 14:23:46 +08:00
Argyrios Kyrtzidis f7e19a5928 [Lex] Keep track of skipped preprocessor blocks and advance the lexer directly if they are revisited
This speeds up preprocessing, specifically for preprocessing the clang sources time is reduced by about -36%,
using measurements on M1Pro with a release+thinLTO build.

Differential Revision: https://reviews.llvm.org/D127379
2022-06-13 21:46:46 -07:00
Fangrui Song 11cf75f602 [Driver][test] Make ananas.c and solaris-ld.c robust
`{{.*}}crt{{[^.]+}}.o` may match `"-r" "/tmp/lit-tmp-9ur5crtx/solaris-ld-4fa504.o"`
in a lit invocation.
2022-06-13 19:44:24 -07:00
Fangrui Song 0ba43f4c2b [sanitizer] Add -lresolv only for non-Android non-musl Linux
Refine the D127145 logic with my original suggestion.
It turns out that many OSes don't have libresolv.
2022-06-13 19:12:13 -07:00
Ben Shi 3b6e166999 [Driver] Improve linking options for target AVR
1. Support user specified linker (-fuse-ld)
2. Support user specified linker script (-T)

Reviewed By: MaskRay

Differential Revision: https://reviews.llvm.org/D126192
2022-06-14 01:30:49 +00:00
Ben Shi 520d17bfa0 Revert "[Driver] Improve linking options for target AVR"
This reverts commit d7599be9e8.
2022-06-14 09:12:21 +08:00
Ben Shi d7599be9e8 [Driver] Improve linking options for target AVR
1. Support linking with lld
2. Support user specifed linker script

Reviewed By: MaskRay

Differential Revision: https://reviews.llvm.org/D126192
2022-06-13 23:38:59 +00:00