Commit Graph

5362 Commits

Author SHA1 Message Date
Richard Smith 825e3bb580 PR46209: properly determine whether a copy assignment operator is
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.
2020-06-05 16:05:32 -07:00
Jonas Devlieghere df53f09056 Revert "PR46209: properly determine whether a copy assignment operator is"
This reverts commit c57f8a3a20.
2020-06-04 23:45:36 -07:00
Richard Smith c57f8a3a20 PR46209: properly determine whether a copy assignment operator is
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.
2020-06-04 19:19:01 -07:00
Bruno Ricci a2f32bfcc7
[clang][Sema] SequenceChecker: C++17 sequencing rule for call expressions.
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
2020-06-03 12:35:12 +01:00
Richard Smith b5f2c4e45b PR23029 / C++ DR2233: Allow expanded parameter packs to follow
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.
2020-06-02 13:48:59 -07:00
Fangrui Song 7096e04a68 [Sema] Use isAlwaysUninit for -Wuninitialized-const-reference after D79895 2020-06-02 11:25:04 -07:00
Zequan Wu 170b6869b5 [Clang] Add a new warning to warn when passing uninitialized variables as const reference parameters to a function
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
2020-06-02 10:21:02 -07:00
Florian Hahn 8f3f88d2f5 [Matrix] Implement matrix index expressions ([][]).
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
2020-06-01 20:08:49 +01:00
Florian Hahn 6f6e91d193 [Matrix] Implement + and - operators for MatrixType.
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
2020-05-29 20:42:22 +01:00
Richard Smith 0dfb43deb6 Fix handling of default arguments in __attribute__((enable_if)).
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.
2020-05-28 15:35:22 -07:00
Richard Smith 00e5d38d40 Do not warn that an expression of the form (void)arr; is unused when
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.
2020-05-27 17:26:29 -07:00
John Brawn 6c906f7785 [Sema] Diagnose more cases of static data members in local or unnamed classes
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
2020-05-26 13:29:59 +01:00
Alexey Bader e95ee300c0 [SYCL] Prohibit arithmetic operations for incompatible pointers
Summary:
This change enables OpenCL diagnostics for the pointers annotated with
address space attribute SYCL mode.

Move `isAddressSpaceOverlapping` method from PointerType to QualType.

Reviewers: Anastasia, rjmccall

Reviewed By: rjmccall

Subscribers: rjmccall, jeroen.dobbelaere, Fznamznon, yaxunl, ebevhan, cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D80317
2020-05-22 13:43:24 +03:00
Akira Hatanaka 854f5f332a [Sema] Teach -Wcast-align to compute an accurate alignment using the
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
2020-05-15 00:59:03 -07:00
Erich Keane 0c5db3e4aa Fix test from 5f1f4a5
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.
2020-05-14 08:22:08 -07:00
Erich Keane 5f1f4a5d01 Prohibit capture of _ExtInt in inline assembly.
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.
2020-05-14 07:21:09 -07:00
Akira Hatanaka 50a81ea2bc Don't apply lvalue-to-rvalue conversion in DefaultLValueConversion to
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
2020-05-13 20:12:10 -07:00
Ronald Wampler 4b53495c4b Perform ActOnConversionDeclarator after looking for any virtual functions it overrides
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
2020-05-13 10:34:19 -04:00
Florian Hahn ffcaed32ef [Matrix] Check non-dependent elt type before creating DepSizedMatrix.
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.
2020-05-12 16:46:37 +01:00
Florian Hahn 1065869195 [Matrix] Add matrix type to Clang.
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
2020-05-11 18:55:45 +01:00
Haojian Wu 507d1eb1ce Add a missing test file for recovery expressions.
The test was missed in 8222107aa9.
2020-05-11 09:23:32 +02:00
Richard Smith 8fc12b8698 Enforce the C++11 anonymous enum bitfields check even for
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.
2020-05-10 14:03:50 -07:00
Richard Smith d6425e2c14 Properly implement 'enum class' parsing.
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.
2020-05-10 13:21:04 -07:00
Richard Smith c90e198107 Fix parsing of enum-base to follow C++11 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.
2020-05-08 19:32:00 -07:00
Weverything 4ae537c222 Fix false positive with -Wnon-c-typedef-for-linkage
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
2020-05-07 19:20:08 -07:00
Richard Sandiford 69ab8b46b8 [Sema][SVE] Fix handling of initialisers for built-in SVE types
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
2020-05-06 12:24:27 +01:00
Haojian Wu c6e1fd70fb [clang] Fix a crash on invalid auto.
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
2020-05-06 11:47:03 +02:00
Erich Keane 9fbf9989a2 Reject operations between vectors and enum types.
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.
2020-05-04 13:11:24 -07:00
Erich Keane 5b862b6aa7 Fix ext-int Sema test that didn't specify a triple.
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.
2020-04-29 14:34:53 -07:00
Richard Smith 0a088ead85 Improve diagnostics for missing import / #include of module.
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.
2020-04-28 18:41:14 -07:00
Erik Pilkington 2bb686b4b6 [AST] Fix a crash on a dependent vector_size attribute
Looks like this was just a copy & paste mistake from
getDependentSizedExtVectorType. rdar://60092165

Differential revision: https://reviews.llvm.org/D79012
2020-04-28 12:54:49 -04:00
Aaron Puchert ce7eb72a3c Thread safety analysis: Reword warning after D72635
We allow arbitrary names for capabilities now, and the name didn't play
a role for this anyway.
2020-04-27 22:23:52 +02:00
Aaron Puchert f43859a099 PR45000: Let Sema::SubstParmVarDecl handle default args of lambdas in initializers
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
2020-04-22 22:37:21 +02:00
Haojian Wu 89d9912cbf [AST] dont invaliate VarDecl when the initializer contains errors.
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
2020-04-21 10:53:35 +02:00
Haojian Wu e90fb82f0f [AST] Suppress the spammy "attempt to use a deleted fucntion" diagnostic.
Summary:
This patch fixes the regression diagnostic, which was introduced in
https://reviews.llvm.org/D77395.

Reviewers: sammccall

