3348 Commits

Author SHA1 Message Date
Yeoul Na
3eb9ff3095
Turn 'counted_by' into a type attribute and parse it into 'CountAttributedType' (#78000)
In `-fbounds-safety`, bounds annotations are considered type attributes
rather than declaration attributes. Constructing them as type attributes
allows us to extend the attribute to apply nested pointers, which is
essential to annotate functions that involve out parameters: `void
foo(int *__counted_by(*out_count) *out_buf, int *out_count)`.

We introduce a new sugar type to support bounds annotated types,
`CountAttributedType`. In order to maintain extra data (the bounds
expression and the dependent declaration information) that is not
trackable in `AttributedType` we create a new type dedicate to this
functionality.

This patch also extends the parsing logic to parse the `counted_by`
argument as an expression, which will allow us to extend the model to
support arguments beyond an identifier, e.g., `__counted_by(n + m)` in
the future as specified by `-fbounds-safety`.

This also adjusts `__bdos` and array-bounds sanitizer code that already
uses `CountedByAttr` to check `CountAttributedType` instead to get the
field referred to by the attribute.
2024-03-20 13:36:56 +09:00
Zahira Ammarguellat
6503b015d4
[clang-cl] Fix value of __FUNCTION__ in MSVC mode. (#84014)
Predefined macro FUNCTION in clang is not returning the same string than
MS for templated functions.

See https://godbolt.org/z/q3EKn5zq4

For the same test case MSVC is returning:

function: TestClass::TestClass
function: TestStruct::TestStruct
function: TestEnum::TestEnum

The initial work for this was in the reverted patch
(https://github.com/llvm/llvm-project/pull/66120). This patch solves the
issues raised in the reverted patch.
2024-03-19 07:55:49 -07:00
Sirraide
69afb9d787
[Clang] [Sema] Fix bug in _Complex float+int arithmetic (#83063)
C23 6.3.1.8 ‘Usual arithmetic conversions’ p1 states (emphasis mine): 
> Otherwise, if the corresponding real type of either operand is
`float`, the other operand is converted, *without change of type
domain*, to a type whose corresponding real type is `float`.

‘type domain’ here refers to `_Complex` vs real (i.e. non-`_Complex`);
there is another clause that states the same for `double`.

Consider the following code:
```c++
_Complex float f;
int x;
f / x;
```

After talking this over with @AaronBallman, we came to the conclusion
that `x` should be converted to `float` and *not* `_Complex float` (that
is, we should perform a division of `_Complex float / float`, and *not*
`_Complex float / _Complex float`; the same also applies to `-+*`). This
was already being done correctly for cases where `x` was already a
`float`; it’s just mixed `_Complex float`+`int` operations that
currently suffer from this problem.

This pr removes the extra `FloatingRealToComplex` conversion that we
were erroneously inserting and adds some tests to make sure we’re
actually doing `_Complex float / float` and not `_Complex float /
_Complex float` (and analogously for `double` and `-+*`).

The only exception here is `float / _Complex float`, which calls a
library function (`__divsc3`) that takes 4 `float`s, so we end up having
to convert the `float` to a `_Complex float` after all (and analogously
for `double`); I don’t believe there is a way around this.

Lastly, we were also missing tests for `_Complex` arithmetic at compile
time, so this adds some tests for that as well.
2024-03-13 17:39:23 +01:00
Yaxun (Sam) Liu
b46f980454
[HIP] fix host-used external kernel (#83870)
In -fgpu-rdc mode, when an external kernel is used by a host function
with weak_odr linkage (e.g. explicitly instantiated template function),
the kernel should not be marked as host-used external kernel, since the
host function may be dropped by the linker. Mark the external kernel as
host-used external kernel will force a reference to the external kernel,
which the user may not define in other TU.

Fixes: https://github.com/llvm/llvm-project/issues/83771
2024-03-08 10:50:38 -05:00
cor3ntin
d773c00e52
[Clang] Fix looking for immediate calls in default arguments. (#80690)
Due to improper use of RecursiveASTVisitor.

Fixes #80630
2024-03-05 10:04:45 +01:00
Jan Svoboda
ecd7fce0d4 [clang][sema] NFC: Stylistic changes 2024-03-01 16:53:11 -08:00
Kupa-Martin
8c2ae42b3e
[Clang][Sema] Fix missing warning when comparing mismatched enums in … (#81418)
…C mode

Factored logic from `CheckImplicitConversion` into new methods
`Expr::getEnumConstantDecl` and `Expr::getEnumCoercedType` for use in
`checkEnumArithmeticConversions`.

Fix #29217
2024-02-27 06:58:59 -08:00
Krystian Stasiowski
ce4740d3e3
[Clang][Sema] Fix crash when MS dependent base class lookup occurs in an incomplete context (#83024)
When compiling the following with `-fms-compatibility`:
```
template<typename T> struct C;

// Test lookup with incomplete lookup context
template<typename T>
auto C<T>::f() -> decltype(x) { }
```
An assert fails because `CXXRecordDecl::hasAnyDependentBases` is called
on an incomplete class. This patch ensures we don't perform unqualified
lookup into dependent base classes when the lookup context is
incomplete.
2024-02-26 14:01:48 -05:00
cor3ntin
baf6bd303b
[Clang] Fixes to immediate-escalating functions (#82281)
* Consider that immediate escalating function can appear at global
scope, fixing a crash

* Lambda conversion to function pointer was sometimes not performed in
an immediate function context when it should be.

Fixes #82258
2024-02-21 20:53:44 +01:00
cor3ntin
9d3d6ec665
[Clang] CXXConstructExpr may be immediate calls. (#82179)
A CXXConstructExpr may refer to an immediate constructor, in which case
it should be substituted in the
enclosing default init expression.

Fixes #82154
2024-02-19 08:45:38 +01:00
Mariya Podchishchaeva
a18e92d020
[clang] Fix unexpected -Wconstant-logical-operand in C23 (#80724)
C23 has `bool`, but logical operators still return int. Check that
we're not in C to avoid false-positive -Wconstant-logical-operand.

Fixes https://github.com/llvm/llvm-project/issues/64356
2024-02-06 13:57:35 +01:00
Mike Rice
de1ea787ed
[OpenMP] Move unsupported structured bindings diagnostic (#80216)
Move the diagnostic so it fires only when doing an OpenMP capture, not
for non-OpenMP captures. This allows non-OpenMP code to work when using
OpenMP elsewhere, such as the code reported in
https://github.com/llvm/llvm-project/issues/66999.
2024-02-01 10:07:23 -08:00
yronglin
0aff71c178
[Clang] Implement P2718R0 "Lifetime extension in range-based for loops" (#76361)
Implement P2718R0 "Lifetime extension in range-based for loops"
(https://wg21.link/P2718R0)

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

---------

Signed-off-by: yronglin <yronglin777@gmail.com>
2024-01-30 06:48:14 +08:00
cor3ntin
ad1a65fcac
[Clang][C++26] Implement Pack Indexing (P2662R3). (#72644)
Implements https://isocpp.org/files/papers/P2662R3.pdf

The feature is exposed as an extension in older language modes.
Mangling is not yet supported and that is something we will have to do before release.
2024-01-27 10:23:38 +01:00
Craig Topper
c92ad411f2 Recommit "[RISCV] Support __riscv_v_fixed_vlen for vbool types. (#76551)"
Test updated to expect i8 gep.

Original message:

This adopts a similar behavior to AArch64 SVE, where bool vectors are
represented as a vector of chars with 1/8 the number of elements. This
ensures the vector always occupies a power of 2 number of bytes.

A consequence of this is that vbool64_t, vbool32_t, and vool16_t can
only be used with a vector length that guarantees at least 8 bits.
2024-01-25 10:20:29 -08:00
Craig Topper
51b25bad5e Revert "[RISCV] Support __riscv_v_fixed_vlen for vbool types. (#76551)"
This reverts commit b0511419b3fd71fa8f8c3618b7e849aabd2ccf65.

Test failure was reported.
2024-01-25 09:38:11 -08:00
Craig Topper
b0511419b3
[RISCV] Support __riscv_v_fixed_vlen for vbool types. (#76551)
This adopts a similar behavior to AArch64 SVE, where bool vectors are
represented as a vector of chars with 1/8 the number of elements. This
ensures the vector always occupies a power of 2 number of bytes.

A consequence of this is that vbool64_t, vbool32_t, and vool16_t can
only be used with a vector length that guarantees at least 8 bits.
2024-01-25 09:14:52 -08:00
Nikolas Klauser
4a58284559
[clang] Refactor Builtins.def to be a tablegen file (#68324)
This makes the builtins list quite a bit more verbose, but IMO this is a
huge win in terms of readability.
2024-01-24 11:22:43 +01:00
cor3ntin
e90e43fb9c
[Clang][NFC] Rename CXXMethodDecl::isPure -> is VirtualPure (#78463)
To avoid any possible confusion with the notion of pure function and the
gnu::pure attribute.
2024-01-18 15:30:58 +01:00
Sirraide
af0ee617fc
[Clang] Support MSPropertyRefExpr as placement arg to new-expression (#75883)
It seems we were forgetting to call `checkArgsForPlaceholders` on the
placement arguments of new-expressions in Sema. I don't think that was
intended—at least doing so doesn't seem to break anything—so this pr
adds that.

This also fixes #65053

---------

Co-authored-by: Erich Keane <ekeane@nvidia.com>
2024-01-17 15:09:31 -08:00
Krystian Stasiowski
68ae1e49d2
[Clang][Sema][NFC] Remove unused Scope* parameter from Sema::GetTypeForDeclarator and Sema::ActOnTypeName (#78325)
Split from #78274
2024-01-17 05:47:57 -05:00
Bill Wendling
00b6d032a2 [Clang] Implement the 'counted_by' attribute (#76348)
The 'counted_by' attribute is used on flexible array members. The
argument for the attribute is the name of the field member holding the
count of elements in the flexible array. This information is used to
improve the results of the array bound sanitizer and the
'__builtin_dynamic_object_size' builtin. The 'count' field member must
be within the same non-anonymous, enclosing struct as the flexible array
member. For example:

```
  struct bar;
  struct foo {
    int count;
    struct inner {
      struct {
        int count; /* The 'count' referenced by 'counted_by' */
      };
      struct {
        /* ... */
        struct bar *array[] __attribute__((counted_by(count)));
      };
    } baz;
  };
```

This example specifies that the flexible array member 'array' has the
number of elements allocated for it in 'count':

```
  struct bar;
  struct foo {
    size_t count;
     /* ... */
    struct bar *array[] __attribute__((counted_by(count)));
  };
```

This establishes a relationship between 'array' and 'count';
specifically that 'p->array' must have *at least* 'p->count' number of
elements available. It's the user's responsibility to ensure that this
relationship is maintained throughout changes to the structure.

In the following, the allocated array erroneously has fewer elements
than what's specified by 'p->count'. This would result in an
out-of-bounds access not not being detected:

```
  struct foo *p;

  void foo_alloc(size_t count) {
    p = malloc(MAX(sizeof(struct foo),
                   offsetof(struct foo, array[0]) + count *
                       sizeof(struct bar *)));
    p->count = count + 42;
  }
```

The next example updates 'p->count', breaking the relationship
requirement that 'p->array' must have at least 'p->count' number of
elements available:

```
  void use_foo(int index, int val) {
    p->count += 42;
    p->array[index] = val; /* The sanitizer can't properly check this access */
  }
```

In this example, an update to 'p->count' maintains the relationship
requirement:

```
  void use_foo(int index, int val) {
    if (p->count == 0)
      return;
    --p->count;
    p->array[index] = val;
  }
```
2024-01-16 14:26:12 -08:00
Rashmi Mudduluru
a511c1a9ec
Revert "[Clang] Implement the 'counted_by' attribute (#76348)"
This reverts commit 164f85db876e61cf4a3c34493ed11e8f5820f968.
2024-01-15 18:37:52 -08:00
Sander de Smalen
8e7f073eb4
[Clang][AArch64] Change SME attributes for shared/new/preserved state. (#76971)
This patch replaces the `__arm_new_za`, `__arm_shared_za` and
`__arm_preserves_za` attributes in favour of:
* `__arm_new("za")`
* `__arm_in("za")`
* `__arm_out("za")`
* `__arm_inout("za")`
* `__arm_preserves("za")`

As described in https://github.com/ARM-software/acle/pull/276.

One change is that `__arm_in/out/inout/preserves(S)` are all mutually
exclusive, whereas previously it was fine to write `__arm_shared_za
__arm_preserves_za`. This case is now represented with `__arm_in("za")`.

The current implementation uses the same LLVM attributes under the hood,
since `__arm_in/out/inout` are all variations of "shared ZA", so can use
the existing `aarch64_pstate_za_shared` attribute in LLVM.

#77941 will add support for the new "zt0" state as introduced
with SME2.
2024-01-15 09:41:32 +00:00
Bill Wendling
164f85db87 [Clang] Implement the 'counted_by' attribute (#76348)
The 'counted_by' attribute is used on flexible array members. The
argument for the attribute is the name of the field member holding the
count of elements in the flexible array. This information is used to
improve the results of the array bound sanitizer and the
'__builtin_dynamic_object_size' builtin. The 'count' field member must
be within the same non-anonymous, enclosing struct as the flexible array
member. For example:

```
  struct bar;
  struct foo {
    int count;
    struct inner {
      struct {
        int count; /* The 'count' referenced by 'counted_by' */
      };
      struct {
        /* ... */
        struct bar *array[] __attribute__((counted_by(count)));
      };
    } baz;
  };
```

This example specifies that the flexible array member 'array' has the
number of elements allocated for it in 'count':

```
  struct bar;
  struct foo {
    size_t count;
     /* ... */
    struct bar *array[] __attribute__((counted_by(count)));
  };
```

This establishes a relationship between 'array' and 'count';
specifically that 'p->array' must have *at least* 'p->count' number of
elements available. It's the user's responsibility to ensure that this
relationship is maintained throughout changes to the structure.

In the following, the allocated array erroneously has fewer elements
than what's specified by 'p->count'. This would result in an
out-of-bounds access not not being detected:

```
  struct foo *p;

  void foo_alloc(size_t count) {
    p = malloc(MAX(sizeof(struct foo),
                   offsetof(struct foo, array[0]) + count *
                       sizeof(struct bar *)));
    p->count = count + 42;
  }
```

The next example updates 'p->count', breaking the relationship
requirement that 'p->array' must have at least 'p->count' number of
elements available:

```
  void use_foo(int index, int val) {
    p->count += 42;
    p->array[index] = val; /* The sanitizer can't properly check this access */
  }
```

In this example, an update to 'p->count' maintains the relationship
requirement:

```
  void use_foo(int index, int val) {
    if (p->count == 0)
      return;
    --p->count;
    p->array[index] = val;
  }
```
2024-01-10 22:20:31 -08:00
Nico Weber
2dce77201c Revert "[Clang] Implement the 'counted_by' attribute (#76348)"
This reverts commit fefdef808c230c79dca2eb504490ad0f17a765a5.

Breaks check-clang, see
https://github.com/llvm/llvm-project/pull/76348#issuecomment-1886029515

Also revert follow-on "[Clang] Update 'counted_by' documentation"

This reverts commit 4a3fb9ce27dda17e97341f28005a28836c909cfc.
2024-01-10 21:05:19 -05:00
Bill Wendling
fefdef808c
[Clang] Implement the 'counted_by' attribute (#76348)
The 'counted_by' attribute is used on flexible array members. The
argument for the attribute is the name of the field member holding the
count of elements in the flexible array. This information is used to
improve the results of the array bound sanitizer and the
'__builtin_dynamic_object_size' builtin. The 'count' field member must
be within the same non-anonymous, enclosing struct as the flexible array
member. For example:

```
  struct bar;
  struct foo {
    int count;
    struct inner {
      struct {
        int count; /* The 'count' referenced by 'counted_by' */
      };
      struct {
        /* ... */
        struct bar *array[] __attribute__((counted_by(count)));
      };
    } baz;
  };
```

This example specifies that the flexible array member 'array' has the
number of elements allocated for it in 'count':

```
  struct bar;
  struct foo {
    size_t count;
     /* ... */
    struct bar *array[] __attribute__((counted_by(count)));
  };
```

This establishes a relationship between 'array' and 'count';
specifically that 'p->array' must have *at least* 'p->count' number of
elements available. It's the user's responsibility to ensure that this
relationship is maintained throughout changes to the structure.

In the following, the allocated array erroneously has fewer elements
than what's specified by 'p->count'. This would result in an
out-of-bounds access not not being detected:

```
  struct foo *p;

  void foo_alloc(size_t count) {
    p = malloc(MAX(sizeof(struct foo),
                   offsetof(struct foo, array[0]) + count *
                       sizeof(struct bar *)));
    p->count = count + 42;
  }
```

The next example updates 'p->count', breaking the relationship
requirement that 'p->array' must have at least 'p->count' number of
elements available:

```
  void use_foo(int index, int val) {
    p->count += 42;
    p->array[index] = val; /* The sanitizer can't properly check this access */
  }
```

In this example, an update to 'p->count' maintains the relationship
requirement:

```
  void use_foo(int index, int val) {
    if (p->count == 0)
      return;
    --p->count;
    p->array[index] = val;
  }
```
2024-01-10 15:21:10 -08:00
Timm Bäder
20c144ea10 [clang][Sema][NFC] Make a few parameters const 2024-01-09 14:46:37 +01:00
Bill Wendling
cca4d6cfd2
Revert counted_by attribute feature (#75857)
There are many issues that popped up with the counted_by feature. The
patch #73730 has grown too large and approval is blocking Linux testing.

Includes reverts of:
commit 769bc11f684d ("[Clang] Implement the 'counted_by' attribute
(#68750)")
commit bc09ec696209 ("[CodeGen] Revamp counted_by calculations
(#70606)")
commit 1a09cfb2f35d ("[Clang] counted_by attr can apply only to C99
flexible array members (#72347)")
commit a76adfb992c6 ("[NFC][Clang] Refactor code to calculate flexible
array member size (#72790)")
commit d8447c78ab16 ("[Clang] Correct handling of negative and
out-of-bounds indices (#71877)")
Partial commit b31cd07de5b7 ("[Clang] Regenerate test checks (NFC)")

Closes #73168
Closes #75173
2023-12-18 15:16:09 -08:00
Kazu Hirata
f3dcc2351c
[clang] Use StringRef::{starts,ends}_with (NFC) (#75149)
This patch replaces uses of StringRef::{starts,ends}with with
StringRef::{starts,ends}_with for consistency with
std::{string,string_view}::{starts,ends}_with in C++20.

I'm planning to deprecate and eventually remove
StringRef::{starts,ends}with.
2023-12-13 08:54:13 -08:00
wheatman
0031efe6be
Remove warnings from -Wchar-subscripts for known positive constants (#69061)
Fixes #18763

Remove warnings when using a signed char as an array bound if the char is a known positive constant.

This goes one step farther than gcc does.

For example given the following code
```c++
char upper[300];

int main() {
  upper['a'] = 'A';
  char b = 'a';
  upper[b] = 'A';
  const char c = 'a';
  upper[c] = 'A';
  constexpr char d = 'a';
  upper[d] = 'A';
  char e = -1;
  upper[e] = 'A';
  const char f = -1;
  upper[f] = 'A';
  constexpr char g = -1;
  upper[g] = 'A';
  return 1;
}
```

clang currently gives warnings for all cases, while gcc gives warnings
for all cases except for 'a' (https://godbolt.org/z/5ahjETTv3)

With the change there is no longer any warning for 'a', 'c', or 'd'.
2023-12-04 06:49:37 +01:00
Corentin Jabot
19e2174d54 Revert "[Clang] Eagerly instantiate used constexpr function upon definition. (#73463)"
This reverts commit 030047c432cac133738be68fa0974f70e69dd58d.

Breaks Qt and is inconsistent with GCC.

See the following issue for details:

Fixes #74069
2023-12-02 13:35:27 +01:00
cor3ntin
030047c432
[Clang] Eagerly instantiate used constexpr function upon definition. (#73463)
Despite CWG2497 not being resolved, it is reasonable to expect the
following code to compile (and which is supported by other compilers)

```cpp
  template<typename T> constexpr T f();
  constexpr int g() { return f<int>(); } // #1
  template<typename T> constexpr T f() { return 123; }
  int k[g()];
  // #2
```

To that end, we eagerly instantiate all referenced specializations of
constexpr functions when they are defined.

We maintain a map of (pattern, [instantiations]) independent of
`PendingInstantiations` to avoid having to iterate that list after each
function definition.

We should apply the same logic to constexpr variables, but I wanted to
keep the PR small.

Fixes #73232
2023-11-30 08:45:05 +01:00
cor3ntin
1cbd52f791
[Clang] Implement P2864R2 Remove Deprecated Arithmetic Conversion on Enumerations (#73105)
https://isocpp.org/files/papers/P2864R2.pdf
2023-11-29 21:27:17 +01:00
Timm Bäder
5480be13d5 [clang][NFC] Refactor Sema::DiagnoseSentinelCalls
Fix indentation, naming and capitalization to match current style
guides.
2023-11-15 08:37:01 +01:00
philnik777
4cc791bc98
[Clang] Add __datasizeof (#67805)
The data size is required for implementing the `memmove` optimization
for `std::copy`, `std::move` etc. correctly as well as replacing
`__compressed_pair` with `[[no_unique_address]]` in libc++. Since the
compiler already knows the data size, we can avoid some complexity by
exposing that information.
2023-11-13 11:00:07 +01:00
Yaxun (Sam) Liu
9774d0ce5f
[CUDA][HIP] Make template implicitly host device (#70369)
Added option -foffload-implicit-host-device-templates which is off by
default.

When the option is on, template functions and specializations without
host/device attributes have implicit host device attributes.

They can be overridden by device template functions with the same
signagure.
They are emitted on device side only if they are used on device side.

This feature is added as an extension.
`__has_extension(cuda_implicit_host_device_templates)` can be used to
check whether it is enabled.

This is to facilitate using standard C++ headers for device.

Fixes: https://github.com/llvm/llvm-project/issues/69956

Fixes: SWDEV-428314
2023-11-09 20:36:38 -05:00
Vlad Serebrennikov
6e35db0694 [clang][NFC] Refactor PredefinedExpr::IdentKind
This patch converts `PredefinedExpr::IdentKind` into a scoped enum in namespace scope, making it eligible for forward declaring. This is useful in certain contexts, such as `preferred_type` annotations on bit-fields.
2023-11-05 15:39:05 +03:00
Vlad Serebrennikov
c23aaa4103 [clang][NFC] Refactor CharacterLiteral::CharacterKind
This patch converts `CharacterLiteral::CharacterKind` to scoped enum in namespace scope. This enables forward declaration of this enum, which is useful in case like annotating bit-fields with `preferred_type`.
2023-11-05 13:36:08 +03:00
Vlad Serebrennikov
3e6ce58701 [clang][NFC] Refactor StringLiteral::StringKind
This patch converts `StringLiteral::StringKind` to a scoped enum in namespace scope. This enabled forward-declarations of this enum where necessary, e.g. for `preferred_type` annotation for bit-fields.
2023-11-05 12:30:49 +03:00
Vlad Serebrennikov
99e7e7a597 [clang][NFC] Refactor SourceLocExpr::IdentKind
This patch converts `SourceLocExpr::IdentKind` into a scoped enum at namespace scope, making it eligible to be forward-declared. This is needed by `preferred_type` annotations on bit-fields.
2023-11-04 12:43:26 +03:00
Vlad Serebrennikov
8775947633
[clang][NFC] Refactor clang::Linkage (#71049)
This patch introduces a new enumerator `Invalid = 0`, shifting other enumerators by +1. Contrary to how it might sound, this actually affirms status quo of how this enum is stored in `clang::Decl`:
```
  /// If 0, we have not computed the linkage of this declaration.
  /// Otherwise, it is the linkage + 1.
  mutable unsigned CacheValidAndLinkage : 3;
```
This patch makes debuggers to not be mistaken about enumerator stored in this bit-field. It also converts `clang::Linkage` to a scoped enum.
2023-11-02 20:57:29 +04:00
Vlad Serebrennikov
ae7b20b583 [clang][NFC] Refactor VectorType::VectorKind
This patch moves `VectorKind` to namespace scope, and make it complete at the point its bit-field is declared. It also converts it to a scoped enum.
2023-10-31 21:50:18 +03:00
Vlad Serebrennikov
4ad2ada521 [clang][NFC] Refactor ElaboratedTypeKeyword
This patch moves ElaboratedTypeKeyword before `Type` definition so that the enum is complete where bit-field for it is declared. It also converts it to scoped enum and removes `ETK_` prefix.
2023-10-31 20:46:07 +03:00
Vlad Serebrennikov
49fd28d960 [clang][NFC] Refactor ArrayType::ArraySizeModifier
This patch moves `ArraySizeModifier` before `Type` declaration so that it's complete at `ArrayTypeBitfields` declaration. It's also converted to scoped enum along the way.
2023-10-31 18:06:34 +03:00
Karl-Johan Karlsson
d25e0aac41
[Sema] Fixed faulty shift count warning (#69521)
Constant values of _BitInt have the bitwith to exactly fit the constant
number. This patch fix a problem in Sema when building an APInt where
the supplied bitwidth can become too small and simply truncate the value
leading to a faulty warning.
2023-10-25 09:48:01 +02:00
Kazu Hirata
f9306f6de3
[ADT] Rename llvm::erase_value to llvm::erase (NFC) (#70156)
C++20 comes with std::erase to erase a value from std::vector.  This
patch renames llvm::erase_value to llvm::erase for consistency with
C++20.

We could make llvm::erase more similar to std::erase by having it
return the number of elements removed, but I'm not doing that for now
because nobody seems to care about that in our code base.

Since there are only 50 occurrences of erase_value in our code base,
this patch replaces all of them with llvm::erase and deprecates
llvm::erase_value.
2023-10-24 23:03:13 -07:00
Lawrence Benson
de65b6bec6
[Clang] Add __builtin_vectorelements to get number of elements in vector (#69010)
Adds a new `__builtin_vectorelements()` function which returns the
number of elements for a given vector either at compile-time for
fixed-sized vectors, e.g., created via `__attribute__((vector_size(N)))`
or at runtime via a call to `@llvm.vscale.i32()` for scalable vectors,
e.g., SVE or RISCV V.

The new builtin follows a similar path as `sizeof()`, as it essentially
does the same thing but for the number of elements in vector instead of
the number of bytes. This allows us to re-use a lot of the existing
logic to handle types etc.

A small side addition is `Type::isSizelessVectorType()`, which we need
to distinguish between sizeless vectors (SVE, RISCV V) and sizeless
types (WASM).

This is the [corresponding
discussion](https://discourse.llvm.org/t/new-builtin-function-to-get-number-of-lanes-in-simd-vectors/73911).
2023-10-19 10:45:08 +02:00
Aaron Ballman
343bed8d3a Canonically identical types are allowed in compound expressions in C
We did not have a catch-all for when the two operand types are
identical after canonicalization. Instead, we handled that on a case by
case basis. Thus, we would diagnose code like:
```
mat4 test(int a) {
  typedef float mat4 __attribute((matrix_type(4, 4)));
  mat4 transform;
  return (a > 0) ? transform : transform;
}
```
This simplifies the logic and will be more forwards
compatible with other extended datatypes.

Fixes https://github.com/llvm/llvm-project/issues/69008
2023-10-14 11:03:35 -04:00
Bill Wendling
769bc11f68
[Clang] Implement the 'counted_by' attribute (#68750)
The 'counted_by' attribute is used on flexible array members. The
argument for the attribute is the name of the field member in the same
structure holding the count of elements in the flexible array. This
information can be used to improve the results of the array bound
sanitizer and the '__builtin_dynamic_object_size' builtin.

This example specifies the that the flexible array member 'array' has
the number of elements allocated for it in 'count':

  struct bar;
  struct foo {
    size_t count;
     /* ... */
    struct bar *array[] __attribute__((counted_by(count)));
  };

This establishes a relationship between 'array' and 'count',
specifically that 'p->array' must have *at least* 'p->count' number of
elements available. It's the user's responsibility to ensure that this
relationship is maintained through changes to the structure.

In the following, the allocated array erroneously has fewer elements
than what's specified by 'p->count'. This would result in an
out-of-bounds access not not being detected:

  struct foo *p;

  void foo_alloc(size_t count) {
    p = malloc(MAX(sizeof(struct foo),
                   offsetof(struct foo, array[0]) + count *
                       sizeof(struct bar *)));
    p->count = count + 42;
  }

The next example updates 'p->count', breaking the relationship
requirement that 'p->array' must have at least 'p->count' number of
elements available:

  struct foo *p;

  void foo_alloc(size_t count) {
    p = malloc(MAX(sizeof(struct foo),
                   offsetof(struct foo, array[0]) + count *
                       sizeof(struct bar *)));
    p->count = count + 42;
  }

  void use_foo(int index) {
    p->count += 42;
    p->array[index] = 0; /* The sanitizer cannot properly check this access */
  }

Reviewed By: nickdesaulniers, aaron.ballman

Differential Revision: https://reviews.llvm.org/D148381
2023-10-14 04:18:02 -07:00