2015 Commits

Author SHA1 Message Date
Timm Baeder
b9659ded76
[clang] Fix checkMathBuiltinElementType SignedIntOrFloatTy checks (#180528)
The previous check was way too loose and let everything except unsigned
integer types through.
See e.g. https://godbolt.org/z/3qY8EbK56
2026-02-10 05:27:09 +01:00
Timm Baeder
4344268ad6
[clang] Return std::optional from all Expr::tryEvaluate* API (#179230)
tryEvaluateString was returning an std::optional, but the other try* API
was not. Update tryEvaluateObjectSize and tryEvaluateStrLen to return an
std::optional<uint64_t>.
2026-02-09 13:37:14 +01:00
Prajwal P J
fed9abcb47
[Clang] Fix missing -Warray-bounds warning on member function calls. (#179647)
Fixes #179128.
This patch fixes a false negative where Clang failed to detect
out-of-bounds access when calling a member function on an invalid array
index. It adds handling for CXXMemberCallExpr in CheckArrayAccess.

Signed-off-by: prajwal jalwadi<prajwaljalwadi@gmail.com>
2026-02-09 12:59:38 +01:00
Djordje Todorovic
84cdaa458a
Reland "[clang][RISCV] Add big-endian RISC-V target support" (#177939)
The problem was using the `--rtlib=platform` without
`--unwindlib=platform` conflicts the default unwindlib with the
Fuchsia's configuration, and that is why the test failed.

Orignal PR: https://github.com/llvm/llvm-project/pull/165599
The fail was reported at:
https://github.com/llvm/llvm-project/pull/165599#issuecomment-3751750804

Co-authored-by: Djordje Todorovic <djordje.todorovic@syrmia.com>
2026-02-05 10:53:54 +01:00
woruyu
f541056513
[Clang] Fixes builtin_bswapg builtin for bool type (#179177)
This PR resolves #178317, the related PR: #169285
2026-02-04 13:49:45 +00:00
Abhay Kanhere
e39d2822bc
[CodeGen][AArch64] ptrauth intrinsic to safely construct relative ptr (#142047)
ptrauth intrinsic to safely construct relative ptr for swift coroutines.

A ptrauth intrinsic for swift co-routine support that allows creation of
signed pointer
 from offset stored at address relative to the pointer.

Following C-like pseudo code (ignoring keys,discriminators) explains its
operation:
      let rawptr = PACauth(inputptr);
return PACsign( rawptr + signextend64( *(int32*)(rawptr+addend) ))

What: Authenticate a signed pointer, load a 32bit value at offset
'addend' from pointer,
       add this value to pointer, sign this new pointer.
 builtin: __builtin_ptrauth_auth_load_relative_and_sign
 intrinsic: ptrauth_auth_resign_load_relative
2026-02-03 18:03:37 +01:00
Joseph Huber
d5899ccb6f
[Clang] Rename uinc_wrap and add normal atomic builtin (#177253)
Summary:
The `__scoped_atomic` builtins are supposed to match the standard
GNU-flavored `__atomic` builtins. We added a scoped builtin without a
corresponding standard one before the fork so this should be added in
the release candidate. These were originally added in
https://github.com/llvm/llvm-project/pull/168666

Also, the name `uinc_wrap` does not follow the naming convention. The
GNU atomics use `fetch_xyz` to indicate that the builtin returns the
previous location's value as part of the RMW operation, which these do.
This PR renames it and its uses.
2026-01-22 08:02:45 -06:00
NagaChaitanya Vellanki
370529c7f7
[clang] Implement __builtin_stdc_rotate_left, __builtin_stdc_rotate_right (#160259)
This patch adds type-generic rotate builtins that accept any unsigned
integer
type. These builtins provide:

- Support for all unsigned integer types, including _BitInt
- Constexpr evaluation capability
- Automatic normalization of rotation counts modulo the bit-width
- Proper handling of negative rotation counts (converted to equivalent
  positive rotations in the opposite direction)
- Implicit conversion support for both arguments for
  types with conversion operators. 

The builtins follow C23 naming conventions.

Resolves https://github.com/llvm/llvm-project/issues/122819
2026-01-21 10:30:45 +01:00
Djordje Todorovic
dc133c9c21
Revert "[clang][RISCV] Add big-endian RISC-V target support" (#176039)
Reverts llvm/llvm-project#165599
2026-01-14 23:04:53 +01:00
Djordje Todorovic
2bce962db2
[clang][RISCV] Add big-endian RISC-V target support (#165599)
We proceeded with frontend/clang changes, until we figure out how ABI
for BE should look like. Once it is final, we will proceed with codegen
changes.

In this patch several things addressed:
  - Define riscv32be/riscv64be target triples
  - Set correct data layout for BE targets
  - Handle BE-specific ABI details
  - Emit warning for BE case since it is still experimental
2026-01-14 21:46:36 +01:00
Hans Wennborg
2a8be8bd73
Revert "[Clang] Warn when std::atomic_thread_fence is used with fsanitize=thread" (#175520)
Reverts llvm/llvm-project#166542

It caused clang to assert with: `!isa<CXXDestructorDecl>(D) && "Use
other ctor with dtor decls!"`
see comment on the PR.
2026-01-12 12:01:47 +00:00
Benjamin Stott
d6d5c5f6a2
[Clang] Warn when std::atomic_thread_fence is used with fsanitize=thread (#166542)
- ThreadSanitizer currently does not support `std::atomic_thread_fence`,
leading to false positives:
https://github.com/llvm/llvm-project/issues/52942.
- GCC produces a warning when `std::atomic_thread_fence` is used with
`-fsanitize=thread` while Clang doesn't.
- This PR introduces a matching warning in Clang to avoid confusion as
in the linked issue.

---------

Co-authored-by: Aaron Ballman <aaron@aaronballman.com>
2026-01-09 10:20:35 +00:00
Marco Elver
0e2b16217e
[Clang] Add __builtin_allow_sanitize_check() (#172030)
Introduce `__builtin_allow_sanitize_check("name")` which returns true if
the specified sanitizer is enabled for the function (after inlining).
Supported sanitizers are "address", "thread", "memory", "hwaddress", and
their "kernel-" variants, matching the names of the
`no_sanitize("name")`
usage.

This builtin enables conditional execution of explicit checks only when
the sanitizer is enabled, respecting `no_sanitize` attributes, even when
used from `always_inline` functions that may be used in sanitized or
no_sanitize functions.

Since we must defer until after inlining and cannot determine the result
statically, Clang must lower to the `llvm.allow.sanitize.*` intrinsics,
which are then resolved by the `LowerAllowCheckPass`.

*Original Motivation:*  The Linux kernel has a number of low-level
primitives that use inline assembly not visible to the sanitizers, but
use explicitly inserted checks to avoid coverage loss. Many of those
low-level helpers, however, are also used from so-called `noinstr`
functions, which use `no_sanitize(..)` to prohibit instrumentation;
these are used for very brittle code (such as when the kernel sets up a
task context *before* normal memory is accessible), and any
instrumentation, incl. from explicit instrumentation, is prohibited.
Many such helpers themselves are macros or `always_inline`, however, are
unable to be used from such brittle contexts because they contain
explicit instrumentation. This requires awkward workarounds to avoid the
instrumentation.

The ideal solution is this new builtin, that can be used to determine if
instrumentation is enabled in a given function or not, which the helper
can then use to insert instrumentation only where instrumentation is
allowed.

A recent such case came up in [1], where file-level instrumentation had
already been disabled for KASAN and KCSAN, which had not been necessary
if the new builtin were available.

[1] https://lore.kernel.org/all/20251208-gcov-inline-noinstr-v1-0-623c48ca5714@google.com/
2026-01-05 19:38:44 +01:00
Farzon Lotfi
491e001627
[HLSL][Matrix] Add Matrix Bool and represent them as i32 elements (#171051)
fixes #171049
fixes #171050

- Allow Bools for matrix type when in HLSL mode
- use ConvertTypeForMem to figure out the bool size
- Add Bool matrix types to hlsl_basic_types.h

---------

Co-authored-by: Helena Kotas <hekotas@microsoft.com>
2025-12-15 10:21:32 -05:00
Farzon Lotfi
7062cd63d0
[Matrix] Add a row\col major toggle in the clang driver (#167628)
fixes #167621

- define the new options in `Options.td` limit the naming to row-major
or column-major.
- In `ToolChains/Clang.cpp` limit the opt usage to only when
`-fenable-matrix` is used.

---------

Co-authored-by: Florian Hahn <flo@fhahn.com>
2025-12-09 18:30:25 -05:00
Vladimir Vuksanovic
1df7b512bd
[Sema] Suggest missing format attributes (#166738)
Implements the `-Wmissing-format-attribute` diagnostic as a subgroup of
`-Wformat-nonliteral`. It suggests adding format attributes to function
declarations that call other format functions and pass the format string
to them.

This is an updated implementation of #105479.

---------

Co-authored-by: Budimir Arandjelovic <budimir.arandjelovic@htecgroup.com>
2025-12-05 09:04:12 -05:00
Kees Cook
722026886f
[Clang] Extend __builtin_counted_by_ref to support pointers with 'counted_by' (#170750)
The __builtin_counted_by_ref builtin was previously limited to flexible
array members (FAMs). This change extends it to also support pointer
members that have the 'counted_by' attribute.

The 'counted_by' attribute can be applied to both FAMs and pointer
members:

    struct fam_struct {
        int count;
        int array[] __attribute__((counted_by(count)));
    };

    struct ptr_struct {
        int count;
        int *buf __attribute__((counted_by(count)));
    };

With this change, __builtin_counted_by_ref works with both:

    *__builtin_counted_by_ref(p->array) = size;  // FAM - already worked
    *__builtin_counted_by_ref(p->buf) = size;    // pointer - now works

This enables the same allocation pattern for pointer members that was
previously only available for FAMs:

    #define alloc_buf(P, MEMBER, COUNT) ({                           \
        typeof(P) __p = malloc(sizeof(*__p));                        \
        __p->MEMBER = malloc(sizeof(*__p->MEMBER) * COUNT);          \
        *_Generic(__builtin_counted_by_ref(__p->MEMBER),             \
            void *: &(size_t){0},                                    \
            default: __builtin_counted_by_ref(__p->MEMBER)) = COUNT; \
        __p;                                                         \
    })

The builtin returns:
- A pointer to the count field if the member has 'counted_by'
- void* (null) if the member is an array or pointer without 'counted_by'
- An error for other member types (e.g., int, struct)

This was requested by upstream Linux kernel devs:

https://lore.kernel.org/linux-hardening/202512041215.44484FCACD@keescook/
2025-12-04 23:18:39 -08:00
Farzon Lotfi
dd1b4abfb7
[HLSL][Matrix] Add support for Matrix element and trunc Casts (#168915)
fixes #168737
fixes #168755

This change fixes adds support for Matrix truncations via the
ICK_HLSL_Matrix_Truncation enum. That ends up being most of the files
changed.

It also allows Matrix as an HLSL Elementwise cast as long as the cast
does not perform a shape transformation ie 3x2 to 2x3.

Tests for the new elementwise and truncation behavior were added. As
well as sema tests to make sure we error n the shape transformation
cast.

I am punting right now on the ConstExpr Matrix support. That will need
to be addressed later. Will file a seperate issue for that if reviewers
agree it can wait.
2025-12-02 19:02:25 -05:00
Wenju He
5d38cddc3b
[Clang] Add __scoped_atomic_uinc_wrap and __scoped_atomic_udec_wrap builtins (#168666)
This PR extends __scoped_atomic builtins with inc and dec functions.
They map to LLVM IR `atomicrmw uinc_wrap` and `atomicrmw udec_wrap`.
These enable implementation of OpenCL-style atomic_inc / atomic_dec with
wrap semantics on targets supporting scoped atomics (e.g. GPUs).

---------

Co-authored-by: Copilot <175728472+Copilot@users.noreply.github.com>
2025-11-26 09:29:55 +08:00
venk-ks
1a29a2359b
[Clang][Sema] Add fortify warnings for strcat (#168965)
Continue to add fortify warnings that are missing in Clang for string
functions as part of #142230
2025-11-21 11:15:28 -08:00
Marco Elver
609c88a1fd
[Clang][Sema] Fix __builtin_infer_alloc_token() return type (#168773)
Using the builtin failed on 32-bit architectures:
```
clang/lib/AST/ExprConstant.cpp:14299: [..]: Assertion `I.getBitWidth() == Info.Ctx.getIntWidth(E->getType()) && "Invalid evaluation result."' failed.
```

The return type is meant to be size_t. Fix it.
2025-11-19 22:25:35 +01:00
clf
f210fc1a1c
[Clang] Add __builtin_bswapg (#162433)
Add a new builtin function __builtin_bswapg. It works on any integral
types that has a multiple of 16 bits as well as a single byte.

Closes #160266
2025-11-15 12:27:38 -08:00
Wenju He
3b010c96ac
[Clang] Add elementwise ldexp builtin function (#166296)
This PR adds __builtin_elementwise_ldexp. It can be used for
implementing OpenCL ldexp builtin with vector inputs.
2025-11-06 07:31:30 +08:00
Vladimir Vuksanovic
1fe3b2d81b
[Sema] Fix parameter index checks on explicit object member functions (#165586)
With the C++23 explicit object parameter feature, it is no longer
sufficient to only check if a function is an instance method to
determine if it has an implicit this argument. That causes problems in
attributes that have parameter indexes.
2025-10-31 14:52:01 +01:00
Bruno De Fraine
e07aef9dde
[clang][Sema] close IsStandardConversion hole when adding cfi_unchecked_callee (#164592)
Commit b194cf1e401a changed this function for the case where attribute
`cfi_unchecked_callee` is added in a function conversion. But this
introduces a hole (issue #162798), and it seems the change was
unnecessary: the preceding `TryFunctionConversion` will already allow
adding the `cfi_unchecked_callee` attribute, and will update `FromType`
if it succeeds. So we revert the changes to `IsStandardConversion`. We
also remove the helper function `AddingCFIUncheckedCallee` which is no
longer needed, and simplify the corresponding
`DiscardingCFIUncheckedCallee`.

Fixes: #162798
2025-10-24 23:33:25 +02:00
Marco Elver
4f4bee428d
[Clang][Sema] Add __builtin_infer_alloc_token() declaration and semantic checks (#163638)
Introduce the `__builtin_infer_alloc_token()` builtin declaration and
adds the necessary semantic checks in Sema.
2025-10-23 12:41:21 +02:00
Jakub Kuderski
d86da4efee
[ADT] Prepare for deprecation of StringSwitch cases with 4+ args. NFC. (#164173)
Update `.Cases` and `.CasesLower` with 4+ args to use the
`initializer_list` overload. The deprecation of these functions will
come in a separate PR.

For more context, see: https://github.com/llvm/llvm-project/pull/163405.
2025-10-20 12:03:46 -04:00
Corentin Jabot
3a15687d1c
[Clang] Do not warn on UTF-16 -> UTF-32 conversions. (#163927)
UTF-16 to UTF-16 conversions seems widespread,
and lone surrogate have a distinct representation in UTF-32.

Lets not warn on this case to make the warning easier to adopt. This
follows SG-16 guideline


https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2025/p3695r2.html#changes-since-r1

Fixes #163719
2025-10-19 09:26:22 +02:00
Farzon Lotfi
1d5bd28906
[Matrix][Clang][HLSL] Move MaxMatrixDimension to a LangOpt (#163307)
fixes #160190
fixes #116710

This change just makes MaxMatrixDimension configurable by language mode.
It was previously introduced in
94b43118e2
when there was not a need to make dimensions configurable.

Current testing to this effect exists in:
- clang/test/Sema/matrix-type-builtins.c
- clang/test/SemaCXX/matrix-type-builtins.cpp
- clang/test/SemaHLSL/BuiltIns/matrix-basic_types-errors.hlsl

New Tests to confirm configurability by language mode:
- clang/unittests/Frontend/CompilerInvocationTest.cpp

I considered adding a driver flag to
`clang/include/clang/Driver/Options.td` but HLSL matrix max dim is
always 4 so we don't need this configurable beyond that size for our use
case.
2025-10-16 09:01:53 -04:00
Matheus Izvekov
b516dcc998
[clang] NFC: rename TagType::getOriginalDecl back to getDecl (#163271)
This rename was made as part of
https://github.com/llvm/llvm-project/pull/147835 in order to ease
rebasing the PR, and give a nice window for other patches to get rebased
as well.

It has been a while already, so lets go ahead and rename it back.
2025-10-15 16:11:17 -03:00
yicuixi
3e023f7169
[clang] Don't crash when -Wformat-signedness specified (#162049)
Fixes https://github.com/llvm/llvm-project/issues/161075. This patch
follow the changes in https://github.com/llvm/llvm-project/pull/150962,
and fix a crash issue when `-Wformat-signedness` was specificed.
2025-10-07 13:07:06 +08:00
Timm Baeder
8dac6e28c9
Reapply "[clang] Convert second arg of __builtin_assume_aligned to Co… (#161945)
…nstantExpr (#161314)" (#161719)

This reverts commit f1650cf91b01470ce44f47797663d59f00828493.
2025-10-05 08:35:56 +02:00
Devon Loehr
f1650cf91b
Revert "[clang] Convert second arg of __builtin_assume_aligned to ConstantExpr (#161314)" (#161719)
This reverts commit 8f77621574176387f906b8ceef9e1abb90bf22f6 (#161314).

Reason: Causing crashes when building https://github.com/google/highway.
See the original PR for details.
2025-10-02 15:11:07 -04:00
Samarth Narang
a2330a398d
[Clang][Sema] Switch diagnostics from toString to operator<< for APSInt/APInt (#161474) 2025-10-02 07:59:52 +05:30
Justin Bogner
78c65545d4
[AST] Give CharUnits::operator% a consistent type. NFC (#160781)
Update the `operator%` overload that accepts `CharUnits` to return
`CharUnits` to match the other `operator%`. This is more logical than
returning an `int64` and cleans up users that want to continue to do
math with the result.

Many users of this were explicitly comparing against 0. I considered
updating these to compare against `CharUnits::Zero` or even introducing
an `explicit operator bool()`, but they all feel clearer if we update
them to use the existing `isMultipleOf()` function instead.
2025-10-01 19:15:46 +00:00
Timm Baeder
8f77621574
[clang] Convert second arg of __builtin_assume_aligned to ConstantExpr (#161314)
Since the second argument must be a constant integer, we can as well
convert it to a `ConstantExpr` in Sema.


Fixes https://github.com/llvm/llvm-project/issues/161272
2025-10-01 16:24:48 +02:00
Joseph Huber
8a9aa183ac
[Clang][FIX] Fix type qualifiers on vector builtins (#160185)
Summary:
These were not stripping qualifiers when using them to infer the types,
leading to errors when mixiing const and non-const.
2025-09-25 18:32:24 -05:00
Xing Guo
c5ded52d5f
[clang][Sema] Accept gnu format attributes (#160255)
This patch teaches clang accepts gnu_printf, gnu_scanf, gnu_strftime and
gnu_strfmon. These attributes are aliases for printf, scanf, strftime and
strfmon.

Ref: https://gcc.gnu.org/onlinedocs/gcc/Common-Function-Attributes.html
Fixes: #16219

---------

Co-authored-by: Sirraide <aeternalmail@gmail.com>
2025-09-25 16:56:17 +08:00
Joseph Huber
c989283c27
[Clang] Change masked load / store builtin interface to take scalar pointer (#156063)
Summary:
Right now these enformce alignment, which isn't convenient for the user
on platforms that support unaligned accesses. The options are to either
permit passing the alignment manually, or just assume it's unaligned
unless the user specifies it.

I've added https://github.com/llvm/llvm-project/pull/156057 which should
make the requiested alignment show up on the intrinsic if the user
passed `__builtin_assume_aligned`, however that's only with
optimizations. This shouldn't cause issues unless the backend
categorically decides to reject an unaligned access.
2025-09-24 16:32:49 -05:00
Marcel Jacobse
3cc56dd82a
[Clang] [Sema] Fix -Wdouble-promotion in C++ list-initialization (#159992)
Resolves https://github.com/llvm/llvm-project/issues/33409.

The information `IsListInit` is already passed to function
`CheckImplicitConversion` for another use-case which makes adding a
condition for the double-promotion case simple.

Also adds tests, both for the changed list-initialization case as well
as for normal explicit casts which already would have passed before this
PR. These negative tests are added directly next to the positive tests
in `warn-double-promotion.c` or for the C++-specific cases in a new .cpp
version of that file.
2025-09-24 18:33:27 +00:00
Akira Hatanaka
8a0d145d90
[os_log] Fix a CodeGen crash that occurs when arguments of struct, class, or complex types are passed to _builtin_os_log_format (#158744)
This change fixes the crash in clang's CodeGen by erroring out in Sema
if those arguments are passed.

rdar://139824423
2025-09-23 12:21:15 -07:00
Mary Kassayova
2c12a3df76
[Sema][AArch64] Emit error for mismatched VLs on streaming mode transitions (#159131)
Update Sema::checkCall to handle the case where a call involves a
streaming mode transition and passes or returns scalable vector types.
Previously, Clang always issued a warning in this case, noting that the
streaming and non-streaming vector lengths may differ at runtime. With
this change:
- if both `-msve-vector-bits` and `-msve-streaming-vector-bits` are
specified and produce different fixed VL values, Clang now emits an
error rather than a warning
- If either flag is missing or vector lengths are equal, the diagnostic
remains a warning
2025-09-23 11:05:47 +01:00
Joseph Huber
2c6adc97d4
[Clang] Add vector gather / scatter builtins to clang (#157895)
Summary:
This patch exposes `__builtin_masked_gather` and
`__builtin_masked_scatter` to clang. These map to the underlying
intrinsic relatively cleanly, needing only a level of indirection to
take a vector of indices and a base pointer to a vector of pointers.
2025-09-22 08:22:10 -05:00
Joseph Huber
1597fad405
[Clang] Rename elementwise builtins to clzg and ctzg (#157128)
Summary:
The added bit counting builtins for vectors used `cttz` and `ctlz`,
which is consistent with the LLVM naming convention. However, these are
clang builtins and implement exactly the `__builtin_ctzg` and
`__builtin_clzg` behavior. It is confusing to people familiar with other
other builtins that these are the only bit counting intrinsics named
differently. This includes the additional operation for the undefined
zero case, which was added as a `clzg` extension.
2025-09-19 07:00:47 -05:00
Timm Baeder
5399ca97c4
[clang][sema][NFC] Use a for-range loop in checkBuiltinVerboseTrap (#159114)
We don't use `I` at all, so use a for-range loop.
2025-09-17 07:24:07 +02:00
Timm Baeder
c8b5b6e0a6
[clang][ExprConst] Reject unary vector shuffles (#158589)
This is not implemented at compile time and asserts in assertion builds,
so reject it here.


Fixed the coding style in `BuiltinShuffleVector` at the same time.

Fixes #158471
2025-09-16 07:58:15 +02:00
Timm Baeder
6dde34969e
[clang][sema][NFC] Clean up builtin arg checking functions (#158615)
Always take an `unsigned` for the argument index, pull some locals in
the closest scope and use `APInt::isPowerOf2()`.
2025-09-16 04:55:20 +02:00
Joseph Huber
62447efa73
[Clang] Permit half precision in __builtin_complex (#156479)
Summary:
This was forbidden previously, which made us divergent with the GCC
implementation. Permit this by simply removing this Sema check.

Fixes: https://github.com/llvm/llvm-project/issues/156463
2025-09-02 11:16:21 -05:00
Joseph Huber
ca14a8afe8
[Clang] Add masked vector builtins for expand and compress access (#156042)
Summary:
The interface here is nearly indentical to the already added masked
loads and stores. These bind to very similar intrinsics so we add them
here.
2025-08-29 11:37:11 -05:00
Chaitanya Koparkar
5e97338c95
[Clang] Update typechecking of builtin elementwise ternary math operators (#155620)
For scalars we directly compare their unqualified types. But even if we
compare unqualified vector types, a difference in qualifiers in the
element types can make the vector types be considered not equal. For
example, vector of 4 'const float' values vs vector of 4 'float' values.
So we compare unqualified types of their elements and number of
elements.

Fixes #155405
2025-08-29 10:32:59 +00:00