Reviewed By: sammccall

Subscribers: rsmith, adamcz, cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D78100
2020-04-21 09:43:46 +02:00
Richard Smith 4b03dd7b84 PR45534: don't ignore unmodeled side-effects when constant-evaluating a call to __builtin_constant_p.
Such side-effects should result in the call evaluating to 'false', even
if we can still determine what value the argument expression will
evaluate to.
2020-04-20 21:23:35 -07:00
Erich Keane 5f0903e9be Reland Implement _ExtInt as an extended int type specifier.
I fixed the LLDB issue, so re-applying the patch.

This reverts commit a4b88c0449.
2020-04-17 10:45:48 -07:00
Sterling Augustine a4b88c0449 Revert "Implement _ExtInt as an extended int type specifier."
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()) {
2020-04-17 10:29:40 -07:00
Erich Keane 61ba1481e2 Implement _ExtInt as an extended int type specifier.
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
2020-04-17 07:10:57 -07:00
Aaron Ballman 2ec5520a54 Disallow [[nodiscard]] on a function pointer declaration.
This is not allowed by [dcl.attr.nodiscard]p1 for the standard attribute, but
is still supported for the [[clang::warn_unused_result]] spelling.
2020-04-16 09:28:49 -04:00
Richard Smith 57acbaece1 Improve diagnostic when constant-evaluating a std::initializer_list with
an unexpected form.
2020-04-15 13:28:24 -07:00
Richard Smith bab6df86ae Rework how UuidAttr, CXXUuidofExpr, and GUID template arguments and constants are represented.
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
2020-04-15 12:20:42 -07:00
Haojian Wu 17198dfaff [AST] Fix recovery-expr crash on invalid aligned attr.
Summary:
crash stack:

```
lang: tools/clang/include/clang/AST/AttrImpl.inc:1490: unsigned int clang::AlignedAttr::getAlignment(clang::ASTContext &) const: Assertion `!isAlignmentDependent()' failed.
PLEASE submit a bug report to https://bugs.llvm.org/ and include the crash backtrace, preprocessed source, and associated run script.
Stack dump:
0.      Program arguments: ./bin/clang -cc1 -std=c++1y -ast-dump -frecovery-ast -fcxx-exceptions /tmp/t4.cpp
1.      /tmp/t4.cpp:3:31: current parser token ';'
 #0 0x0000000002530cff llvm::sys::PrintStackTrace(llvm::raw_ostream&) llvm-project/llvm/lib/Support/Unix/Signals.inc:564:13
 #1 0x000000000252ee30 llvm::sys::RunSignalHandlers() llvm-project/llvm/lib/Support/Signals.cpp:69:18
 #2 0x000000000253126c SignalHandler(int) llvm-project/llvm/lib/Support/Unix/Signals.inc:396:3
 #3 0x00007f86964d0520 __restore_rt (/lib/x86_64-linux-gnu/libpthread.so.0+0x13520)
 #4 0x00007f8695f9ff61 raise /build/glibc-oCLvUT/glibc-2.29/signal/../sysdeps/unix/sysv/linux/raise.c:51:1
 #5 0x00007f8695f8b535 abort /build/glibc-oCLvUT/glibc-2.29/stdlib/abort.c:81:7
 #6 0x00007f8695f8b40f _nl_load_domain /build/glibc-oCLvUT/glibc-2.29/intl/loadmsgcat.c:1177:9
 #7 0x00007f8695f98b92 (/lib/x86_64-linux-gnu/libc.so.6+0x32b92)
 #8 0x0000000004503d9f llvm::APInt::getZExtValue() const llvm-project/llvm/include/llvm/ADT/APInt.h:1623:5
 #9 0x0000000004503d9f clang::AlignedAttr::getAlignment(clang::ASTContext&) const llvm-project/build/tools/clang/include/clang/AST/AttrImpl.inc:1492:0
```

Reviewers: sammccall

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D78085
2020-04-15 16:15:20 +02:00
Haojian Wu 9657385960 [AST] Dont invalide VarDecl even the default initializaiton is failed.
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
2020-04-14 12:58:48 +02:00
Reid Kleckner 55efb68c19 [MS] Mark vbase dtors used when marking dtor used
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
2020-04-09 14:19:36 -07:00
Haojian Wu 041080c247 [AST] Fix a crash on invalid constexpr Ctorinitializer when building RecoveryExpr.
Summary:
crash stack:

```

lang:  workspace/llvm-project/clang/lib/AST/ExprConstant.cpp:13704: bool EvaluateInPlace(clang::APValue &, (anonymous namespace)::EvalInfo &, const (anonymous namespace)::LValue &, const clang::Expr *, bool): Assertion `!E->isValueDependent()' failed.
 #8  EvaluateInPlace(clang::APValue&, (anonymous namespace)::EvalInfo&, (anonymous namespace)::LValue const&, clang::Expr const*, bool)  workspace/llvm-project/clang/lib/AST/ExprConstant.cpp:0:0
 #9  HandleConstructorCall(clang::Expr const*, (anonymous namespace)::LValue const&, clang::APValue*, clang::CXXConstructorDecl const*, (anonymous namespace)::EvalInfo&, clang::APValue&)  workspace/llvm-project/clang/lib/AST/ExprConstant.cpp:5779:57
#10  HandleConstructorCall(clang::Expr const*, (anonymous namespace)::LValue const&, llvm::ArrayRef<clang::Expr const*>, clang::CXXConstructorDecl const*, (anonymous namespace)::EvalInfo&, clang::APValue&)  workspace/llvm-project/clang/lib/AST/ExprConstant.cpp:5819:10
#11  clang::Expr::isPotentialConstantExpr(clang::FunctionDecl const*, llvm::SmallVectorImpl<std::pair<clang::SourceLocation, clang::PartialDiagnostic> >&) workspace/llvm-project/clang/lib/AST/ExprConstant.cpp:14746:5
#12  CheckConstexprFunctionBody(clang::Sema&, clang::FunctionDecl const*, clang::Stmt*, clang::Sema::CheckConstexprKind)  workspace/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp:2306:7
#13  clang::Sema::CheckConstexprFunctionDefinition(clang::FunctionDecl const*, clang::Sema::CheckConstexprKind)  workspace/llvm-project/clang/lib/Sema/SemaDeclCXX.cpp:1766:0
#14  clang::Sema::ActOnFinishFunctionBody(clang::Decl*, clang::Stmt*, bool)  workspace/llvm-project/clang/lib/Sema/SemaDecl.cpp:14357:9
#15  clang::Parser::ParseFunctionStatementBody(clang::Decl*, clang::Parser::ParseScope&)  workspace/llvm-project/clang/lib/Parse/ParseStmt.cpp:2213:18
```

Reviewers: sammccall

Reviewed By: sammccall

Subscribers: rsmith, cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D77041
2020-04-07 14:29:38 +02:00
Richard Smith c56975e299 Fix template instantiation of a non-dependent call to an inherited
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.
2020-04-06 19:20:30 -07:00
Richard Smith 944db8a433 Permit constant evaluation of mixed __builtin_memcmp between char and
char8_t.
2020-04-05 15:35:32 -07:00
Richard Smith 7f24db0175 Add documentation and testing for
2c88a485c7.

Also extend it to cover memchr for consistency.
2020-04-05 15:24:49 -07:00
Richard Smith 179f4baba0 Don't treat a CXXScopeSpec with a nested name specifier but no location
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.
2020-04-03 20:20:48 -07:00
Richard Smith 4ede887992 PR45402: Make the restrictions on constant evaluation of memcmp and
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.
2020-04-03 18:26:14 -07:00
Sam McCall 88fbadd0f5 [AST] clang::VectorType supports any size (that fits in unsigned)
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
2020-04-03 17:30:31 +02:00
Weverything f93aed66f2 Fix diagnostics where _Atomic can't be applied
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.
2020-03-31 17:23:35 -07:00
Eli Friedman 24485aec47 [clang analysis] Make mutex guard detection more reliable.
-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
2020-03-30 11:46:02 -07:00
Richard Smith 9a7eda1bec PR45350: Handle unsized array CXXConstructExprs in constant evaluation
of array new expressions with runtime bound.
2020-03-29 19:33:56 -07:00
Richard Smith a5458bb0d6 Don't claim template names that name non-templates are undeclared. 2020-03-29 13:15:30 -07:00
Joerg Sonnenberger 09d4021853 Fix compatibility for __builtin_stdarg_start
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.
2020-03-28 23:24:13 +01:00
Richard Smith 499b2a8d63 PR45294: Fix handling of assumed template names looked up in the lexical
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.
2020-03-27 21:07:06 -07:00
Richard Smith 88c7ffaf94 Form invalid template-id annotations when parsing a construct that is
required to be a template-id but names an undeclared identifier.
2020-03-27 20:27:42 -07:00
Richard Smith 0c42539df3 Improve error recovery from missing '>' in template argument list.
Produce the conventional "to match this '<'" note, so that the user
knows why we expected a '>', and properly handle '>>' in C++11 onwards.
2020-03-27 18:59:01 -07:00
Richard Smith b3f6e3d6d6 Improve recovery from invalid template-ids.
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.
2020-03-27 17:11:04 -07:00
Richard Sandiford c6824883cc [AST][SVE] Treat built-in SVE types as trivial
Built-in SVE types are trivial, since they're trivially copyable
and support default construction.

Differential Revision: https://reviews.llvm.org/D76692
2020-03-27 17:34:04 +00:00
Richard Sandiford 35392660e6 [AST][SVE] Treat built-in SVE types as trivially copyable
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
2020-03-27 17:32:55 +00:00
Richard Sandiford 9dcb20a7d0 [AST][SVE] Treat built-in SVE types as POD
Built-in SVE types are POD in much the same that scalars and
fixed-length vectors are.

Differential Revision: https://reviews.llvm.org/D76690
2020-03-27 17:04:07 +00:00
Haojian Wu 62dea6e9be Revert "[AST] Build recovery expressions by default for C++."
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);
2020-03-26 16:25:32 +01:00
Haojian Wu a9ab11d408 [AST] Build recovery expressions for nonexistent member exprs.
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
2020-03-26 08:50:33 +01:00
Erich Keane 044c51d8d4 Fix vector type scalar checking when the scalar operand is dependent
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.
2020-03-25 11:38:58 -07:00
Haojian Wu 0788acbccb [AST] Build recovery expressions by default for C++.
Update the existing tests.

