trivial.
We previously took a shortcut by assuming that if a subobject had a
trivial copy assignment operator (with a few side-conditions), we would
always invoke it, and could avoid going through overload resolution.
That turns out to not be correct in the presenve of ref-qualifiers (and
also won't be the case for copy-assignments with requires-clauses
either). Use the same logic for lazy declaration of copy-assignments
that we use for all other special member functions.
Previously committed as c57f8a3a20. This
now also includes an extension of LLDB's workaround for handling special
members without the help of Sema to cover copy assignments.
trivial.
We previously took a shortcut by assuming that if a subobject had a
trivial copy assignment operator (with a few side-conditions), we would
always invoke it, and could avoid going through overload resolution.
That turns out to not be correct in the presenve of ref-qualifiers (and
also won't be the case for copy-assignments with requires-clauses
either). Use the same logic for lazy declaration of copy-assignments
that we use for all other special member functions.
In C++17 the postfix-expression of a call expression is sequenced before
each expression in the expression-list and any default argument.
Differential Revision: https://reviews.llvm.org/D58579
Reviewed By: rsmith
parameters with default arguments.
Directly follow the wording by relaxing the AST invariant that all
parameters after one with a default arguemnt also have default
arguments, and removing the diagnostic on missing default arguments
on a pack-expanded parameter following a parameter with a default
argument.
Testing also revealed that we need to special-case explicit
specializations of templates with a pack following a parameter with a
default argument, as such explicit specializations are otherwise
impossible to write. The standard wording doesn't address this case; a
issue has been filed.
This exposed a bug where we would briefly consider a parameter to have
no default argument while we parse a delay-parsed default argument for
that parameter, which is also fixed.
Partially incorporates a patch by Raul Tambre.
Summary:
Add a new warning -Wuninitialized-const-reference as a subgroup of -Wuninitialized to address a bug filed here: https://bugs.llvm.org/show_bug.cgi?id=45624
This warning is controlled by -Wuninitialized and can be disabled by -Wno-uninitialized-const-reference.
The warning is diagnosed when passing uninitialized variables as const reference parameters to a function.
Differential Revision: https://reviews.llvm.org/D79895
This patch implements matrix index expressions
(matrix[RowIdx][ColumnIdx]).
It does so by introducing a new MatrixSubscriptExpr(Base, RowIdx, ColumnIdx).
MatrixSubscriptExprs are built in 2 steps in ActOnMatrixSubscriptExpr. First,
if the base of a subscript is of matrix type, we create a incomplete
MatrixSubscriptExpr(base, idx, nullptr). Second, if the base is an incomplete
MatrixSubscriptExpr, we create a complete
MatrixSubscriptExpr(base->getBase(), base->getRowIdx(), idx)
Similar to vector elements, it is not possible to take the address of
a MatrixSubscriptExpr.
For CodeGen, a new MatrixElt type is added to LValue, which is very
similar to VectorElt. The only difference is that we may need to cast
the type of the base from an array to a vector type when accessing it.
Reviewers: rjmccall, anemet, Bigcheese, rsmith, martong
Reviewed By: rjmccall
Differential Revision: https://reviews.llvm.org/D76791
This patch implements the + and - binary operators for values of
MatrixType. It adds support for matrix +/- matrix, scalar +/- matrix and
matrix +/- scalar.
For the matrix, matrix case, the types must initially be structurally
equivalent. For the scalar,matrix variants, the element type of the
matrix must match the scalar type.
Reviewers: rjmccall, anemet, Bigcheese, rsmith, martong
Reviewed By: rjmccall
Differential Revision: https://reviews.llvm.org/D76793
We didn't properly build default argument expressions previously -- we
failed to build the wrapper CXXDefaultArgExpr node, which meant that
std::source_location misbehaved, and we didn't perform default argument
instantiation when necessary, which meant that dependent default
arguments in function templates didn't work at all.
arr is a volatile non-local array.
This fixes a recent regression exposed by removing lvalue-to-rvalue
conversion of discarded volatile arrays. In passing, regularize the
rules we use to determine whether '(void)expr;' warns when expr is a
volatile glvalue.
We currently diagnose static data members directly contained in unnamed classes,
but we should also diagnose when they're in a class that is nested (directly or
indirectly) in an unnamed class. Do this by iterating up the list of parent
DeclContexts and checking if any is an unnamed class.
Similarly also check for function or method DeclContexts (which includes things
like blocks and openmp captured statements) as then the class is considered to
be a local class, which means static data members aren't allowed.
Differential Revision: https://reviews.llvm.org/D80295
alignment information on VarDecls in more cases
This commit improves upon https://reviews.llvm.org/D21099. The code that
computes the source alignment now understands array subscript
expressions, binary operators, derived-to-base casts, and several more
expressions.
rdar://problem/59242343
Differential Revision: https://reviews.llvm.org/D78767
My test needs a requires target clause to support inline assembly. This
patch splits out the asm tests into a separate test so we don't skip the
rest of the conditions.
The backends don't seem to properly handle the _ExtInt type in inline
assembly with crashes occurring in many. While the ones I tested seem to
work for powers of 2 < 64 (and some any multiple of 64 greater than
that), it seemed like a better idea to just use of this type in inline
assembly prohibited.
the expression that is passed to it if it has a function type or array
type
lvalue-to-rvalue conversion should only be applied to non-function,
non-array types, but clang was applying the conversion to discarded
value expressions of array types.
rdar://problem/61203170
Differential Revision: https://reviews.llvm.org/D78134
Summary: This allows for suppressing warnings about the conversion function never being called if it overrides a virtual function in a base class.
Differential Revision: https://reviews.llvm.org/D78444
We should check non-dependent element types before creating a
DependentSizedMatrixType. Otherwise we do not generate an error message
for dependent-sized matrix types with invalid non-dependent element
types, if the template is never instantiated. See the make5 struct in
the tests.
It also moves the SEMA template tests to
clang/test/SemaTemplate/matrix-type.cpp and introduces a few more test
cases.
This patch adds a matrix type to Clang as described in the draft
specification in clang/docs/MatrixSupport.rst. It introduces a new option
-fenable-matrix, which can be used to enable the matrix support.
The patch adds new MatrixType and DependentSizedMatrixType types along
with the plumbing required. Loads of and stores to pointers to matrix
values are lowered to memory operations on 1-D IR arrays. After loading,
the loaded values are cast to a vector. This ensures matrix values use
the alignment of the element type, instead of LLVM's large vector
alignment.
The operators and builtins described in the draft spec will will be added in
follow-up patches.
Reviewers: martong, rsmith, Bigcheese, anemet, dexonsmith, rjmccall, aaron.ballman
Reviewed By: rjmccall
Differential Revision: https://reviews.llvm.org/D72281
Objective-C++11 and under MS extensions.
This matches the MSVC behavior, and means that Objective-C behaves as a
set of extensions to the base language, rather than replacing the base
language rule with a different one.
The 'class' or 'struct' keyword is only permitted as part of either an
enum definition or a standalone opaque-enum-declaration, not as part of
an elaborated type specifier. We previously failed to diagnose this, and
generally didn't properly implement the restrictions on elaborated type
specifiers for enumeration types.
In passing, also fixed incorrect parsing for enum-bases, which we
previously parsed as a type-name, but are actually a type-specifier-seq.
This matters for cases like 'enum E : int *p;', which is valid as a
Microsoft extension.
Plus some minor parse diagnostic improvements.
Bumped the recently-added ExtWarn for 'enum E : int x;' to be
DefaultError; this is not an intentional extension, so producing an
error by default seems appropriate, but the warning flag to disable it
may still be useful for code written against old Clang. The same
treatment is given here to the diagnostic for 'enum class E x;', which
we similarly have incorrectly accepted for many years. These diagnostics
continue to be suppressed under -fms-extensions and when compiling
Objective-C code. We will need to decide separately whether Objective-C
should follow the C++ rules or the (older) MSVC rules.
Previously we implemented non-standard disambiguation rules to
distinguish an enum-base from a bit-field but otherwise treated a :
after an elaborated-enum-specifier as introducing an enum-base. That
misparses various examples (anywhere an elaborated-type-specifier can
appear followed by a colon, such as within a ternary operator or
_Generic).
We now implement the C++11 rules, with the old cases accepted as
extensions where that seemed reasonable. These amount to:
* an enum-base must always be accompanied by an enum definition (except
in a standalone declaration of the form 'enum E : T;')
* in a member-declaration, 'enum E :' always introduces an enum-base,
never a bit-field
* in a type-specifier (or similar context), 'enum E :' is not
permitted; the colon means whatever else it would mean in that
context.
Fixed underlying types for enums are also permitted in Objective-C and
under MS extensions, plus as a language extension in all other modes.
The behavior in ObjC and MS extensions modes is unchanged (but the
bit-field disambiguation is a bit better); remaining language modes
follow the C++11 rules.
Fixes PR45726, PR39979, PR19810, PR44941, and most of PR24297, plus C++
core issues 1514 and 1966.
Implicit methods for structs can confuse the warning, so exclude checking
the Decl's that are implicit. Implicit Decl's for lambdas still need to
be checked, so skipping all implicit Decl's won't work.
Differential Revision: https://reviews.llvm.org/D79548
The built-in SVE types are supposed to be treated as opaque types.
This means that for initialisation purposes they should be treated
as a single unit, much like a scalar type.
However, as Eli pointed out, actually using "scalar" in the diagnostics
is likely to cause confusion, given the types are logically vectors.
The patch therefore uses custom diagnostics or generalises existing
ones. Some of the messages use the word "indivisible" to try to make
it clear(er) that these types can't be initialised elementwise.
I don't think it's possible to trigger warn_braces_around_(scalar_)init
for sizeless types as things stand, since the types can't be used as
members or elements of more complex types. But it seemed better to be
consistent with ext_many_braces_around_(scalar_)init, so the patch
changes it anyway.
Differential Revision: https://reviews.llvm.org/D76689
Summary:
The crash is triggered on accessing a null InitExpr.
For group declaration, e.g. `auto c = a, &d = {a};`, what's happening:
1. each VarDecl is built separately during the parsing stage.
2. perform the semantic analysis (Sema::BuildDeclaratorGroup) to check
whether the type of the two VarDecl is the same, if not mark it as invalid.
in step 1, VarDecl c and d are built, both of them are valid (after D77395),
but d is without the InitExpr attached (under -fno-recovery-ast), crash
happens in step 2 when accessing the source range of d's InitExpr.
Reviewers: sammccall
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D79473
There are some lookup oddities with these as reported in PR45780, and
GCC doesn't support these behaviors at all. To be more consistent with
GCC and prevent the crashes caused by our lookup issues, nip the problem
in the bud and prohibit enums here.
I added a limit to make sure that _ExtInt isn't exposed on systems that
haven't considered it in their ABI. The ext-int.cpp Sema test didn't
have a triple, so on non x86/x86_64 it would fail with this new error.
This patch adds said triple to make sure this passes.
Fix a few bugs where we would fail to properly determine header to
module correspondence when determining whether to suggest a #include or
import, and suggest a #include more often in language modes where there
is no import syntax. Generally, if the target is in a header with
include guards or #pragma once, we should suggest either #including or
importing that header, and not importing a module that happens to
textually include it.
In passing, improve the notes we attach to the corresponding
diagnostics: calling an entity that we couldn't see "previous" is
confusing.
Looks like this was just a copy & paste mistake from
getDependentSizedExtVectorType. rdar://60092165
Differential revision: https://reviews.llvm.org/D79012
Summary:
We extend the behavior for local functions and methods of local classes
to lambdas in variable initializers. The initializer is not a separate
scope, but we treat it as such.
We also remove the (faulty) instantiation of default arguments in
TreeTransform::TransformLambdaExpr, because it doesn't do proper
initialization, and if it did, we would do it twice (and thus also emit
eventual errors twice).
Reviewed By: rsmith
Differential Revision: https://reviews.llvm.org/D76038
Summary:
This patch contains 2 separate changes:
1) the initializer of a variable should play no part in decl "invalid" bit;
2) preserve the invalid initializer via recovery exprs;
With 1), we will regress the diagnostics (one big regression is that we loose
the "selected 'begin' function with iterator type" diagnostic in for-range stmt;
but with 2) together, we don't have regressions (the new diagnostics seems to be
improved).
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D78116
This reverts commit 61ba1481e2.
I'm reverting this because it breaks the lldb build with
incomplete switch coverage warnings. I would fix it forward,
but am not familiar enough with lldb to determine the correct
fix.
lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp:3958:11: error: enumeration values 'DependentExtInt' and 'ExtInt' not handled in switch [-Werror,-Wswitch]
switch (qual_type->getTypeClass()) {
^
lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp:4633:11: error: enumeration values 'DependentExtInt' and 'ExtInt' not handled in switch [-Werror,-Wswitch]
switch (qual_type->getTypeClass()) {
^
lldb/source/Plugins/TypeSystem/Clang/TypeSystemClang.cpp:4889:11: error: enumeration values 'DependentExtInt' and 'ExtInt' not handled in switch [-Werror,-Wswitch]
switch (qual_type->getTypeClass()) {
Introduction/Motivation:
LLVM-IR supports integers of non-power-of-2 bitwidth, in the iN syntax.
Integers of non-power-of-two aren't particularly interesting or useful
on most hardware, so much so that no language in Clang has been
motivated to expose it before.
However, in the case of FPGA hardware normal integer types where the
full bitwidth isn't used, is extremely wasteful and has severe
performance/space concerns. Because of this, Intel has introduced this
functionality in the High Level Synthesis compiler[0]
under the name "Arbitrary Precision Integer" (ap_int for short). This
has been extremely useful and effective for our users, permitting them
to optimize their storage and operation space on an architecture where
both can be extremely expensive.
We are proposing upstreaming a more palatable version of this to the
community, in the form of this proposal and accompanying patch. We are
proposing the syntax _ExtInt(N). We intend to propose this to the WG14
committee[1], and the underscore-capital seems like the active direction
for a WG14 paper's acceptance. An alternative that Richard Smith
suggested on the initial review was __int(N), however we believe that
is much less acceptable by WG14. We considered _Int, however _Int is
used as an identifier in libstdc++ and there is no good way to fall
back to an identifier (since _Int(5) is indistinguishable from an
unnamed initializer of a template type named _Int).
[0]https://www.intel.com/content/www/us/en/software/programmable/quartus-prime/hls-compiler.html)
[1]http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2472.pdf
Differential Revision: https://reviews.llvm.org/D73967
Summary:
Previously, we treated CXXUuidofExpr as quite a special case: it was the
only kind of expression that could be a canonical template argument, it
could be a constant lvalue base object, and so on. In addition, we
represented the UUID value as a string, whose source form we did not
preserve faithfully, and that we partially parsed in multiple different
places.
With this patch, we create an MSGuidDecl object to represent the
implicit object of type 'struct _GUID' created by a UuidAttr. Each
UuidAttr holds a pointer to its 'struct _GUID' and its original
(as-written) UUID string. A non-value-dependent CXXUuidofExpr behaves
like a DeclRefExpr denoting that MSGuidDecl object. We cache an APValue
representation of the GUID on the MSGuidDecl and use it from constant
evaluation where needed.
This allows removing a lot of the special-case logic to handle these
expressions. Unfortunately, many parts of Clang assume there are only
a couple of interesting kinds of ValueDecl, so the total amount of
special-case logic is not really reduced very much.
This fixes a few bugs and issues:
* PR38490: we now support reading from GUID objects returned from
__uuidof during constant evaluation.
* Our Itanium mangling for a non-instantiation-dependent template
argument involving __uuidof no longer depends on which CXXUuidofExpr
template argument we happened to see first.
* We now predeclare ::_GUID, and permit use of __uuidof without
any header inclusion, better matching MSVC's behavior. We do not
predefine ::__s_GUID, though; that seems like a step too far.
* Our IR representation for GUID constants now uses the correct IR type
wherever possible. We will still fall back to using the
{i32, i16, i16, [8 x i8]}
layout if a definition of struct _GUID is not available. This is not
ideal: in principle the two layouts could have different padding.
Reviewers: rnk, jdoerfert
Subscribers: arphaman, cfe-commits, aeubanks
Tags: #clang
Differential Revision: https://reviews.llvm.org/D78171
Summary:
This patch would cause clang emit more diagnostics, but it is much better than https://reviews.llvm.org/D76831
```cpp
struct A {
A(int);
~A() = delete;
};
void k() {
A a;
}
```
before the patch:
/tmp/t3.cpp:24:5: error: no matching constructor for initialization of 'A'
A a;
^
/tmp/t3.cpp:20:3: note: candidate constructor not viable: requires 1 argument, but 0 were provided
A(int);
^
/tmp/t3.cpp:19:8: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided
struct A {
After the patch:
/tmp/t3.cpp:24:5: error: no matching constructor for initialization of 'A'
A a;
^
/tmp/t3.cpp:20:3: note: candidate constructor not viable: requires 1 argument, but 0 were provided
A(int);
^
/tmp/t3.cpp:19:8: note: candidate constructor (the implicit copy constructor) not viable: requires 1 argument, but 0 were provided
struct A {
^
/tmp/t3.cpp:24:5: error: attempt to use a deleted function
A a;
^
/tmp/t3.cpp:21:3: note: '~A' has been explicitly marked deleted here
~A() = delete;
Reviewers: sammccall
Reviewed By: sammccall
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D77395
In the MS C++ ABI, the complete destructor variant for a class with
virtual bases is emitted whereever it is needed, instead of directly
alongside the base destructor variant. The complete destructor calls the
base destructor of the current class and the base destructors of each
virtual base. In order for this to work reliably, translation units that
use the destructor of a class also need to mark destructors of virtual
bases of that class used.
Fixes PR38521
Reviewed By: rsmith
Differential Revision: https://reviews.llvm.org/D77081
constructor with default arguments.
We used to try to rebuild the call as a call to the faked-up inherited
constructor, which is only a placeholder and lacks (for example) default
arguments. Instead, build the call by reference to the original
constructor.
In passing, add a note to say where a call that recursively uses a
default argument from within itself occurs. This is usually pretty
obvious, but still at least somewhat useful, and would have saved
significant debugging time for this particular bug.
as invalid.
We create those when forming trivial type source information with no
associated location, which, unfortunately, we do create in some cases
(when a TreeTransform with no base location is used to transform a
QualType).
This would previously lead to rejects-valid bugs when we misinterpreted
these constructs as having no nested-name-specifier.
memchr consistent and comprehensible, and document them.
We previously allowed evaluation of memcmp on arrays of integers of any
size, so long as the call evaluated to 0, and allowed evaluation of
memchr on any array of integral type of size 1 (including enums). The
purpose of constant-evaluating these builtins is only to support
constexpr std::char_traits, so we now consistently allow them on arrays
of (possibly signed or unsigned) char only.
Summary:
This matches llvm::VectorType.
It moves the size from the type bitfield into VectorType, increasing size by 8
bytes (including padding of 4). This is OK as we don't expect to create terribly
many of these types.
c.f. D77313 which enables large power-of-two sizes without growing VectorType.
Reviewers: efriedma, hokein
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D77335
adb290d974 added a new case to
err_atomic_specifier_bad_type. The diagnostic has two %select's
controlled by the same argument, but only the first was updated to have
the new case. Add the extra case for the second %select and add a
test case that exercises the last case.
-Wthread-safety was failing to detect certain AST patterns it should
detect. Make the pattern detection a bit more comprehensive.
Due to an unrelated bug involving template instantiation, this showed up
as a regression in 10.0 vs. 9.0 in the original bug report. The included
testcase fails on older versions of clang, though.
Fixes https://bugs.llvm.org/show_bug.cgi?id=45323 .
Differential Revision: https://reviews.llvm.org/D76943
The __builtin_stdarg_start is the legacy spelling of __builtin_va_start.
It should behave exactly the same, but for the last 9 years it would
behave subtly different for diagnostics. Follow the change from
29ad95b232 to require custom type checking.
scope.
There are a few contexts in which we assume a name is a template name;
if such a context is one where we should perform an unqualified lookup,
and lookup finds nothing, we would form a dependent template name even
if the name is not dependent. This happens in particular for the lookup
of a pseudo-destructor.
In passing, rename ActOnDependentTemplateName to just ActOnTemplateName
given that we apply it for non-dependent template names too.
Instead of bailing out of parsing when we encounter an invalid
template-name or template arguments in a template-id, produce an
annotation token describing the invalid construct.
This avoids duplicate errors and generally allows us to recover better.
In principle we should be able to extend this to store some kinds of
invalid template-id in the AST for tooling use, but that isn't handled
as part of this change.
Built-in SVE types are trivial, since they're trivially copyable
and support default construction.
Differential Revision: https://reviews.llvm.org/D76692
SVE types are trivially copyable: they can be copied simply
by reproducing the byte representation of the source object.
Differential Revision: https://reviews.llvm.org/D76691
This reverts commit 0788acbccb.
This reverts commit c2d7a1f79cedfc9fcb518596aa839da4de0adb69: Revert "[clangd] Add test for FindTarget+RecoveryExpr (which already works). NFC"
It causes a crash on invalid code:
class X {
decltype(unresolved()) foo;
};
constexpr int s = sizeof(X);
Summary: Previously, we dropped the AST node for nonexistent member exprs.
Reviewers: sammccall
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D76764
As reported in PR45298 and PR45299, vector_size type checking would
crash when done in a situation where the scalar is dependent, such as
a member of the current instantiation.
This is because the scalar checking ensures that you can implicitly
convert a value to a vector-type as long as it doesn't require
truncation. It does this by using the constant evaluator to get the
value as a float. Unfortunately, if the scalar is dependent (such as a
member of the current instantiation), we would hit the assert in the
evaluator.
This patch suppresses the truncation- of-value check in the first phase
of translation. All values are properly errored upon instantiation. This
has one minor regression, in that previously in a non-asserts build,
template<typename T>
struct S {
float4 f(float4 f) {
return k + f;
}
static constexpr k = 1.1; // causes a truncation on conversion.
};
would error immediately. Because 'k' is value dependent (as a
member-of-the-current-instantiation), this would still be evaluatable
(despite normally asserting). Due to this patch, this diagnostic is
delayed until instantiation time.
Summary:
Changes:
- handle immediate invocations for constructors.
- add tests
after this patch i believe the implementation of consteval is nearly standard compliant, but IR-gen still needs to be taught not to emit consteval declarations.
Reviewers: rsmith
Reviewed By: rsmith
Subscribers: wchilders
Differential Revision: https://reviews.llvm.org/D74007
Sizeless types can't be used with "new", so it doesn't make sense
to use them with "delete" either. The SVE ACLE therefore doesn't
allow that.
This is slightly stronger than for normal incomplete types, since:
struct S;
void f(S *s) { delete s; }
is (by necessity) just a default-on warning rather than an error.
Differential Revision: https://reviews.llvm.org/D76219
new-expressions for a type T require sizeof(T) to be computable,
so the SVE ACLE does not allow them for sizeless types. At the moment:
auto f() { return new __SVInt8_t; }
creates a call to operator new with a zero size:
%call = call noalias nonnull i8* @_Znwm(i64 0)
This patch reports an appropriate error instead.
Differential Revision: https://reviews.llvm.org/D76218
In the current SVE ACLE spec, the usual rules for throwing and
catching incomplete types also apply to sizeless types. However,
throwing pointers to sizeless types should not pose any real difficulty,
so as an extension, the clang implementation allows that.
This patch enforces these rules for catch statements.
Differential Revision: https://reviews.llvm.org/D76090
Summary:
The same rules for throwing and catching incomplete types also apply
to sizeless types. This patch enforces that for throw statements.
It also make sure that we use "sizeless type" rather "incomplete type"
in the associated message. (Both are correct, but "sizeless type" is
more specific and hopefully more user-friendly.)
The SVE ACLE simply extends the rule for incomplete types to
sizeless types. However, throwing pointers to sizeless types
should not pose any real difficulty, so as an extension,
the clang implementation allows that.
Reviewers: sdesmalen, efriedma, rovka, rjmccall
Subscribers: tschuett, rkruppe, psnobl, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D76088
In the current SVE ACLE spec, the usual rules for throwing and
catching incomplete types also apply to sizeless types. However,
throwing pointers to sizeless types should not pose any real difficulty,
so as an extension, the clang implementation allows that.
This patch enforces these rules for explicit exception specs.
Differential Revision: https://reviews.llvm.org/D76087
This patch completes a trio of changes related to arrays of
sizeless types. It rejects various forms of arithmetic on
pointers to sizeless types, in the same way as for other
incomplete types.
Differential Revision: https://reviews.llvm.org/D76086
clang currently accepts:
__SVInt8_t &foo1(__SVInt8_t *x) { return *x; }
__SVInt8_t &foo2(__SVInt8_t *x) { return x[1]; }
The first function is valid ACLE code and generates correct LLVM IR
(and assembly code). But the second function is invalid for the
same reason that arrays of sizeless types are. Trying to code-generate
the function leads to:
llvm/include/llvm/Support/TypeSize.h:126: uint64_t llvm::TypeSize::getFixedSize() const: Assertion `!IsScalable && "Request for a fixed size on a s
calable object"' failed.
Another problem is that:
template<typename T>
constexpr __SIZE_TYPE__ f(T *x) { return &x[1] - x; }
typedef int arr1[f((int *)0) - 1];
typedef int arr2[f((__SVInt8_t *)0) - 1];
produces:
a.cpp:2:48: warning: subtraction of pointers to type '__SVInt8_t' of zero size has undefined behavior [-Wpointer-arith]
constexpr __SIZE_TYPE__ f(T *x) { return &x[1] - x; }
~~~~~ ^ ~
a.cpp:4:18: note: in instantiation of function template specialization 'f<__SVInt8_t>' requested here
typedef int arr2[f((__SVInt8_t *)0) - 1];
This patch reports an appropriate diagnostic instead.
Differential Revision: https://reviews.llvm.org/D76084
TryAnnotateTypeConstraint could annotate a template-id which doesn't end up being a type-constraint,
in which case control flow would incorrectly flow into ParseImplicitInt.
Reenter the loop in this case.
Enable relevant tests for C++20. This required disabling typo-correction during TryAnnotateTypeConstraint
and changing a test case which is broken due to a separate bug (will be reported and handled separately).
transparent context.
(The same crash would happen if a class template with a friend was
declared in an 'export' block, but there are more issues with that
case.)
The SVE ACLE doesn't allow arrays of sizeless types. At the moment
clang accepts the TU:
__SVInt8_t x[2];
but trying to code-generate it triggers the LLVM assertion:
llvm/lib/IR/Type.cpp:588: static llvm::ArrayType* llvm::ArrayType::get(llvm::Type*, uint64_t): Assertion `isValidElementType(ElementType) && "Invalid type for array element!"' failed.
This patch reports an appropriate error instead.
The rules are slightly more restrictive than for general incomplete types.
For example:
struct s;
typedef struct s arr[2];
is valid as far as it goes, whereas arrays of sizeless types are
invalid in all contexts. BuildArrayType therefore needs a specific
check for isSizelessType in addition to the usual handling of
incomplete types.
Differential Revision: https://reviews.llvm.org/D76082
Since fields can't have sizeless type, it also doesn't make sense
to capture sizeless types by value in lambda expressions. This patch
makes sure that we diagnose that and that we use "sizeless type" rather
"incomplete type" in the associated message. (Both are correct, but
"sizeless type" is more specific and hopefully more user-friendly.)
Differential Revision: https://reviews.llvm.org/D75738
The SVE ACLE doesn't allow fields to have sizeless type. At the moment
clang accepts things like:
struct s { __SVInt8_t x; } y;
but trying to code-generate it leads to LLVM asserts like:
llvm/include/llvm/Support/TypeSize.h:126: uint64_t llvm::TypeSize::getFixedSize() const: Assertion `!IsScalable && "Request for a fixed size on a scalable object"' failed.
This patch adds an associated clang diagnostic.
Differential Revision: https://reviews.llvm.org/D75737
function and an overridden function until we know whether the overriding
function is deleted.
We previously did these checks when we first built the declaration,
which was too soon in some cases. We now defer all these checks to the
end of the class.
Also add missing check that a consteval function cannot override a
non-consteval function and vice versa.
clang accepts a TU containing just:
__SVInt8_t x;
However, sizeless types are not allowed to have static or thread-local
storage duration and trying to code-generate the TU triggers an LLVM
fatal error:
Globals cannot contain scalable vectors
<vscale x 16 x i8>* @x
fatal error: error in backend: Broken module found, compilation aborted!
This patch adds an associated clang diagnostic.
Differential Revision: https://reviews.llvm.org/D75736
It would be difficult to guarantee atomicity for sizeless types,
so the SVE ACLE makes atomic sizeless types invalid. As it happens,
we already rejected them before the patch, but for the wrong reason:
error: _Atomic cannot be applied to type 'svint8_t' (aka '__SVInt8_t')
which is not trivially copyable
The SVE types should be treated as trivially copyable; a later
patch fixes that.
Differential Revision: https://reviews.llvm.org/D75734
A previous patch rejected alignof for sizeless types. This patch
extends that to cover the "aligned" attribute and _Alignas. Since
sizeless types are not meant to be used for long-term data, cannot
be used in aggregates, and cannot have static storage duration,
there shouldn't be any need to fiddle with their alignment.
Like with alignof, this is a conservative position that can be
relaxed in future if it turns out to be too restrictive.
Differential Revision: https://reviews.llvm.org/D75573
clang current accepts:
void foo1(__SVInt8_t *x, __SVInt8_t *y) { *x = *y; }
void foo2(__SVInt8_t *x, __SVInt8_t *y) {
memcpy(y, x, sizeof(__SVInt8_t));
}
The first function is valid ACLE code and generates correct LLVM IR.
However, the second function is invalid ACLE code and generates a
zero-length memcpy. The point of this patch is to reject the use
of sizeof in the second case instead.
There's no similar wrong-code bug for alignof. However, the SVE ACLE
conservatively treats alignof in the same way as sizeof, just as the
C++ standard does for incomplete types. The idea is that layout of
sizeless types is an implementation property and isn't defined at
the language level.
Implementation-wise, the patch adds a new CompleteTypeKind enum
that controls whether RequireCompleteType & friends accept sizeless
built-in types. For now the default is to maintain the status quo
and accept sizeless types. However, the end of the series will flip
the default and remove the Default enum value.
The patch also adds new ...CompleteSized... wrappers that callers can
use if they explicitly want to reject sizeless types. The callers then
use diagnostics that have an extra 0/1 parameter to indicats whether
the type is sizeless or not.
The idea is to have three cases:
1. calls that explicitly reject sizeless types, with a tweaked diagnostic
for the sizeless case
2. calls that explicitly allow sizeless types
3. normal/old-style calls that don't make an explicit choice either way
Once the default is flipped, the 3. calls will conservatively reject
sizeless types, using the same diagnostic as for other incomplete types.
Differential Revision: https://reviews.llvm.org/D75572
This patch adds C and C++ tests for various uses of SVE types.
The tests cover valid uses that are already (correctly) accepted and
invalid uses that are already (correctly) rejected. Later patches
will expand the tests as they fix other cases.[*]
Some of the tests for invalid uses aren't obviously related to
scalable vectors. Part of the reason for having them is to make
sure that the quality of the error message doesn't regress once/if
the types are treated as incomplete types.
[*] These later patches all fix invalid uses that are being incorrectly
accepted. I don't know of any cases in which valid uses are being
incorrectly rejected. In other words, this series is all about
diagnosing invalid code rather than enabling something new.
Differential Revision: https://reviews.llvm.org/D75571
deduction guides.
Previously if an implicit deduction guide had a default argument with a
cleanup, we'd leave the 'pending cleanup' flag set after declaring the
implicit guide. But it turns out that there's no reason to even
substitute into the default argument when declaring an implicit
deduction guide: we only need to record that the default argument
exists, not what it is, since we never actually form a call to a
deduction guide.
Summary:
The messages for two of the warnings are misleading:
* warn_for_range_const_reference_copy suggests that the initialization
of the loop variable results in a copy. But that's not always true,
we just know that some conversion happens, potentially invoking a
constructor or conversion operator. The constructor might copy, as in
the example that lead to this message [1], but it might also not.
However, the constructed object is bound to a reference, which is
potentially misleading, so we rewrite the message to emphasize that.
We also make sure that we print the reference type into the warning
message to clarify that this warning only appears when operator*
returns a reference.
* warn_for_range_variable_always_copy suggests that a reference type
loop variable initialized from a temporary "is always a copy". But
we don't know this, the range might just return temporary objects
which aren't copies of anything. (Assuming RVO a copy constructor
might never have been called.)
The message for warn_for_range_copy is a bit repetitive: the type of a
VarDecl and its initialization Expr are the same up to cv-qualifiers,
because Sema will insert implicit casts or constructor calls to make
them match.
[1] https://bugs.llvm.org/show_bug.cgi?id=32823
Reviewers: aaron.ballman, Mordante, rtrieu
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D75613
is ambiguous, but only one of the possible lookup results could possibly
be right.
Clang recently started diagnosing ambiguity in more cases, and this
broke the build of Firefox. GCC, ICC, MSVC, and previous versions of
Clang all accept some forms of ambiguity here (albeit different ones in
each case); this patch mostly accepts anything any of those compilers
accept.
Summary:
Right now we annotate C++'s `operator new` with `noalias` attribute,
which very much is healthy for optimizations.
However as per [[ http://eel.is/c++draft/basic.stc.dynamic.allocation | `[basic.stc.dynamic.allocation]` ]],
there are more promises on global `operator new`, namely:
* non-`std::nothrow_t` `operator new` *never* returns `nullptr`
* If `std::align_val_t align` parameter is taken, the pointer will also be `align`-aligned
* ~~global `operator new`-returned pointer is `__STDCPP_DEFAULT_NEW_ALIGNMENT__`-aligned ~~ It's more caveated than that.
Supplying this information may not cause immediate landslide effects
on any specific benchmarks, but it for sure will be healthy for optimizer
in the sense that the IR will better reflect the guarantees provided in the source code.
The caveat is `-fno-assume-sane-operator-new`, which currently prevents emitting `noalias`
attribute, and is automatically passed by Sanitizers ([[ https://bugs.llvm.org/show_bug.cgi?id=16386 | PR16386 ]]) - should it also cover these attributes?
The problem is that the flag is back-end-specific, as seen in `test/Modules/explicit-build-flags.cpp`.
But while it is okay to add `noalias` metadata in backend, we really should be adding at least
the alignment metadata to the AST, since that allows us to perform sema checks on it.
Reviewers: erichkeane, rjmccall, jdoerfert, eugenis, rsmith
Reviewed By: rsmith
Subscribers: xbolva00, jrtc27, atanasyan, nlopes, cfe-commits
Tags: #llvm, #clang
Differential Revision: https://reviews.llvm.org/D73380
Summary:
There was even a TODO for this.
The main motivation is to make use of call-site based
`__attribute__((alloc_align(param_idx)))` validation (D72996).
Reviewers: rsmith, erichkeane, aaron.ballman, jdoerfert
Reviewed By: rsmith
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D73020
Compute and propagate conversion kind to diagnostics helper in C++
to provide more specific diagnostics about incorrect implicit
conversions in assignments, initializations, params, etc...
Duplicated some diagnostics as errors because C++ is more strict.
Tags: #clang
Differential Revision: https://reviews.llvm.org/D74116
The diagnostic added in D72231 also shows a diagnostic when casting to a
_Bool. This is unwanted. This patch removes the diagnostic for _Bool types.
Differential Revision: https://reviews.llvm.org/D74860
Summary:
As @rsmith notes in https://reviews.llvm.org/D73020#inline-672219
while that is certainly UB land, it may not be actually reachable at runtime, e.g.:
```
template<int N> void *make() {
if ((N & (N-1)) == 0)
return operator new(N, std::align_val_t(N));
else
return operator new(N);
}
void *p = make<7>();
```
and we shouldn't really error-out there.
That being said, i'm not really following the logic here.
Which ones of these cases should remain being an error?
Reviewers: rsmith, erichkeane
Reviewed By: erichkeane
Subscribers: cfe-commits, rsmith
Tags: #clang
Differential Revision: https://reviews.llvm.org/D73996
user interface and documentation, and update __cplusplus for C++20.
WG21 considers the C++20 standard to be finished (even though it still
has some more steps to pass through in the ISO process).
The old flag names are accepted for compatibility, as usual, and we
still have lots of references to C++2a in comments and identifiers;
those can be cleaned up separately.
and objects with mutable subobjects.
The standard wording doesn't really cover these cases; accepting all
such cases seems most in line with what we do in other cases and what
other compilers do. (Essentially this means we're assuming that objects
external to the evaluation are always in-lifetime.)
The C++ rules briefly allowed this, but the rule changed nearly 10 years
ago and we never updated our implementation to match. However, we've
warned on this by default for a long time, and no other compiler accepts
(even as an extension).
1) Fix a regression in llvmorg-11-init-2485-g0e3a4877840 that would
reject some cases where a class name is shadowed by a typedef-name
causing a destructor declaration to be rejected. Prefer a tag type over
a typedef in destructor name lookup.
2) Convert the "type in destructor declaration is a typedef" error to an
error-by-default ExtWarn to allow codebases to turn it off. GCC and MSVC
do not enforce this rule.
Also add extension warnings for the cases that are disallowed by the
current rules for destructor name lookup, refactor and simplify the
lookup code, and improve the diagnostic quality when lookup fails.
The special case we previously supported for converting
p->N::S<int>::~S() from naming a class template into naming a
specialization thereof is subsumed by a more general rule here (which is
also consistent with Clang's historical behavior and that of other
compilers): if we can't find a suitable S in N, also look in N::S<int>.
The extension warnings are off by default, except for a warning when
lookup for p->N::S::~T() looks for T in scope instead of in N (or N::S).
That seems sufficiently heinous to warn on by default, especially since
we can't support it for a dependent nested-name-specifier.
Summary:
Due to a recent (but retroactive) C++ rule change, only sufficiently
C-compatible classes are permitted to be given a typedef name for
linkage purposes. Add an enabled-by-default warning for these cases, and
rephrase our existing error for the case where we encounter the typedef
name for linkage after we've already computed and used a wrong linkage
in terms of the new rule.
Reviewers: rjmccall
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D74103
constant initialization.
Removing this zeroing regressed our code generation in a few cases, also
fixed here. We now compute whether a variable has constant destruction
even if it doesn't have a constant initializer, by trying to destroy a
default-initialized value, and skip emitting a trivial default
constructor for a variable even if it has non-trivial (but perhaps
constant) destruction.
Summary:
Changes:
- Calls to consteval function are now evaluated in constant context but IR is still generated for them.
- Add diagnostic for taking address of a consteval function in non-constexpr context.
- Add diagnostic for address of consteval function accessible at runtime.
- Add tests
Reviewers: rsmith, aaron.ballman
Reviewed By: rsmith
Subscribers: mgrang, riccibruno, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D63960
Summary:
Clang -fpic defaults to -fno-semantic-interposition (GCC -fpic defaults
to -fsemantic-interposition).
Users need to specify -fsemantic-interposition to get semantic
interposition behavior.
Semantic interposition is currently a best-effort feature. There may
still be some cases where it is not handled well.
Reviewers: peter.smith, rnk, serge-sans-paille, sfertile, jfb, jdoerfert
Subscribers: dschuff, jyknight, dylanmckay, nemanjai, jvesely, kbarton, fedor.sergeev, asb, rbar, johnrusso, simoncook, sabuasal, niosHD, jrtc27, zzheng, edward-jones, atanasyan, rogfer01, MartinMosbeck, brucehoult, the_o, arphaman, PkmX, jocewei, jsji, Jim, lenary, s.egerton, pzheng, sameer.abuasal, apazos, luismarques, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D73865
During the review of D73007 Aaron Puchert mentioned
`warn_for_range_variable_always_copy` shouldn't be part of -Wall since
some coding styles require `for(const auto &bar : bars)`. This warning
would cause false positives for these users. Based on Aaron's proposal
refactored the warnings:
* -Wrange-loop-construct warns about possibly unintended constructor
calls. This is part of -Wall. It contains
* warn_for_range_copy: loop variable A of type B creates a copy from
type C
* warn_for_range_const_reference_copy: loop variable A is initialized
with a value of a different type resulting in a copy
* -Wrange-loop-bind-reference warns about misleading use of reference
types. This is not part of -Wall. It contains
* warn_for_range_variable_always_copy: loop variable A is always a copy
because the range of type B does not return a reference
Differential Revision: https://reviews.llvm.org/D73434
Summary: Just like templates, they are excepted from the ODR rule.
Reviewed By: aaron.ballman, rsmith
Differential Revision: https://reviews.llvm.org/D68923
When used as qualified names, pseudo-destructors are always named as if
they were members of the type, never as members of the namespace
enclosing the type.
Summary:
`alloc_align` attribute takes parameter number, not the alignment itself,
so given **just** the attribute/function declaration we can't do any
sanity checking for said alignment.
However, at call site, given the actual `Expr` that is passed
into that parameter, we //might// be able to evaluate said `Expr`
as Integer Constant Expression, and perform the sanity checks.
But since there is no requirement for that argument to be an immediate,
we may fail, and that's okay.
However if we did evaluate, we should enforce the same constraints
as with `__builtin_assume_aligned()`/`__attribute__((assume_aligned(imm)))`:
said alignment is a power of two, and is not greater than our magic threshold
This was initially committed in c2a9061ac5
but reverted in 00756b1823 because of
suspicious bot failures.
Reviewers: erichkeane, aaron.ballman, hfinkel, rsmith, jdoerfert
Reviewed By: erichkeane
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D72996
Summary:
I kind-of understand why it is restricted to integer-typed arguments,
for general enum's the value passed is not nessesairly the alignment implied,
although one might say that user would know best.
But we clearly should whitelist `std::align_val_t`,
which is just a thin wrapper over `std::size_t`,
and is the C++ standard way of specifying alignment.
Reviewers: erichkeane, rsmith, aaron.ballman, jdoerfert
Reviewed By: erichkeane
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D73019
Summary:
`alloc_align` attribute takes parameter number, not the alignment itself,
so given **just** the attribute/function declaration we can't do any
sanity checking for said alignment.
However, at call site, given the actual `Expr` that is passed
into that parameter, we //might// be able to evaluate said `Expr`
as Integer Constant Expression, and perform the sanity checks.
But since there is no requirement for that argument to be an immediate,
we may fail, and that's okay.
However if we did evaluate, we should enforce the same constraints
as with `__builtin_assume_aligned()`/`__attribute__((assume_aligned(imm)))`:
said alignment is a power of two, and is not greater than our magic threshold
Reviewers: erichkeane, aaron.ballman, hfinkel, rsmith, jdoerfert
Reviewed By: erichkeane
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D72996
This patch implements P1141R2 "Yet another approach for constrained declarations".
General strategy for this patch was:
- Expand AutoType to include optional type-constraint, reflecting the wording and easing the integration of constraints.
- Replace autos in parameter type specifiers with invented parameters in GetTypeSpecTypeForDeclarator, using the same logic
previously used for generic lambdas, now unified with abbreviated templates, by:
- Tracking the template parameter lists in the Declarator object
- Tracking the template parameter depth before parsing function declarators (at which point we can match template
parameters against scope specifiers to know if we have an explicit template parameter list to append invented parameters
to or not).
- When encountering an AutoType in a parameter context we check a stack of InventedTemplateParameterInfo structures that
contain the info required to create and accumulate invented template parameters (fields that were already present in
LambdaScopeInfo, which now inherits from this class and is looked up when an auto is encountered in a lambda context).
Resubmit after fixing MSAN failures caused by incomplete initialization of AutoTypeLocs in TypeSpecLocFiller.
Differential Revision: https://reviews.llvm.org/D65042
This patch implements P1141R2 "Yet another approach for constrained declarations".
General strategy for this patch was:
- Expand AutoType to include optional type-constraint, reflecting the wording and easing the integration of constraints.
- Replace autos in parameter type specifiers with invented parameters in GetTypeSpecTypeForDeclarator, using the same logic
previously used for generic lambdas, now unified with abbreviated templates, by:
- Tracking the template parameter lists in the Declarator object
- Tracking the template parameter depth before parsing function declarators (at which point we can match template
parameters against scope specifiers to know if we have an explicit template parameter list to append invented parameters
to or not).
- When encountering an AutoType in a parameter context we check a stack of InventedTemplateParameterInfo structures that
contain the info required to create and accumulate invented template parameters (fields that were already present in
LambdaScopeInfo, which now inherits from this class and is looked up when an auto is encountered in a lambda context).
Resubmit after incorrect check in NonTypeTemplateParmDecl broke lldb.
Differential Revision: https://reviews.llvm.org/D65042
This patch implements P1141R2 "Yet another approach for constrained declarations".
General strategy for this patch was:
- Expand AutoType to include optional type-constraint, reflecting the wording and easing the integration of constraints.
- Replace autos in parameter type specifiers with invented parameters in GetTypeSpecTypeForDeclarator, using the same logic
previously used for generic lambdas, now unified with abbreviated templates, by:
- Tracking the template parameter lists in the Declarator object
- Tracking the template parameter depth before parsing function declarators (at which point we can match template
parameters against scope specifiers to know if we have an explicit template parameter list to append invented parameters
to or not).
- When encountering an AutoType in a parameter context we check a stack of InventedTemplateParameterInfo structures that
contain the info required to create and accumulate invented template parameters (fields that were already present in
LambdaScopeInfo, which now inherits from this class and is looked up when an auto is encountered in a lambda context).
Differential Revision: https://reviews.llvm.org/D65042
When Wrange-loop-analysis issues a diagnostic on a dependent type in a
template the diagnostic may not be valid for all instantiations. Therefore
the diagnostic is suppressed during the instantiation. Non dependent types
still issue a diagnostic.
The same can happen when using macros. Therefore the diagnostic is
disabled for macros.
Fixes https://bugs.llvm.org/show_bug.cgi?id=44556
Differential Revision: https://reviews.llvm.org/D73007
This needs somewhat careful disambiguation, as C++2a explicit(bool) is a
breaking change. We only enable it in cases where the source construct
could not possibly be anything else.
We currently treat noexcept(not-convertible-to-bool) as 'none', which
results in the typeloc info being a different size, and causing an
assert later on in the process. In order to make recovery less
destructive, replace this with noexcept(false) and a constructed 'false'
expression.
Bug Report: https://bugs.llvm.org/show_bug.cgi?id=44514
Differential Revision: https://reviews.llvm.org/D72621
GCC supports the conditional operator on VectorTypes that acts as a
'select' in C++ mode. This patch implements the support. Types are
converted as closely to GCC's behavior as possible, though in a few
places consistency with our existing vector type support was preferred.
Note that this implementation is different from the OpenCL version in a
number of ways, so it unfortunately required a different implementation.
First, the SEMA rules and promotion rules are significantly different.
Secondly, GCC implements COND[i] != 0 ? LHS[i] : RHS[i] (where i is in
the range 0- VectorSize, for each element). In OpenCL, the condition is
COND[i] < 0 ? LHS[i]: RHS[i].
In the process of implementing this, it was also required to make the
expression COND ? LHS : RHS type dependent if COND is type dependent,
since the type is now dependent on the condition. For example:
T ? 1 : 2;
Is not typically type dependent, since the result can be deduced from
the operands. HOWEVER, if T is a VectorType now, it could change this
to a 'select' (basically a swizzle with a non-constant mask) with the 1
and 2 being promoted to vectors themselves.
While this is a change, it is NOT a standards incompatible change. Based
on my (and D. Gregor's, at the time of writing the code) reading of the
standard, the expression is supposed to be type dependent if ANY
sub-expression is type dependent.
Differential Revision: https://reviews.llvm.org/D71463
No longer generate a diagnostic when a small trivially copyable type is
used without a reference. Before the test looked for a POD type and had no
size restriction. Since the range-based for loop is only available in
C++11 and POD types are trivially copyable in C++11 it's not required to
test for a POD type.
Since copying a large object will be expensive its size has been
restricted. 64 bytes is a common size of a cache line and if the object is
aligned the copy will be cheap. No performance impact testing has been
done.
Differential Revision: https://reviews.llvm.org/D72212
The language wording change forgot to update overload resolution to rank
implicit conversion sequences based on qualification conversions in
reference bindings. The anticipated resolution for that oversight is
implemented here -- we order candidates based on qualification
conversion, not only on top-level cv-qualifiers, including ranking
reference bindings against non-reference bindings if they differ in
non-top-level qualification conversions.
For OpenCL/C++, this allows reference binding between pointers with
differing (nested) address spaces. This makes the behavior of reference
binding consistent with that of implicit pointer conversions, as is the
purpose of this change, but that pre-existing behavior for pointer
conversions is itself probably not correct. In any case, it's now
consistently the same behavior and implemented in only one place.
This reinstates commit de21704ba9,
reverted in commit d8018233d1, with
workarounds for some overload resolution ordering problems introduced by
CWG2352.
explicit functions that are not candidates.
It's not always obvious that the reason a conversion was not possible is
because the function you wanted to call is 'explicit', so explicitly say
if that's the case.
It would be nice to rank the explicit candidates higher in the
diagnostic if an implicit conversion sequence exists for their
arguments, but unfortunately we can't determine that without potentially
triggering non-immediate-context errors that we're not permitted to
produce.
This change introduces three new builtins (which work on both pointers
and integers) that can be used instead of common bitwise arithmetic:
__builtin_align_up(x, alignment), __builtin_align_down(x, alignment) and
__builtin_is_aligned(x, alignment).
I originally added these builtins to the CHERI fork of LLVM a few years ago
to handle the slightly different C semantics that we use for CHERI [1].
Until recently these builtins (or sequences of other builtins) were
required to generate correct code. I have since made changes to the default
C semantics so that they are no longer strictly necessary (but using them
does generate slightly more efficient code). However, based on our experience
using them in various projects over the past few years, I believe that adding
these builtins to clang would be useful.
These builtins have the following benefit over bit-manipulation and casts
via uintptr_t:
- The named builtins clearly convey the semantics of the operation. While
checking alignment using __builtin_is_aligned(x, 16) versus
((x & 15) == 0) is probably not a huge win in readably, I personally find
__builtin_align_up(x, N) a lot easier to read than (x+(N-1))&~(N-1).
- They preserve the type of the argument (including const qualifiers). When
using casts via uintptr_t, it is easy to cast to the wrong type or strip
qualifiers such as const.
- If the alignment argument is a constant value, clang can check that it is
a power-of-two and within the range of the type. Since the semantics of
these builtins is well defined compared to arbitrary bit-manipulation,
it is possible to add a UBSAN checker that the run-time value is a valid
power-of-two. I intend to add this as a follow-up to this change.
- The builtins avoids int-to-pointer casts both in C and LLVM IR.
In the future (i.e. once most optimizations handle it), we could use the new
llvm.ptrmask intrinsic to avoid the ptrtoint instruction that would normally
be generated.
- They can be used to round up/down to the next aligned value for both
integers and pointers without requiring two separate macros.
- In many projects the alignment operations are already wrapped in macros (e.g.
roundup2 and rounddown2 in FreeBSD), so by replacing the macro implementation
with a builtin call, we get improved diagnostics for many call-sites while
only having to change a few lines.
- Finally, the builtins also emit assume_aligned metadata when used on pointers.
This can improve code generation compared to the uintptr_t casts.
[1] In our CHERI compiler we have compilation mode where all pointers are
implemented as capabilities (essentially unforgeable 128-bit fat pointers).
In our original model, casts from uintptr_t (which is a 128-bit capability)
to an integer value returned the "offset" of the capability (i.e. the
difference between the virtual address and the base of the allocation).
This causes problems for cases such as checking the alignment: for example, the
expression `if ((uintptr_t)ptr & 63) == 0` is generally used to check if the
pointer is aligned to a multiple of 64 bytes. The problem with offsets is that
any pointer to the beginning of an allocation will have an offset of zero, so
this check always succeeds in that case (even if the address is not correctly
aligned). The same issues also exist when aligning up or down. Using the
alignment builtins ensures that the address is used instead of the offset. While
I have since changed the default C semantics to return the address instead of
the offset when casting, this offset compilation mode can still be used by
passing a command-line flag.
Reviewers: rsmith, aaron.ballman, theraven, fhahn, lebedev.ri, nlopes, aqjune
Reviewed By: aaron.ballman, lebedev.ri
Differential Revision: https://reviews.llvm.org/D71499
It turns out it is useful to be able to define the deref type as void.
In case we have a type erased owner, we want to express that the pointee
can be basically any type. It should not be unnatural to have a void
deref type as we already familiar with "pointers to void".
Differential Revision: https://reviews.llvm.org/D72097
This makes the range loop warnings part of -Wall.
Fixes PR32823: Warn about accidental coping of data in range based for
Differential Revision: https://reviews.llvm.org/D68912
Recomitted after fixing the warnings it created.
This makes the range loop warnings part of -Wall.
Fixes PR32823: Warn about accidental coping of data in range based for
Differential Revision: https://reviews.llvm.org/D68912
The Wrange-loop-analyses warns if a copy is made. Suppress this warning when
a temporary is bound to a rvalue reference.
While fixing this issue also found a copy-paste error in test6, which is also
fixed.
Differential Revision: https://reviews.llvm.org/D71806
msvc allows a subsequent declaration of a uuid attribute on a
struct/class. Mirror this behavior in clang-cl.
Reviewed By: rnk
Differential Revision: https://reviews.llvm.org/D71439
The current handling of the operators ||, && and ?: has a number of false
positive and false negative. The issues for operator || and && are:
1. We need to add sequencing regions for the LHS and RHS as is done for the
comma operator. Not doing so causes false positives in expressions like
`((a++, false) || (a++, false))` (from PR39779, see PR22197 for another
example).
2. In the current implementation when the evaluation of the LHS fails, the RHS
is added to a worklist to be processed later. This results in false negatives
in expressions like `(a && a++) + a`.
Fix these issues by introducing sequencing regions for the LHS and RHS, and by
not deferring the visitation of the RHS.
The issues with the ternary operator ?: are similar, with the added twist that
we should not warn on expressions like `(x ? y += 1 : y += 2)` since exactly
one of the 2nd and 3rd expression is going to be evaluated, but we should still
warn on expressions like `(x ? y += 1 : y += 2) = y`.
Differential Revision: https://reviews.llvm.org/D57747
Reviewed By: rsmith
C-style cast) to an enumeration type.
We previously forgot to check this, and happened to get away with it
(with bad diagnostics) only because we misclassified incomplete
enumeration types as not being unscoped enumeration types. This also
fixes the misclassification.
This covers:
* usual arithmetic conversions (comparisons, arithmetic, conditionals)
between different enumeration types
* usual arithmetic conversions between enums and floating-point types
* comparisons between two operands of array type
The deprecation warnings are on-by-default (in C++20 compilations); it
seems likely that these forms will become ill-formed in C++23, so
warning on them now by default seems wise.
For the first two bullets, off-by-default warnings were also added for
all the cases where we didn't already have warnings (covering language
modes prior to C++20). These warnings are in subgroups of the existing
-Wenum-conversion (except that the first case is not warned on if either
enumeration type is anonymous, consistent with our existing
-Wenum-conversion warnings).
Summary:
In https://reviews.llvm.org/D62550 @rsmith pointed out that there are
many situations in which a coroutine body statement may be
transformed/rebuilt as part of a template instantiation, and my naive
check whether the coroutine was a generic lambda was insufficient.
This is indeed true, as I've learned by reading more of the
TreeTransform code. Most transformations are written in a way that
doesn't assume the resulting types are not dependent types. So the
assertion in 'TransformCoroutineBodyStmt', that the promise type must no
longer be dependent, is out of place.
This patch removes the assertion, spruces up some code comments, and
adds a test that would have failed with my naive check from
https://reviews.llvm.org/D62550.
Reviewers: GorNishanov, rsmith, lewissbaker
Reviewed By: rsmith
Subscribers: junparser, EricWF, rsmith, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D70579
conservatively assuming they always can.
Also fix cases where we would not consider the computation of a VLA type
when determining whether an expression can throw. We don't yet properly
determine whether a VLA can throw, but no longer incorrectly claim it
can never throw.
Allow sending address spaces into diagnostics to simplify and improve
error reporting. Improved wording of diagnostics for address spaces
in overloading.
Tags: #clang
Differential Revision: https://reviews.llvm.org/D71111
This warning is supposed to be suppressed when the
constructor/destructor are non-trivial, since it might be a RAII type.
However, if the type has a trivial destructor and the constructor hasn't
been resolved (since it is called with dependent arguments), we were
still warning.
This patch suppresses the warning if the type could possibly have a
be a non-trivial constructor call. Note that this does not take the
arity of the constructors into consideration, so it might suppress
the warning in cases where it isn't possible to call a non-trivial
constructor.
In the presence of modules, we can have multiple lookup results for the
same entity, and we need to re-check for completeness each time we
consider a type.
forming non-type template parameter values.
This reverts commit 93cc9dddd8,
which reverted commit 11d1052785.
We now always form `&x` when forming a pointer to a function rather than
trying to use function-to-pointer decay. This matches the behavior of
the old code in this case, but not the intent as described by the
comments.
This reverts commit 11d1052785.
This change is problematic with function pointer template parameters. For
example, building libcxxabi with futexes (-D_LIBCXXABI_USE_FUTEX) produces this
diagnostic:
In file included from .../llvm-project/libcxxabi/src/cxa_guard.cpp:15:
.../llvm-project/libcxxabi/src/cxa_guard_impl.h:416:54: error: address of function 'PlatformThreadID' will always evaluate to 'true' [-Werror,-Wpointer-bool-conversion]
has_thread_id_support(this->thread_id_address && GetThreadIDArg),
~~ ^~~~~~~~~~~~~~
.../llvm-project/libcxxabi/src/cxa_guard.cpp:38:26: note: in instantiation of member function '__cxxabiv1::(anonymous namespace)::InitByteFutex<&__cxxabiv1::(anonymous namespace)::PlatformFutexWait, &__cxxabiv1::(anonymous namespace)::PlatformFutexWake, &__cxxabiv1::(anonymous namespace)::PlatformThreadID>::InitByteFutex' requested here
SelectedImplementation imp(raw_guard_object);
^
.../llvm-project/libcxxabi/src/cxa_guard_impl.h:416:54: note: prefix with the address-of operator to silence this warning
has_thread_id_support(this->thread_id_address && GetThreadIDArg),
^
&
1 error generated.
The diagnostic is incorrect: adding the address-of operator also fails ("cannot
take the address of an rvalue of type 'uint32_t (*)()' (aka 'unsigned int
(*)()')").
If the lambda used 'this' without without capturing it, an error was
emitted, but the constant evaluator would still attempt to lookup the
capture, and failing to find it, dereference a null pointer.
This only happens in C++17 (as that's when lambdas were made
potentially-constexpr). Therefore, I also updated the
lambda-expressions.cpp test to run in both C++14 and C++17 modes.
This patch reapplies commit 759948467e. Patch was reverted due to a
clang-tidy test fail on Windows. The test has been modified. There
are no additional code changes.
Patch was tested with ninja check-all on Windows and Linux.
Summary of code changes:
Clang currently crashes for switch statements inside a template when the
condition is a non-integer field member because contextual implicit
conversion is skipped when parsing the condition. This conversion is
however later checked in an assert when the case statement is handled.
The conversion is skipped when parsing the condition because
the field member is set as type-dependent based on its containing class.
This patch sets the type dependency based on the field's type instead.
This patch fixes Bug 40982.
Summary:
GCC 9 added -Wdeprecated-copy (as part of -Wextra). This diagnostic is already implemented in Clang too, just hidden under -Wdeprecated (not on by default).
This patch adds -Wdeprecated-copy and makes it compatible with GCC 9+.
This diagnostic is heavily tested in deprecated.cpp, so I added simple tests just to check we warn when new flag/-Wextra is enabled.
Reviewers: rsmith, dblaikie
Reviewed By: dblaikie
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D70342
Summary:
The assertion of CoroutineParameterMoves happens when build coroutine function with arguments multiple time while fails to build promise type.
Fix: use return false instead.
Test Plan: check-clang
Reviewers: modocache, GorNishanov, rjmccall
Reviewed By: modocache
Subscribers: rjmccall, EricWF, cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D69022
Patch by junparser (JunMa)!
Some warnings in -Wtautological-compare subgroups are DefaultIgnore.
Adding this group to -Wmost, which is part of -Wall, will aid in their
discoverability.
Differential Revision: https://reviews.llvm.org/D69292
This patch reapplies commit 76945821b9. The first version broke
buildbots due to clang-tidy test fails. The fails are because some
errors in templates are now diagnosed earlier (does not wait till
instantiation). I have modified the tests to add checks for these
diagnostics/prevent these diagnostics. There are no additional code
changes.
Summary of code changes:
Clang currently crashes for switch statements inside a template when the
condition is a non-integer field member because contextual implicit
conversion is skipped when parsing the condition. This conversion is
however later checked in an assert when the case statement is handled.
The conversion is skipped when parsing the condition because
the field member is set as type-dependent based on its containing class.
This patch sets the type dependency based on the field's type instead.
This patch fixes Bug 40982.
Reviewers: rnk, gribozavr2
Patch by: Elizabeth Andrews (eandrews)
Differential revision: https://reviews.llvm.org/D69950
While here, wordsmith the error a bit. Now clang says:
error: filter expression has non-integral type 'Foo'
Fixes PR43779
Reviewers: amccarth
Differential Revision: https://reviews.llvm.org/D69969
Assume that the user knows what they're doing if they provide a char
literal as an array index. This more closely matches the behavior of
GCC.
Differential Revision: https://reviews.llvm.org/D58896
non-constant.
We previously failed the entire condition evaluation if an unmodeled
side-effect was encountered in an argument, even if that argument was
unused in the attribute's condition.
Summary:
This happens when someone initializes a variable with guaranteed copy
elision and an added const qualifier. Fixes PR43826.
Reviewers: aaron.ballman, rsmith
Reviewed By: aaron.ballman
Differential Revision: https://reviews.llvm.org/D69533
Taking a value and the bitwise-or it with a non-zero constant will always
result in a non-zero value. In a boolean context, this is always true.
if (x | 0x4) {} // always true, intended '&'
This patch creates a new warning group -Wtautological-bitwise-compare for this
warning. It also moves in the existing tautological bitwise comparisons into
this group. A few other changes were needed to the CFGBuilder so that all bool
contexts would be checked. The warnings in -Wtautological-bitwise-compare will
be off by default due to using the CFG.
Fixes: https://bugs.llvm.org/show_bug.cgi?id=42666
Differential Revision: https://reviews.llvm.org/D66046
llvm-svn: 375318
This adds support for rewriting <, >, <=, and >= to a normal or reversed
call to operator<=>, for rewriting != to a normal or reversed call to
operator==, and for rewriting <=> and == to reversed forms of those same
operators.
Note that this is a breaking change for various C++17 code patterns,
including some in use in LLVM. The most common patterns (where an
operator== becomes ambiguous with a reversed form of itself) are still
accepted under this patch, as an extension (with a warning). I'm hopeful
that we can get the language rules fixed before C++20 ships, and the
extension warning is aimed primarily at providing data to inform that
decision.
llvm-svn: 375306
Summary:
We don't know what context to use until the classification result is
consumed by the parser, which could happen in a different semantic
context. So don't build the expression that results from name
classification until we get to that point and can handle it properly.
This covers everything except C++ implicit class member access, which
is a little awkward to handle properly in the face of the protected
member access check. But it at least fixes all the currently-filed
instances of PR43080.
Reviewers: efriedma
Subscribers: cfe-commits
Tags: #clang
Differential Revision: https://reviews.llvm.org/D68896
llvm-svn: 374826
whose value is not ignored.
We don't warn on all the cases that are deprecated: specifically, we
choose to not warn for now if there are parentheses around the
assignment but its value is not actually used. This seems like a more
defensible rule, particularly for cases like sizeof(v = a), where the
parens are part of the operand rather than the sizeof syntax.
llvm-svn: 374135