Reviewers: sammccall

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D76696
2020-03-25 09:00:48 +01:00
Momchil Velikov 080d046c91 [ARM][CMSE] Implement CMSE attributes
This patch adds CMSE attributes `cmse_nonsecure_call` and
`cmse_nonsecure_entry`.  As usual, specification is available here:
https://developer.arm.com/docs/ecm0359818/latest

Patch by Javed Absar, Bradley Smith, David Green, Momchil Velikov,
possibly others.

Differential Revision: https://reviews.llvm.org/D71129
2020-03-24 10:21:26 +00:00
Richard Smith 502915c619 PR45142: 'template ~X<T>' is ill-formed; reject it rather than crashing. 2020-03-23 15:07:06 -07:00
Tyker 180581cfcf [clang] Add support for consteval constructors
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
2020-03-20 11:33:54 +01:00
Richard Smith e7a811b319 PR45133: Don't crash if the active member of a union changes while it's
in the process of being initialized.
2020-03-17 20:37:14 -07:00
Richard Sandiford 4ece6f051b [Sema][SVE] Reject "delete" with sizeless types
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
2020-03-17 12:45:00 +00:00
Richard Sandiford 506406c4d5 [Sema][SVE] Reject "new" with sizeless types
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
2020-03-17 12:23:46 +00:00
Richard Sandiford 72ffb16b4c [Sema][SVE] Don't allow sizeless types to be caught
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
2020-03-17 12:00:16 +00:00
Richard Sandiford c47f971694 [Sema][SVE] Don't allow sizeless objects to be thrown
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
2020-03-17 11:52:37 +00:00
Richard Sandiford 0947296902 [Sema][SVE] Reject sizeless types in exception specs
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
2020-03-17 11:39:03 +00:00
Richard Sandiford 94489f35a7 [Sema][SVE] Reject arithmetic on pointers to sizeless types
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
2020-03-17 11:35:20 +00:00
Richard Sandiford 010005f077 [Sema][SVE] Reject subscripts on pointers to sizeless types
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
2020-03-17 11:24:57 +00:00
Saar Raz 19fccc52ff [Concepts] Fix incorrect control flow when TryAnnotateTypeConstraint annotates an invalid template-id
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).
2020-03-17 01:49:42 +02:00
Aaron Ballman dab43c8592 Remove some explicit calls to getName() when printing diagnostics; NFC 2020-03-14 17:01:45 -04:00
Richard Smith 810794ce88 PR44992 Don't crash when a defaulted <=> is in a class declared in a
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.)
2020-03-13 19:30:49 -07:00
Richard Sandiford 994c071a1b [Sema][SVE] Reject arrays of sizeless types
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
2020-03-13 19:28:45 +00:00
Richard Sandiford 8c5c60a493 [Sema][SVE] Reject by-copy capture of sizeless types
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
2020-03-13 19:27:31 +00:00
Richard Sandiford b50d80c1ee [Sema][SVE] Don't allow fields to have sizeless type
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
2020-03-13 19:22:23 +00:00
Richard Smith 9975dc38bf Defer checking for mismatches between the deletedness of and overriding
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.
2020-03-12 13:07:22 -07:00
Richard Sandiford f8700db7f1 [Sema][SVE] Don't allow static or thread-local variables to have sizeless type
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
2020-03-12 17:39:29 +00:00
Richard Sandiford adb290d974 [Sema][SVE] Reject atomic sizeless types
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
2020-03-12 17:20:23 +00:00
Richard Sandiford 627b5c1206 [Sema][SVE] Reject aligned/_Alignas for sizeless types
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
2020-03-12 17:12:40 +00:00
Richard Sandiford 39969c7d3a [Sema][SVE] Reject sizeof and alignof for sizeless types
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
2020-03-12 17:06:53 +00:00
Richard Sandiford f09c7d642a [Sema][SVE] Add tests for valid and invalid type usage
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
2020-03-12 16:56:13 +00:00
Richard Smith 4cba668ac1 Fix crash-on-invalid when trying to recover from a function template
being deleted on its second or subsequent declaration.
2020-03-10 16:34:27 -07:00
Richard Smith 6d894afdea PR45124: Don't leave behind pending cleanups when declaring implicit
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.
2020-03-06 13:22:10 -08:00
Aaron Puchert 33bb32bbc6 [Sema] Reword -Wrange-loop-analysis warning messages
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
2020-03-06 14:57:01 +01:00
Arthur Eubanks cfff4851ac Add warnings for casting ptr -> smaller int for C++ in Microsoft mode
Adds warnings to groups recently added in https://reviews.llvm.org/D72231.

Reviewed By: rnk

Differential Revision: https://reviews.llvm.org/D75708
2020-03-05 15:17:06 -08:00
Richard Smith ad18665e37 PR45087: Fix check for emptiness when determining whether a trivial copy
operation needs to read from its operand.
2020-03-03 15:57:48 -08:00
Richard Smith 98ed0c5475 PR44978: Accept as an extension some cases where destructor name lookup
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.
2020-02-26 14:55:31 -08:00
Tyker ca50f09db9 [clang] fix error detection in consteval calls
Summary:
code like:
```
consteval int f() {
  int *A = new int(0);
  return *A;
}

int i1 = f();
```
currently doesn't generate any error.

Reviewers: rsmith

Reviewed By: rsmith

Differential Revision: https://reviews.llvm.org/D74418
2020-02-26 21:09:31 +01:00
Hans Wennborg 41a6612ea8 Put microsoft template parameter shadow warning behind separate flag (PR44794)
Differential revision: https://reviews.llvm.org/D75121
2020-02-26 16:04:40 +01:00
Roman Lebedev 3dd5a298bf
[clang] Annotating C++'s `operator new` with more attributes
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
2020-02-26 01:37:17 +03:00
Roman Lebedev b8fdafe68c
[Sema] Perform call checking when building CXXNewExpr
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
2020-02-26 01:36:44 +03:00
Anastasia Stulova fa755d3e71 [Sema][C++] Propagate conversion kind to specialize the diagnostics
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
2020-02-25 16:05:37 +00:00
Mark de Wever 56eb15a1c7 [Sema] Fix pointer-to-int-cast diagnostic for _Bool
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
2020-02-22 19:39:49 +01:00
Roman Lebedev 9ea5d17cc9
[Sema] Demote call-site-based 'alignment is a power of two' check for AllocAlignAttr into a warning
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
2020-02-20 16:39:26 +03:00
Richard Smith 061f3a50dd P0593R6: Pseudo-destructor expressions end object lifetimes.
This only has an observable effect on constant evaluation.
2020-02-18 18:41:03 -08:00
Richard Smith 24ad121582 Add -std=c++20 flag, replace C++2a with C++20 throughout the Clang
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.
2020-02-18 16:16:37 -08:00
Richard Smith e28d9bae4b PR44958: Allow member calls and typeid / dynamic_cast on mutable objects
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.)
2020-02-18 14:57:13 -08:00
Richard Smith 9ce6dc9872 CWG1423: don't permit implicit conversion of nullptr_t to bool.
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).
2020-02-11 06:52:45 -08:00
Richard Smith 76f888d0a5 Fix handling of destructor names that name typedefs.
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.
2020-02-10 02:21:01 -08:00
Richard Smith 0e3a487784 PR12350: Handle remaining cases permitted by CWG DR 244.
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.
2020-02-07 18:40:41 -08:00
Richard Smith 7ae1b4a0ce Implement P1766R1: diagnose giving non-C-compatible classes a typedef name for linkage purposes.
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
2020-02-07 11:47:37 -08:00
Richard Smith 96c899449b C++ DR2026: static storage duration variables are not zeroed before
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.
2020-02-06 16:37:22 -08:00
Richard Smith b96c6b65b9 PR44786: Don't assert when profiling <=> expressions. 2020-02-04 18:30:17 -08:00
Tyker f5d1a9f1cf Try to fix windows build bot after 008e7bf923 2020-02-04 21:20:16 +01:00
Tyker 008e7bf923 [C++20] Add consteval-specific semantic for functions
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
2020-02-04 20:38:32 +01:00
Fangrui Song dbc96b518b Revert "[CodeGenModule] Assume dso_local for -fpic -fno-semantic-interposition"
This reverts commit 789a46f2d7.

Accidentally committed.
2020-02-03 10:09:39 -08:00
Fangrui Song 789a46f2d7 [CodeGenModule] Assume dso_local for -fpic -fno-semantic-interposition
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
2020-02-03 09:52:48 -08:00
Mark de Wever c03349e40f [Sema] Remove a -Wrange warning from -Wall
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
2020-02-01 18:44:27 +01:00
Aaron Puchert 27684ae66d Don't warn about missing declarations for partial template specializations
Summary: Just like templates, they are excepted from the ODR rule.

Reviewed By: aaron.ballman, rsmith

Differential Revision: https://reviews.llvm.org/D68923
2020-02-01 00:06:03 +01:00
Richard Smith 04f131da0b DR1753: Don't permit x.NS::~T() as a pseudo-destructor name.
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.
2020-01-24 18:53:50 -08:00
Roman Lebedev ba545c814b
[Sema] Try 2: Attempt to perform call-size-specific `__attribute__((alloc_align(param_idx)))` validation
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
2020-01-24 14:42:45 +03:00
Roman Lebedev 00756b1823
Revert "[Sema] Attempt to perform call-size-specific `__attribute__((alloc_align(param_idx)))` validation"
Likely makes bots angry.

This reverts commit c2a9061ac5.
2020-01-23 23:10:34 +03:00
Roman Lebedev b749af6a1f
[Sema] Don't disallow placing `__attribute__((alloc_align(param_idx)))` on `std::align_val_t`-typed parameters
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
2020-01-23 22:50:50 +03:00
Roman Lebedev c2a9061ac5
[Sema] Attempt to perform call-size-specific `__attribute__((alloc_align(param_idx)))` validation
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
2020-01-23 22:50:49 +03:00
Saar Raz b481f02814 [Concepts] Placeholder constraints and abbreviated templates
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
2020-01-23 19:39:43 +02:00
Sam McCall 5c02fe1faa Revert "[Concepts] Placeholder constraints and abbreviated templates"
This reverts commit e57a9abc4b.

Parser/cxx2a-placeholder-type-constraint.cpp has MSan failures.

Present at 7b81c3f8793d30a4285095a9b67dcfca2117916c:
http://lab.llvm.org:8011/builders/sanitizer-x86_64-linux-bootstrap-msan/builds/17133/steps/check-clang%20msan/logs/stdio
not present at eaa594f4ec54eba52b03fd9f1c789b214c66a753:
http://lab.llvm.org:8011/builders/sanitizer-x86_64-linux-bootstrap-msan/builds/17132/steps/check-clang%20msan/logs/stdio

Stack trace:
```
==57032==WARNING: MemorySanitizer: use-of-uninitialized-value
    #0 0xccfe016 in clang::AutoTypeLoc::getLocalSourceRange() const /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/include/clang/AST/TypeLoc.h:2036:19
    #1 0xcc56758 in CheckDeducedPlaceholderConstraints(clang::Sema&, clang::AutoType const&, clang::AutoTypeLoc, clang::QualType) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Sema/SemaTemplateDeduction.cpp:4505:56
    #2 0xcc550ce in clang::Sema::DeduceAutoType(clang::TypeLoc, clang::Expr*&, clang::QualType&, llvm::Optional<unsigned int>, bool) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Sema/SemaTemplateDeduction.cpp:4707:11
    #3 0xcc52407 in clang::Sema::DeduceAutoType(clang::TypeSourceInfo*, clang::Expr*&, clang::QualType&, llvm::Optional<unsigned int>, bool) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Sema/SemaTemplateDeduction.cpp:4457:10
    #4 0xba38332 in clang::Sema::deduceVarTypeFromInitializer(clang::VarDecl*, clang::DeclarationName, clang::QualType, clang::TypeSourceInfo*, clang::SourceRange, bool, clang::Expr*) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Sema/SemaDecl.cpp:11351:7
    #5 0xba3a8a9 in clang::Sema::DeduceVariableDeclarationType(clang::VarDecl*, bool, clang::Expr*) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Sema/SemaDecl.cpp:11385:26
    #6 0xba3c520 in clang::Sema::AddInitializerToDecl(clang::Decl*, clang::Expr*, bool) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Sema/SemaDecl.cpp:11725:9
    #7 0xb39c498 in clang::Parser::ParseDeclarationAfterDeclaratorAndAttributes(clang::Declarator&, clang::Parser::ParsedTemplateInfo const&, clang::Parser::ForRangeInit*) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Parse/ParseDecl.cpp:2399:17
    #8 0xb394d80 in clang::Parser::ParseDeclGroup(clang::ParsingDeclSpec&, clang::DeclaratorContext, clang::SourceLocation*, clang::Parser::ForRangeInit*) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Parse/ParseDecl.cpp:2128:21
    #9 0xb383bbf in clang::Parser::ParseSimpleDeclaration(clang::DeclaratorContext, clang::SourceLocation&, clang::Parser::ParsedAttributesWithRange&, bool, clang::Parser::ForRangeInit*, clang::SourceLocation*) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Parse/ParseDecl.cpp:1848:10
    #10 0xb383129 in clang::Parser::ParseDeclaration(clang::DeclaratorContext, clang::SourceLocation&, clang::Parser::ParsedAttributesWithRange&, clang::SourceLocation*) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/llvm/include/llvm/ADT/PointerUnion.h
    #11 0xb53a388 in clang::Parser::ParseStatementOrDeclarationAfterAttributes(llvm::SmallVector<clang::Stmt*, 32u>&, clang::Parser::ParsedStmtContext, clang::SourceLocation*, clang::Parser::ParsedAttributesWithRange&) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Parse/ParseStmt.cpp:221:13
    #12 0xb539309 in clang::Parser::ParseStatementOrDeclaration(llvm::SmallVector<clang::Stmt*, 32u>&, clang::Parser::ParsedStmtContext, clang::SourceLocation*) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Parse/ParseStmt.cpp:106:20
    #13 0xb55610e in clang::Parser::ParseCompoundStatementBody(bool) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Parse/ParseStmt.cpp:1079:11
    #14 0xb559529 in clang::Parser::ParseFunctionStatementBody(clang::Decl*, clang::Parser::ParseScope&) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Parse/ParseStmt.cpp:2204:21
    #15 0xb33c13e in clang::Parser::ParseFunctionDefinition(clang::ParsingDeclarator&, clang::Parser::ParsedTemplateInfo const&, clang::Parser::LateParsedAttrList*) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Parse/Parser.cpp:1339:10
    #16 0xb394703 in clang::Parser::ParseDeclGroup(clang::ParsingDeclSpec&, clang::DeclaratorContext, clang::SourceLocation*, clang::Parser::ForRangeInit*) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Parse/ParseDecl.cpp:2068:11
    #17 0xb338e52 in clang::Parser::ParseDeclOrFunctionDefInternal(clang::Parser::ParsedAttributesWithRange&, clang::ParsingDeclSpec&, clang::AccessSpecifier) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Parse/Parser.cpp:1099:10
    #18 0xb337674 in clang::Parser::ParseDeclarationOrFunctionDefinition(clang::Parser::ParsedAttributesWithRange&, clang::ParsingDeclSpec*, clang::AccessSpecifier) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Parse/Parser.cpp:1115:12
    #19 0xb334a96 in clang::Parser::ParseExternalDeclaration(clang::Parser::ParsedAttributesWithRange&, clang::ParsingDeclSpec*) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Parse/Parser.cpp:935:12
    #20 0xb32f12a in clang::Parser::ParseTopLevelDecl(clang::OpaquePtr<clang::DeclGroupRef>&, bool) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Parse/Parser.cpp:686:12
    #21 0xb31e193 in clang::ParseAST(clang::Sema&, bool, bool) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Parse/ParseAST.cpp:158:20
    #22 0x80263f0 in clang::FrontendAction::Execute() /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Frontend/FrontendAction.cpp:936:8
    #23 0x7f2a257 in clang::CompilerInstance::ExecuteAction(clang::FrontendAction&) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/Frontend/CompilerInstance.cpp:965:33
    #24 0x8288bef in clang::ExecuteCompilerInvocation(clang::CompilerInstance*) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/lib/FrontendTool/ExecuteCompilerInvocation.cpp:290:25
    #25 0xad44c2 in cc1_main(llvm::ArrayRef<char const*>, char const*, void*) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/tools/driver/cc1_main.cpp:239:15
    #26 0xacd76a in ExecuteCC1Tool(llvm::ArrayRef<char const*>) /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/tools/driver/driver.cpp:325:12
    #27 0xacc9fd in main /b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm-project/clang/tools/driver/driver.cpp:398:12
    #28 0x7f7d82cdb2e0 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x202e0)
    #29 0xa4dde9 in _start (/b/sanitizer-x86_64-linux-bootstrap-msan/build/llvm_build_msan/bin/clang-11+0xa4dde9)
```
2020-01-23 10:38:59 +01:00
Saar Raz e57a9abc4b [Concepts] Placeholder constraints and abbreviated templates
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
2020-01-22 12:09:13 +02:00
Jonas Devlieghere 62e4b501ab Revert "[Concepts] Placeholder constraints and abbreviated templates"
This temporarily reverts commit e03ead6771
because it breaks LLDB.

http://lab.llvm.org:8011/builders/lldb-x86_64-debian/builds/3356
http://lab.llvm.org:8011/builders/lldb-x64-windows-ninja/builds/12872
http://green.lab.llvm.org/green/view/LLDB/job/lldb-cmake/6407/
2020-01-21 19:03:52 -08:00
Saar Raz e03ead6771 [Concepts] Placeholder constraints and abbreviated templates
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
2020-01-22 02:03:05 +02:00
Mark de Wever 41fcd17250 [Sema] Avoid Wrange-loop-analysis false positives
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
2020-01-21 21:14:10 +01:00
Richard Smith 45d70806f4 PR42694 Support explicit(bool) in older language modes as an extension.
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.
2020-01-15 18:38:23 -08:00
Amy Huang 44560762c6 Revert "Further implement CWG 2292"
This reverts commit ee0f1f1edc because it
causes an error on valid code.
See https://reviews.llvm.org/rGee0f1f1edc3ec0d4e698d50cc3180217448802b7.
2020-01-15 15:46:07 -08:00
Soumi Manna ee0f1f1edc Further implement CWG 2292
The core issue is that simple-template-id is ambiguous between class-name
and type-name. This fixes PR43966.
2020-01-15 08:49:44 -05:00
Erich Keane f0719bf219 PR44514: Fix recovery from noexcept with non-convertible expressions
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
2020-01-13 13:51:48 -08:00
Erich Keane 349636d2bf Implement VectorType conditional operator GNU extension.
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
2020-01-13 13:27:20 -08:00
Mark de Wever 9c74fb402e [Sema] Improve -Wrange-loop-analysis warnings.
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
2020-01-11 15:34:02 +01:00
Richard Smith f041e9ad70 CWG2352: Allow qualification conversions during reference binding.
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.
2020-01-09 18:24:06 -08:00
Richard Smith 2519554134 When diagnosing the lack of a viable conversion function, also list
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.
2020-01-09 15:15:02 -08:00
Alex Richardson 8c387cbea7 Add builtins for aligning and checking alignment of pointers and integers
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
2020-01-09 21:48:29 +00:00
Gabor Horvath 247a603254 [LifetimeAnalysis] Do not forbid void deref type in gsl::Pointer/gsl::Owner annotations
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
2020-01-07 08:32:40 -08:00
Mark de Wever eec0240f97 Adds -Wrange-loop-analysis to -Wall
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.
2020-01-06 17:37:47 +01:00
Mark de Wever 8ca79dac55 Revert "Adds -Wrange-loop-analysis to -Wall"
The sanitizer-x86_64-linux buildbot failed to build lld with -Werror.

This reverts commit d8117542ac.
2020-01-01 22:19:18 +01:00
Mark de Wever d8117542ac Adds -Wrange-loop-analysis to -Wall
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
2020-01-01 20:02:42 +01:00
Mark de Wever e5ab1e49f9 Improve Wrange-loop-analyses for rvalue reference
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
2020-01-01 20:02:18 +01:00
Mark de Wever f022a5a792 Adds fixit hints to the -Wrange-loop-analysis
Differential Revision: https://reviews.llvm.org/D68913
2020-01-01 20:02:00 +01:00
Zachary Henkel 0acfc49317 Allow redeclaration of __declspec(uuid)
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
2019-12-28 13:13:46 -08:00
Bruno Ricci 7394c15178
[Sema] SequenceChecker: C++17 sequencing rules for built-in operators <<, >>, .*, ->*, =, op=
Implement the C++17 sequencing rules for the built-in operators <<, >>, .*,
 ->*, = and op=.

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

Reviewed By: rsmith
2019-12-22 12:41:14 +00:00
Bruno Ricci 8a571538df
[Sema] SequenceChecker: Fix handling of operator ||, && and ?:
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
2019-12-22 12:27:31 +00:00
Richard Smith eea8ba097c Check whether the destination is a complete type in a static_cast (or
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.
2019-12-16 18:33:35 -08:00
Richard Smith f495de43bd [c++20] P1959R0: Remove support for std::*_equality. 2019-12-16 17:49:45 -08:00
Richard Smith 4e9f1379b9 If constant evaluation fails due to an unspecified pointer comparison,
produce a note saying that rather than the default "evaluation failed"
note.
2019-12-16 17:49:45 -08:00
Richard Smith 4b00299958 [c++20] Add deprecation warnings for the expression forms deprecated by P1120R0.
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).
2019-12-16 17:49:45 -08:00
Brian Gesiak 376cf43729 [coroutines][PR41909] Generalize fix from D62550
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
2019-12-16 17:43:04 -05:00
Richard Smith fbf60b7dbe Properly compute whether statement expressions can throw, rather than
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.
2019-12-15 22:02:31 -08:00
Richard Smith c5b890e922 PR44268: Fix crash if __builtin_object_size is applied to a heap
allocation.
2019-12-13 18:41:54 -08:00
Richard Smith 38c3b5d562 [c++20] Improve phrasing of diagnostic for missing #include <compare>. 2019-12-13 18:41:54 -08:00
Anastasia Stulova ed8dadb37c [Sema] Improve diagnostic about addr spaces for overload candidates
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
2019-12-13 12:35:18 +00:00
Erich Keane 654c0daef7 Suppress -Wwarn-unused-variables when we don't know the constructor
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.
2019-12-12 11:34:17 -08:00
Richard Smith db4c7adfa3 Suppress false-positive -Wuninitialized warnings in the constructor of a
templated but non-template class.
2019-12-11 14:26:28 -08:00
Richard Smith 56bba012d9 [c++20] Fix incorrect assumptions in checks for comparison category types.
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.
2019-12-09 12:18:33 -08:00
Richard Smith dbd1129724 Stop checking whether std::strong_* has ::equivalent members.
Any attempt to use these would be a bug, so we shouldn't even look for
them.
2019-12-06 11:35:41 -08:00
Richard Smith 759909506c Fix crash if a user-defined conversion is applied in the middle of a
rewrite of an operator in terms of operator<=>.
2019-12-05 18:44:15 -08:00
Richard Smith b220662a45 Properly convert all declaration non-type template arguments when
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.
2019-12-05 14:32:36 -08:00
David L. Jones 93cc9dddd8 Revert "Properly convert all declaration non-type template arguments when"
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
(*)()')").
2019-12-04 22:12:15 -08:00
Richard Smith 11d1052785 Properly convert all declaration non-type template arguments when
forming non-type template parameter values.
2019-12-04 18:55:24 -08:00
James Y Knight 90fce46fa6 Fix crash-on-invalid-code in lambda constant evaluation.
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.
2019-12-04 15:12:17 -05:00
Elizabeth Andrews 878a24ee24 Reapply "Fix crash on switch conditions of non-integer types in templates"
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.
2019-12-03 15:27:19 -08:00
Dávid Bolvanský 549ff601f0 Try to reenable -Wdeprecated-copy under -Wextra 2019-11-27 22:36:51 +01:00
Dávid Bolvanský 4eacc32672 Partially reland "[Diagnostics] Put "deprecated copy" warnings into -Wdeprecated-copy""
But do not enable it under -Wextra until libcxx issue is solved.
2019-11-26 14:41:34 +01:00
Tom Stellard 3c5142597a Revert "[Diagnostic] add a warning which warns about misleading indentation"
This reverts commit 7b86188b50.

This commit introduced bot falures for multi-stage bots with -Werror.
2019-11-25 13:19:57 -08:00
Tom Stellard 0e12815566 Revert "[Diagnostics] Put "deprecated copy" warnings into -Wdeprecated-copy"
This reverts commit 9353c5dd06.

This commit introduced bot falures for multi-stage bots with -Werror.
2019-11-25 13:19:57 -08:00
Tyker 7b86188b50 [Diagnostic] add a warning which warns about misleading indentation
Summary: Add a warning for misleading indentation similar to GCC's -Wmisleading-indentation

Reviewers: aaron.ballman, xbolva00

Reviewed By: aaron.ballman, xbolva00

Subscribers: arphaman, Ka-Ka, thakis

Differential Revision: https://reviews.llvm.org/D70638
2019-11-25 20:46:32 +01:00
Dávid Bolvanský 9e260c12bc [Diagnostics] Make behaviour of Clang's -Wdeprecated-copy same as in GCC
Do not warn for  functions that are explicitly marked delete or default, which follows the behavior of the GCC warning.
2019-11-23 23:57:17 +01:00
Dávid Bolvanský 9353c5dd06 [Diagnostics] Put "deprecated copy" warnings into -Wdeprecated-copy
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
2019-11-22 22:37:19 +01:00
Brian Gesiak 0b3d1d1348 [coroutines] Remove assert on CoroutineParameterMoves in Sema::buildCoroutineParameterMoves
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)!
2019-11-22 11:39:13 -05:00
Weverything 9740f9f0b6 Add -Wtautological-compare to -Wall
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
2019-11-12 14:36:57 -08:00
Dávid Bolvanský 1da13237a4 [Diagnostics] Try to improve warning message for -Wreturn-type
Summary: I agree with https://easyaspi314.github.io/gcc-vs-clang.html?fbclid=IwAR1VA0qxiWVUusOQUv5z7JESS7ZpeJy-UqAI5mnJscofGLqXcqeErIUB2gU, current warning message is not very good. We should try to improve it..

Reviewers: rsmith, aaron.ballman, easyaspi314

Reviewed By: aaron.ballman

Subscribers: arphaman, Quuxplusone, mehdi_amini, hiraditya, cfe-commits, llvm-commits

Tags: #clang, #llvm

Differential Revision: https://reviews.llvm.org/D69762
2019-11-09 17:54:58 +01:00
Melanie Blower d0b3e73175 Revert "Reapply "Fix crash on switch conditions of non-integer types in templates""
This reverts commit 759948467e.
There were build bot failures in clang-tidy
2019-11-08 14:18:15 -08:00
Melanie Blower 759948467e Reapply "Fix crash on switch conditions of non-integer types in templates"
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
2019-11-08 10:17:06 -08:00
Reid Kleckner 7177ce978e [SEH] Defer checking filter expression types until instantiaton
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
2019-11-07 14:52:04 -08:00
Edward Jones 90ecfa2f5f Revert "[Sema] Suppress -Wchar-subscripts if the index is a literal char"
This reverts commit 7adab7719e.
2019-11-07 18:45:40 +00:00
Edward Jones 7adab7719e [Sema] Suppress -Wchar-subscripts if the index is a literal char
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
2019-11-07 15:45:44 +00:00
Dávid Bolvanský 55507110b9 [Diagnostics] Improve some error messages related to bad use of dynamic_cast 2019-11-04 16:26:43 +01:00
Dávid Bolvanský b06305e449 [Diagnostics] Warn for std::is_constant_evaluated in constexpr mode
Summary:
constexpr int fn1() {
  if constexpr (std::is_constant_evaluated()) // condition is always true!
    return 0;
  else
    return 1;
}

constexpr int fn2() {
  if (std::is_constant_evaluated())
    return 0;
  else
    return 1;
}

Solves PR42977

Reviewers: rsmith, aaron.ballman

Reviewed By: rsmith

Subscribers: cfe-commits

Tags: #clang

Differential Revision: https://reviews.llvm.org/D69518
2019-10-31 10:03:11 +01:00
Richard Smith bb06149131 Fix __attribute__((enable_if)) to treat arguments with side-effects as
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.
2019-10-30 13:39:29 -07:00
Aaron Puchert ae3159e497 Thread safety analysis: Peel away NoOp implicit casts in initializers
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
2019-10-30 00:37:32 +01:00
Richard Smith eb535d2341 Accept __is_same_as as a GCC-compatibility synonym for the proper trait name __is_same. 2019-10-29 14:44:38 -07:00
Richard Smith 52590319a2 Fix argument numbering confusion when diagnosing a non-viable operator().
This could lead to crashes if operator() is a variadic template, as we
could end up asking for an out-of-bounds argument.
2019-10-29 13:08:39 -07:00
Richard Smith 39eef2cbb6 PR43775: don't produce a bogus 'auto' -Wc++98-compat warning for CTAD 2019-10-27 21:42:58 -07:00
Richard Smith faee39baa8 PR43762: when implicitly changing the active union member for an
assignment during constant evaluation, only start the lifetime of
trivially-default-constructible union members.
2019-10-27 12:31:16 -07:00
Richard Smith 70f59b5bbc When diagnosing an ambiguity, only note the candidates that contribute
to the ambiguity, rather than noting all viable candidates.
2019-10-24 14:58:29 -07:00
Richard Smith d052a578de [c++2a] Allow comparison functions to be explicitly defaulted.
This adds some initial syntactic checking that only the appropriate
function signatures can be defaulted. No implicit definitions are
generated yet.
2019-10-22 18:16:17 -07:00
Richard Trieu 8b0d14a8f0 New tautological warning for bitwise-or with non-zero constant always true.
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
2019-10-19 00:57:23 +00:00
Richard Smith 974c8b7e2f [c++20] Add rewriting from comparison operators to <=> / ==.
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
2019-10-19 00:04:43 +00:00
Richard Smith 61dadfc894 PR43674: fix incorrect constant evaluation of 'switch' where no case
label corresponds to the condition.

llvm-svn: 374954
2019-10-15 22:23:11 +00:00
Richard Smith 7e8fe67f0e PR43080: Do not build context-sensitive expressions during name classification.
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
2019-10-14 21:53:03 +00:00
Richard Smith 1e3a8d12a1 Suppress false-positive -Wdeprecated-volatile warning from __is_*_assignable(volatile T&, U).
llvm-svn: 374580
2019-10-11 17:59:09 +00:00
Richard Smith e381f33651 PR43629: Fix crash evaluating constexpr placement new on a subobject of
an out-of-lifetime object.

llvm-svn: 374465
2019-10-10 22:31:17 +00:00
Gauthier Harnisch 59c6df9b2c [clang] prevent crash for nonnull attribut in constant context (Bug 43601)
Summary:

bug : https://bugs.llvm.org/show_bug.cgi?id=43601

Reviewers: rnk

Reviewed By: rnk

Subscribers: cfe-commits

Tags: #clang

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

llvm-svn: 374285
2019-10-10 07:13:20 +00:00
Richard Smith 4a6861a7e5 [c++20] P1152R4: warn on any simple-assignment to a volatile lvalue
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
2019-10-09 02:04:54 +00:00