`SortIncludes` currently orders includes lexicographically with the
option to ignore case or extension. This adds another option, `Natural`,
that compares embedded runs of digits as numbers rather than sequences
of characters, matching the "natural sort" behaviour found in most file
managers and tools like `sort` when called with the `-V` option.
**Disclaimer**
AI assistance was used in initial exploration and review but the code is
"hand generated".
The UPDATE clause has the same spelling on both of these directives, but
functionally it's two different clauses. Split them into "update", and
"update_depend_objects" to be able to tie their properties to their enum
ids.
This should make it easier to implement auto-generating of clause
properties in the future by avoiding spelling conflicts.
---------
Co-authored-by: Alexey Bataev <a.bataev@outlook.com>
RangedConstraintManager discards a simplified symbol if it reduces to a
concrete integer. This leads to delayed realization that some state
might be infeasible (because the concrete integer does not fit in the
assumed range), which might produce unexpected null pointers on the
following state splits.
PthreadLockChecker has fallen just into this trap. It assumes
`pthread_mutex_lock` is always called in a feasible state, which is was
not true.
In particular, in ZFS the analyzer crashes when runs in CTU mode because
it reaches `pthread_mutex_lock()` in over-constraint state (see the
reduced example in the first commit).
Checkers rely on the invariant that a state split can never result in
both `StateRef`s being null. To fix this violation of the invariant,
this patch helps RangedConstraintManager to realize a state is
infeasible and abort its exploration early so no follow-up state split
produce unexpected null-null pair.
Assisted by Claude Opus 4.8
--
CPP-8665
fixes https://github.com/llvm/llvm-project/issues/212109
From the edits to the release notes:
- On MIPS, a `_Complex` value with an integer element type is now
returned packed
into a single integer register when it fits in one, matching GCC. A
`_Complex char` or
`_Complex short`, and on N32/N64 also a `_Complex int`, is no longer
returned
with one part per register. `-fclang-abi-compat=23` restores the
previous
behavior. (#GH212109)
- On MIPS N32/N64, a `_Complex float` or `_Complex double` argument is
now packed
into integer registers, or onto the stack, once there is no longer room
to give
each of its parts a floating-point register, matching GCC. Clang
previously
always passed the parts separately. `-fclang-abi-compat=23` restores the
previous
behavior. (#GH212109)
This PR adds diagnostics for exact `Where.Parameters` selectors on top
of the existing parsing, serialization, and Sema matching support.
It diagnoses duplicate exact selectors during API notes conversion,
including duplicate `Where.Parameters: []`, while still allowing broad
name-only entries and same-name entries with different selectors.
It also adds reader/Sema support to warn under `-Wapinotes` when an
exact selector in API notes does not match any visible overload. The
reader can now enumerate stored exact selectors for global functions and
C++ methods, and Sema compares those against the selector candidates
derived from the visible overload set.
The diagnostic path follows the same matching policy as Sema, including
the desugared alias fallback, so valid matched selectors do not produce
false warnings.
Tests cover duplicate selector errors, unmatched selector warnings for
globals and C++ methods, broad-plus-exact coexistence, exact notes not
silently applying on mismatch, and no false warnings for matched or
alias-fallback selectors.
Reviewers: @Xazax-hun @j-hui @egorzhdan
---------
Co-authored-by: John Hui <updog@j-hui.com>
We aren't testing the existence of the function in the output here, but
without these markers, debugging test failures here can become very
cumbersome.
1) Mention the limit in the "constexpr evaluation hit maximum step
limit" diagnostic as well
2) Move the "use -fconstexpr-steps" instruction to its own note so we
can reuse it for two different diagnostics
For
```c++
struct S {
constexpr S() {}
};
constexpr S foo[1'500'000] = {};
```
we used to emit
```console
array.cpp:1028:13: error: constexpr variable 'foo' must be initialized by a constant expression
1028 | constexpr S foo[1'500'000] = {};
| ^ ~~
array.cpp:1026:17: note: constexpr evaluation hit maximum step limit; possible infinite loop?
1026 | constexpr S() {}
| ^
array.cpp:1028:31: note: in call to 'S()'
1028 | constexpr S foo[1'500'000] = {};
| ^
```
and now we emit
```console
array.cpp:1028:13: error: constexpr variable 'foo' must be initialized by a constant expression
1028 | constexpr S foo[1'500'000] = {};
| ^ ~~
array.cpp:1026:17: note: constexpr evaluation hit maximum step limit of 1048576; possible infinite loop?
1026 | constexpr S() {}
| ^
array.cpp:1028:31: note: in call to 'S()'
1028 | constexpr S foo[1'500'000] = {};
| ^
array.cpp:1026:17: note: use -fconstexpr-steps= to increase this limit (=0 will remove the limit)
1026 | constexpr S() {}
```
Migrate .def file to tablegen. The initial TargetParser
AMDGPU backend only handled R600. Extend to modern targets.
Stub out some tablegen definitions which will be used in future
changes.
Co-authored-by: Claude (Claude-Opus-4.8)
This commit adds APFloat support for UE5M3 type and the associated tests. It is an 8 bit FP type with no sign bit, 5 exponent and 3 mantissa bits
| Property | Value |
|-----------------|------------|
| Max exponent | 31 |
| Bias | 15 |
| Zero encoding | 00000 000 |
| Smallest denorm | 00000 001 |
| Largest denorm | 00000 111 |
| Smallest norm | 00001 000 |
| Largest norm | 11111 110 |
| Canonical NaN | 11111 111 |
Please refer [PTX ISA](https://docs.nvidia.com/cuda/developer-preview/13.4/parallel-thread-execution/index.html#alternate-floating-point-data-formats) for more info
Assisted by: Claude Code (Opus 4.8)
On Wasm, it's not currently possibly to change which `personality` is
attached to a given IR function. This is primarily because no matter
what `personality` is attached, codegen creates a call to a
`Unwind_CallPersonality` wrapper hard-coded to call c++abi's
personality.
In order to allow alternative personalities without introducing bloat at
each personality call site, this PR adjusts the ABI of the personality
on Wasm. `Unwind_CallPersonality` is moved to `libcxxabi` under the name
`__gxx_wasm_personality_v0`, with the "real" personality code renamed
`__gxx_personality_imp` and called by `__gxx_wasm_personality_v0` (after
resetting the landing pad context).
The signature of EH personalities on Wasm is now `int personality(void*
exception_object)` (where the int return is `_Unwind_Reason_Code` and
the `void*` is `_Unwind_Exception*`), and personalities are expected to
`__wasm_lpad_context.selector = 0;`.
Based on #175202
This change updates HeaderIncludes to recognize #import directives in
addition to #include when parsing existing headers. It also fixes up an
existing issue parsing include/import statements that may have contained
tabs.
Fix `AlignTrailingComments` with `OverEmptyLines` aligning trailing
comments across block boundaries (e.g., between two functions or
structs). The alignment sequence now breaks at block-type braces
(`BK_Block`).
This is an `OverEmptyLines` bug exposed by
bae9ddca42 (#206393).
Fixes https://github.com/llvm/llvm-project/issues/208266
(https://github.com/llvm/llvm-project/issues/208266).
Commit created with the help of kiro-cli.
Co-authored-by: Vladislav Aranov <vladislav.aranov@ericsson.com>
* Add a few tests for when a mapper does something like `map(s.p[0:10])`
where `p` is a pointer.
* Add a few tests that require propagation of bits like `present/always`
into a mapper.
* Fix a few tests that were expecting `p` to be mapped when the mapper
only said `map(s.p[0:10])`.
The output of a few tests is different from what we expect. They have
been annotated with FIXMEs, and the expected output for when the
follow-up changes in this stack to propagate the map-type-modifier bits
and using attach-style mapping for mappers get merged.
---------
Co-authored-by: Claude Opus 4.8 <noreply@anthropic.com>
Reverts llvm/llvm-project#196656
The CI does not yet build compiler-rt with SPIR-V support, so
libclang_rt.builtins.bc is absent on that bot. This change made the
missing file a hard error, breaking all libsycl functional tests that
compile with -fsycl.
Re-landing after CI is updated to build compiler-rt for SPIR-V.
PPC was emitting a "float-abi" module flag for indicating the type of
long double. The "float ABI" naming is already widely taken by soft vs.
hard float controls (e.g., the clang flag is called -mfloat-abi), so this
shouldn't have taken it. This should also not be PPC specific; x86 has
the same problem. Rename the flag to the more specific
long-double-type, and add appropriate verification and documentation
(which was also missing). Also changes the value names to match the IR
type names.
Co-authored-by: Claude (Claude-Opus-4.8) <noreply@anthropic.com>
`ClangScanDeps/logging-two-threads.c` is flaky. It asserts each module's
timestamp is written exactly once, but under
`-fmodules-validate-once-per-build-session` two workers scanning
different TUs can both notice the shared module is unvalidated this
session and each validate and record it before the other's write lands,
so its timestamp is written once or twice depending on the interleaving.
The double write is harmless: the timestamp field is atomic and both
workers store the same session time. Only the exact-count assertion was
wrong.
Relax the test to the real invariant: the shared module A is written
once or twice and the single-TU module B exactly once. Module compile
and pcm write stay exactly once (the in-memory cache builds each module
once) and the per-module event ordering is still checked by the sequence
blocks.
The redundant validation itself (two workers validating the same module)
is a separate, pre-existing issue noted by the validation-lock TODO in
`ModuleCache.h`; I plan to look at that separately.
AI assistance: drafted with AI help; reviewed and validated by me.
The x86_64 calling-convention bridge rejected every integer wider than 64
bits, so a function taking or returning `__int128` hit `errorNYI` even though
its ABI treatment is simple.
On x86_64 `__int128` is Direct and passes in a pair of integer registers,
matching an i128 argument or return in classic CodeGen. `isSupportedType` now
accepts non-bitint integers of width 128 alongside the register-sized widths.
A struct holding a single `__int128` is exactly two eightbytes, so it reaches
the aggregate path and is Direct-coerced to i128; a struct spanning more than
two eightbytes stays Indirect (byval/sret).
`_BitInt` stays rejected pending its register-pair coercion and padding
handling, including `_BitInt(128)`. Non-C intermediate widths (65..127) stay
rejected too: the scalar Direct branch would pass them through unchanged,
without the register-pair coercion they would need.
This patch fixes a bug in handleMSPointerTypeQualifierAttr and
HandleWebAssemblyFuncrefAttr where applying these pointer attributes
would implicitly drop top-level CV qualifiers (like `const`, `volatile`,
and `restrict`) from the pointer type.
A doc comment can contain invalid UTF-8. The raw bytes reach
serializeDocComment, which assigned them to a llvm::json::Value,
tripping its valid-UTF-8 assertion. This is hit by legacy headers that
are not UTF-8 encoded, which compile fine but crash -extract-api.
Sanitize with json::isUTF8/fixUTF8 before serializing.
Fixes#212393
Capability attributes on a parameter mean one of two unrelated things:
on a scoped-lockable parameter they describe the locks the passed scope
object holds, while on a function pointer parameter they describe the
requirements of the function called through the pointer. Since #191187
allowed the latter, both of the scoped-lockable code paths have been
misreading function pointer parameters as scope objects.
At a call site, the argument bound to the parameter was translated into
a capability and required to be held, so passing a callback that
requires a capability was reported as a missing lock named after the
callback:
```
void apply(fn_t fn EXCLUSIVE_LOCKS_REQUIRED(mu));
static int my_fn() EXCLUSIVE_LOCKS_REQUIRED(mu);
...
apply(my_fn); // warning: requires holding mutex 'fn'
```
In the callee, the same confusion seeded the parameter's capabilities
into the function's entry lockset, so they were considered held
throughout the body and the calls made through the pointer went
unchecked -- the opposite of what the annotation asks for.
Skip function pointer parameters in both places; their attributes are
already checked at the indirect call sites (by #191187), the same way as
for annotated function pointer variables and fields.
Assisted-by: Claude Opus 5
Store selector name location alongside the existing @-sign and paren locations, exposed via getSelectorLoc(), so tools and diagnostics can reference the name rather than the @selector keyword. While here, rename things to disambiguate locations.
A global on the `llvm.used`/`llvm.compiler.used` list can be deleted
before the module is released: CodeGen erases an unreferenced
`GlobalValue` without RAUW when the same mangled name is redefined with
a different type (`GetOrCreateLLVMGlobal`), which nulls the
`WeakTrackingVH` on the used list — value handles are not uses, so the
`use_empty()` guard does not protect them.
In whole-TU compilation this is unobservable because the accompanying
`err_duplicate_mangled_name` suppresses `Release()`. The incremental
interpreter, however, clears the diagnostic state after the failed parse
and keeps building the same module, so the next successful parse runs
`Release()` and crashes in `emitUsed` dereferencing the dead handle:
```
clang-repl> __attribute__((used)) int a asm("sym") = 1; float b asm("sym") = 2.0f;
clang-repl> int ok = 0;
clang-repl: .../ValueHandle.h:95: llvm::Value& llvm::ValueHandleBase::operator*() const: Assertion `V && "Dereferencing deleted ValueHandle"' failed.
```
Out-of-tree incremental clients hit the same crash through other routes
that delete an emitted used global before module release (e.g.
CppInterOp's force-emission of reflection queries, see
compiler-research/CppInterOp#1068).
Fix: skip null handles when building the used array. The repro above is
included as a lit test; `clang/test/Interpreter`, `clang/test/CodeGen`,
and `clang/test/CodeGenCXX` pass locally.
🤖 Done with the help of [Claude Code](https://claude.com/claude-code)
(Fable 5, human in the loop)
Co-authored-by: Emery Conrad <emery.conrad@chicagotrading.com>
This PR implements compile-time device library linking for SYCL
offloading to SPIR-V targets, using `libclang_rt.builtins.bc` - an
in-tree compiler-rt artifact produced alongside the existing
`libclang_rt.builtins.a` for `SPIRV64`.
## Motivation
SYCL device compilations targeting SPIR-V need access to compiler
builtins (integer arithmetic, floating-point helpers, etc.) at compile
time so the compiler can optimize across user code and builtins, inline
aggressively, and eliminate dead code. This PR lays the foundation by
wiring up the first in-tree device library : `libclang_rt.builtins.bc` -
using the same `-mlink-builtin-bitcode` mechanism already used by
`libclc` and `HIP`.
## Changes
**compiler-rt (compiler-rt/lib/builtins/CMakeLists.txt)**
For the `spirv64` target, after building
`libclang_rt.builtins-spirv64.a`, runs `llvm-link` to merge all bitcode
objects into a single `libclang_rt.builtins.bc`. This file is installed
to `<ResourceDir>/lib/spirv64-unknown-unknown/` alongside the static
archive. The `-mlink-builtin-bitcode` flag requires raw LLVM IR and
cannot unpack a static archive directly, hence the extra step.
**Clang Driver (clang/lib/Driver/ToolChains/SYCL.cpp)**
`SYCLToolChain::getDeviceLibs()` now constructs the path to
`libclang_rt.builtins.bc` under the clang resource directory and returns
it for `-mlink-builtin-bitcode` injection during `spirv64` device
compilation. If the file is absent (e.g. compiler-rt was not built with
spirv64 support), a specific diagnostic is emitted. Linking is
suppressed when `--no-offloadlib` is passed.
**Diagnostics (clang/include/clang/Basic/DiagnosticDriverKinds.td)**
Added `err_drv_no_compiler_rt_builtins_bc`, following the
`err_drv_libclc_not_found` community pattern, with actionable guidance
on how to build compiler-rt with SPIR-V support.
### Test Infrastructure
1. `clang/test/Driver/sycl-device-lib-spirv64.cpp` - new test verifying
-mlink-builtin-bitcode is passed for spirv64, suppressed with
--no-offloadlib, and that a missing .bc produces the correct diagnostic.
2. `clang/test/Driver/Inputs/spirv64-sycl/` - dummy resource-dir fixture
used by driver tests.
3. All existing SYCL driver tests updated to pass -`resource-dir
%S/Inputs/spirv64-sycl `on -fsycl RUN lines, making them independent of
the installed clang resource directory on CI runners.
## Behavior
### Default
```bash
clang -fsycl myprogram.cpp
# Device compilation includes:
# "-mlink-builtin-bitcode" "<ResourceDir>/lib/spirv64-unknown-unknown/libclang_rt.builtins.bc"
```
Automatically links device libraries from `<clang-install>/lib/` during
device compilation.
### Without device libraries
```bash
clang -fsycl --no-offloadlib myprogram.cpp
# -mlink-builtin-bitcode is suppressed
```
Missing .bc (compiler-rt not built with spirv64 support)
```bash
error: no compiler-rt builtins bitcode library '...' found in the clang resource directory;
build compiler-rt with SPIR-V support or pass '--no-offloadlib' to compile without it ```
The new offload driver packages multi-architecture bitcode in LLVM
offload binaries. A later `--hip-link --offload-device-only`
invocation treated these `.bc` inputs as host LLVM IR and dropped
them before linking.
Pass these inputs directly to clang-linker-wrapper when producing a
device fat binary. The wrapper can then extract and link each
requested GPU architecture.
Unsurprisingly, this manually maintained table is buggy.
fillAMDGCNFeatureMap never set extended-image-insts, so clang's builtin
feature check rejected every case. The tests were working around this
with manually specified -target-features flags.
Co-authored-by: Claude (Claude-Opus-4.8)
No GPU ever sets these bits, and clang's hasFP64()/hasLDEXPF()
short-circuit on isAMDGCN() before testing them, so the bits are
never observed.
Co-authored-by: Claude (Claude-Opus-4.8)
`ParseDeclaratorInternal's` member-pointer special case enters a
speculative scope-specifier parse whenever it sees `decltype`, without
checking that `( `follows:
```
if (getLangOpts().CPlusPlus &&
(Tok.is(tok::coloncolon) || Tok.is(tok::kw_decltype) || ...)) {
```
But `decltype-specifier` is always `decltype ( expression ) — decltype`
not followed by `(` can never be valid. When that happens,
`ParseOptionalCXXScopeSpecifier` still tries to parse it as one, fails,
and error recovery skips tokens. The EndLoc returned is then stale by
the time `AnnotateExistingDecltypeSpecifier` uses it to annotate, which
trips the invariant in `Preprocessor::AnnotatePreviousCachedTokens`:
```
int decltype; // crashed
int *decltype = 0; // crashed
```
Fix: only take this path when decltype is followed by (.
`(Tok.is(tok::kw_decltype) && NextToken().is(tok::l_paren)) ||`
`ParseDecltypeSpecifier` already requires `(` right after `decltype` or
bails with `TST_error`, so this check drops no valid parse —
`decltype(expr)` (including as a member-pointer scope, e.g.` int
decltype(obj)::*p = &S::m;) `is unaffected.
Fixes#211207
Co-authored - Claude-Sonnet
Try-locks are not acquired on the arms of a `?:`, because the arms would
then disagree about whether the capability is held and warn where they
join. That reasoning assumes the `?:` produces a result that is branched
on later, which is where the acquisition is handled instead.
A void `?:` has no such result. Its branch is all there is to interpret,
and its arms might not join at all because one of them does not return
(this is how glibc before 2.32 spells `assert()`).
So asserting that a try-lock succeeded left the capability unheld on
every path, and a function documented to acquire it warned that it did
not, if written like so:
void lock(void) ACQUIRE(mu) {
int got = trylock();
assert(got); // warning: expecting mutex 'mu' to be held at the end of
function
}
Only bail out for a `?:` that has a result to be used, so that a void
`?:` acquires on its branch like any other terminator (for example,
including `&&` and `||`).
Assisted-by: Claude Opus 5
ExpressionTraits.h defines utilities such as `getTraitName`,
`getTraitSpelling` and an enumeration for expression traits. All other
overloads of these utilities can be found in TypeTraits.h - this patch
combines them to BuiltinTraits.h/cpp.
This is a followup patch for
https://github.com/llvm/llvm-project/pull/201491#discussion_r3460883247
After the parameter declaration of a lambda expression, `Sema` enters
the declaration context of the lambda call operator (in
`ActOnLambdaClosureParameters`), so the lambda specifiers and the
trailing return type are analyzed within that context. Because of this,
predefined expressions such as `__func__` resolve to the lambda call
operator, and not to the possibly enclosing function. (issue #122657)
Added a member to `LambdaScopeInfo` to mark whether or not the compound
statement of the lambda expression has been entered, to be used when
resolving a `PredefinedExpr`
Extracts cache insertion logic from `IsValueInFlagEnum`. This allows us
to drop `mutable` on `FlagBitsCache` while making it reusable as work
list for additional flag_enum diagnostics.
Represent `default_func_attrs` on `LLVM::InvokeOp` and translate the
collection onto the generated LLVM invoke instruction. Preserve default
call-site attributes when throwing calls are lowered through the LLVM
dialect, including CIR `try_call` operations.
Use __builtin_convertvector for pncvt and __builtin_shufflevector for
pncvth.
Alternatively we could use shift+__builtin_convertvector for pncvth but
that requires combining psrl+unzip(8/16)p to unzip(8/16)hp. I'm not sure
which is better right now.
A class-type non-type template parameter is represented in the AST by a
TemplateParamObjectDecl, which has an empty DeclarationName.
USRGenerator had no visitor for it, so it fell through to
VisitNamedDecl, where EmitDeclName fails on the empty name and sets
IgnoreResults. That discarded the USR of the enclosing declaration.
Add a visitor that encodes the parameter object's type and value, so
specializations on distinct values get distinct USRs and equal values
agree.
Fixes#212351
An external layout source (such as LLDB reading DWARF) supplies a
record's final alignment directly, since `alignas` / `__declspec(align)`
attributes are not recoverable from debug info. `finalizeLayout`
captured `NonRequiredAlignment` before applying the external alignment,
so an externally laid out record published a stale, too-small value.
On Arm64 this field is used to fold a base's alignment into the derived
record, so a derived class picked up the stale value instead of the
base's actual alignment. This regressed
`lldb/test/API/lang/cpp/alignas_base_class` when #210461 was merged,
where `alignof(Derived)` evaluated to 1 instead of 8. Other targets were
unaffected as they do not read this field.
Treat all of an externally supplied alignment as non-required, as there
is no way to tell how much of it was imposed by an alignment attribute.
With the introduction of offloading via LLVM, the frontend language will
not necessarily determine the backend target anymore. Thus it is
necessary to guard against NVPTX instead of CUDA, since we could have
CUDA-language device code targeting a non-NVPTX backend, where Clang
does not provide __syncthreads as an NVPTX builtin and the generic shim
is still needed.
This also avoids duplicate definitions on NVPTX. Clang already provides
`__syncthreads` as an NVPTX target builtin, so
`__clang_gpu_device_functions.h` should not also define an inline
`__syncthreads` shim for NVPTX targets.
Currently, the `OptionalUnsigned(int) = delete;` constructor means that
constructing e.g. an `OptionalOrUnsigned<uint64_t>` from an `unsigned`
fails because overload resolution is ambiguous (because `unsigned` ->
`int` and `unsigned` -> `uint64_t` are both valid conversions). This
patch adds a constraint to make sure the deleted constructor only
catches signed integer types.
This is needed for #212319.
When targeting aarch64-pc-windows-msvc, clang laid out a base following
an over-aligned, non-standard-layout base at the wrong offset. MSVC on
Arm64 reuses the over-aligned base's tail padding for the subsequent
base, but clang rounded the base up to a full slot, so the two disagreed
on member offsets, breaking interop between clang- and MSVC-built
binaries.
Fix: store each record's natural non-virtual alignment (excluding
`alignas`/`__declspec(align)` over-alignment) as
`getNonRequiredNVAlignment()`, and on Arm64 fold in a base's natural
alignment rather than its full alignment. This is gated to Arm64 only;
Arm64EC and x64 follow the x64 rule (no reuse) and are unchanged.
Validated against MSVC (Hostx64\arm64\cl.exe
/d1reportSingleClassLayout): clang now matches MSVC Arm64 exactly for
the reduced repro, the original polymorphic case (vftable + empty base +
template), and a range of probe cases covering natural vs.
over-alignment padding and field vs. base reuse. Arm64EC and x64 output
is byte-identical to before.
Fixes#210174
Improve dangling value tracking in the `DanglingPtrDeref` checker by
adding `trackExpressionValue`. The report with this change now tracks
the dangling value and shows where the value originated from. Currently
the checker only points at the destruction and use sites which isn't
always useful for the user.
Abstract declarator contexts (specifically `DeclaratorContext::TypeName`) now properly bypass this restricted rule, allowing cv-qualified function types in `__typeof__` while maintaining restrictions in other contexts like `typeid`, `sizeof`, C-style casts, and `new` expressions per CWG1417.
In Clang Tooling, escape HeaderStem before constructing MainIncludeRegex
to prevent special characters (such as '+') from being interpreted as
regex operators. Useful for Objective-C where "Foo+Bar.h" headers are
very common for categories.
```
int foo(){
int i = 42;
int j = 43;
auto l1 = [x = i, &j ](){};
}
```
in the lambda capture:
- `x` is visited as VariableRef (referencing an unvisited VarDecl at the
same location)
- `i` is visited as DelcRefExpr (fair enough, same as in an assignment)
- `j` is visited as VariableRef
Visit `x` as a `VarDecl`, and stop visiting it as a `VariableRef`, as it
makes no sense (referencing itself at an unvisited cursor).
---------
Co-authored-by: Serafean <Serafean@users.noreply.github.com>
StringRef assertion fires up when passing wide literals to
`__builtin_nanf()`.
The patch updates the `TryEvaluateBuiltinNan` method to reject
non-narrow string literals preventing the downstream assertion failure
caused by `getString()` in cases where the user might pass a non-narrow
/ non 1 byte literal."
Fix#205306
Rename `insertDbgValueIntrinsic` to `insertDbgValue`, which is
consistent with the other insert helpers like `insertDbgAssign`,
`insertDeclare`, etc.
Also use debug record instead of intrinsic terminology in doc comments.
This is part of the commit series that gradually eliminates the class
`NodeBuilder` from the analyzer engine.
This is a straightforward case where `makeNodeWithBinding` can be
clearly applied.
The node set `Tmp` was superfluous because we can directly pass the node
to `runCheckersForPostStmt` where it will be implicitly converted to a
one-element set. (There are many precedents for this.)
Also notice that we explicitly pass the `State` to `makeNodeWithBinding`
because it can be different from `Pred->getState()` (which would have
been used implicitly by the 4-argument form of `makeNodeWithBinding`.)
On top of updating the status page, this PR updates the `latest_release`
constant to 22 and fixes a small `cwg_index.html` parsing issue that
arose during the update.
The implementation is quite straightforward. Compared to the FP or GP
register implementations, the main difference is that we need to
configure the vector registers before clearing them.
Now that the backend supports clearing all standard registers, this
patch makes the clang driver accept all -fzero-call-used-regs options.
This patch switches the Checker's expiry and invalidation checks to use
`AccessPath::isPrefixOf` instead of equality (`==`).
Since all generated access paths are currently empty, `isPrefixOf` is
behaviourally identical to `==` (NFC). This prepares the checker to
handle nested paths (fields and container interiors) in subsequent
commits.
Replace the legacy amdgcn architecture name with amdgpu in various
test triples. This set of updates covers cases that did not have
a set -target-cpu.
Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
(#180369)
This patch refactors the internal representations of `AccessPath` and
`Loan` to support path elements, preparing for field-sensitive and
interior-sensitive lifetime tracking.
* Introduces `PathElement` representing a field or interior dereference.
* Refactors `AccessPath` to contain a base and a list of `PathElement`s.
* Updates `Loan` and `LoanManager` to use the new `AccessPath`
structure.
---
Old PR description:
Refactor loan representation to use structured access paths, enabling
more precise borrow tracking and detection of use-after-invalidation.
Previously, loans were associated only with top-level storage (e.g., a
variable `x`, temporary `t`). This was insufficient for reasoning about
borrows of sub-objects (interior memory regions), such as fields (`x.f`)
or container elements (`vec[0]`), or for modelling views like
`string_view` which borrow the interior of an object.
We modify `AccessPath`, which now consists of a `base` (a _variable_,
_temporary_, or _placeholder_ for _parameters/'this'_) and a sequence of
`PathElements`. A `PathElement` can be a field access (`.field`) or an
interior access (denoted as `.*`), representing an unnamed interior
memory region of an object, like the character buffer of a
`std::string`.
High-level changes:
* `PathLoan` and `PlaceholderLoan` are merged into a single Loan class,
containing an `AccessPath`.
* **Path-Based Expiry**: `ExpireFact` is changed from expiring a single
loan to expiring an `AccessPath`. If `x` goes out of scope, any loan
whose path starts with `x` (e.g., loans to `x`, `x.field`, `x.field.*`)
is now considered expired. The checker uses `isPrefixOf` to detect this.
* **Path Extension in Flows**: `OriginFlowFact` now supports extending
loan paths:
* Field access like for expression `obj.field` extends loans to `obj`
into loans to `obj.field`.
* Owner-to-view conversions like `std::string_view s(str)` extend loans
to `str` into loans to `str.*`.
* **Invalidation**: Container invalidation methods (e.g.,
`vec.push_back()`) invalidate loans whose path is a strict extension of
the container's path (e.g., loans to `vec.*` but not loans to `vec`).
The checker uses `isStrictPrefixOf`.
* **Move-Tracking**: Moves are now tracked based on path prefixes via
`isPrefixOf`.
This refactoring enables detection of use-after-invalidation bugs for
STL containers specially when the container appears as fields.
Move the coroutine tests into a dedicated CodeGenCoroutines directory.
This is a test only reorganization in preparation for upcoming
coroutine-related changes.
CompoundAssignOperator (e.g. `+=`, `-=`, `<<=`) is a distinct StmtClass
deriving from BinaryOperator, but it was not handled in the CFGBuilder
dispatch switches. As a result it fell through to the generic default
path (VisitChildren over reverse_children), which emits the LHS before
the RHS in the CFG.
Per C++17 [expr.ass]/1, all assignment operators - simple and compound -
sequence the right operand before the left operand. Route
CompoundAssignOperator through VisitBinaryOperator (and
VisitBinaryOperatorForTemporaries), whose existing isAssignmentOp()
branch already emits the RHS before the LHS, matching simple assignment.
This mirrors the class of evaluation-order defect fixed for lambda
captures in f3b31871e9.
rdar://183253943
Assisted-By: claude
This PR fixes _Atomic crashes for Z3 symbolic execution by passing the
types through getAtomicUnqualifiedType and getCanonicalType and skip
casting in fromCast if `FromTy == ToTy && FromBitWidth == ToBitWidth`.
Assisted-by: Codex
Previously, the captures were emitted in their spelling order - but in
the CFG that gets translared in a reversed order.
Because of this, we need to emit them in reversed order to get them
appear in their natural order.
Fixes rdar://183140177
Commit 68f703f3e5 added these release
notes, but this commit was backported to the 23.x release branch in
47e2df730a (included in the 23.1.0 RC 1
tag).
Therefore, remove these release notes from the main branch (where they
would have been included in the 24.x release notes).
This fixes running a new test that was added in
4b66bacd1f, in mingw environments.
The quirks that warranted adding the `!defined(_WIN32)` condition in the
test aren't actually specific to Windows in general, but specific to
MSVC environments - mingw environments behave just like other platforms.
Ideally we'd use `!defined(_MSC_VER)`, however in -cc1 mode, Clang
doesn't automatically define `_MSC_VER`; defining it requires setting a
command line option that the driver normally passes in MSVC mode.
Therefore, qualify the condition as `!defined(_MSC_VER) ||
defined(__MINGW32__)`.
The current interpreter doesn't do this either. If we do, the clang
build fails because AMDGPUGenGlobalISel.inc: contains a global constexpr
array called MatchTable0 with 1'926'005 elements.
Migrate the OpenMP offload cc1 tests to the new amdgpu triple scheme:
* -fopenmp-targets=amdgcn-amd-amdhsa ->
-fopenmp-targets=amdgpu-amd-amdhsa
(the offload toolchain triple, the generic amdgpu arch).
* The device -triple amdgcn-amd-amdhsa -> amdgpu-amd-amdhsa, or to the
specific subarch triple (dropping -target-cpu) where a -target-cpu was
present.
Autogenerated CHECK lines are regenerated, and the few -Wopenmp-target-
exception diagnostics that embed the triple string are updated. Tests
that
intentionally assert the "target-cpu" function attribute are left
unchanged.
Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
Rewrite the second half of CodeGenOpenCL cc1 test RUN lines to the new
subarch triple form, dropping the redundant -target-cpu.
Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
Even if the static analyzer is disabled, it still gets built into the
dylib. Unit tests and tools already get disables, so also stop building
the library. This reduces the time needed to build a dylib clang by
8-9%.
Rewrite the first half of CodeGenOpenCL cc1 test RUN lines to the new
subarch triple form, dropping the redundant -target-cpu.
Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
In C++20 (P1008R1 https://wg21.link/p1008r1), aggregates are prohibited
from having any user-declared constructors, even if they are = delete or
= default.
Fixes https://github.com/llvm/llvm-project/issues/209787
It was an oversight that the builtin only takes care of the virtual
function table pointer but not the virtual base pointer. On Itanium
there is one pointer so it wasn't a problem but on windows msvc , this
is a problem. And the runtime test in libcxx CI was disabled in llvm 23
because we don't use trunk clang in our libcxx CI in general. and after
we flipped to llvm 24, the test started to fail on downstream (chromium)
where they use trunk clang with trunk libc++ on Windows.
We do have FileCheck test in clang test which covers this virtual case.
However, the target triple in the FileCheck under test were
`x86_64-linux-gnu` and `x86_64-windows-gnu` , which does not cover the
Windows msvc ABI. I updated the test to test `x86_64-pc-windows-msvc` in
this PR to cover that ABI.
Rewrite SemaHIP cc1 test RUN lines to the new subarch triple form,
dropping the redundant -target-cpu.
Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
The patch resolves the following warning.
```bash
clang/lib/StaticAnalyzer/Checkers/RetainCountChecker/RetainCountDiagnostics.cpp:504:16: warning: variable ‘i’ set but not used [-Wunused-but-set-variable=]
504 | unsigned i = 0;
| ^
```
A count variable was set and incremented inside of a for loop but never
actually used inside of the loop or anywhere else in its scope.
This patch adds CIR support for the following atomic builtin functions:
- `__atomic_fetch_fmaximum`
- `__atomic_fetch_fminimum`
- `__atomic_fetch_fmaximumnum`
- `__atomic_fetch_fminimumnum`
The scoped versions of these atomic builtin functions are supported as
well.
Specifically, this patch contains the following changes:
- It updates the `cir.atomic.fetch` operation and adds new fetch
operators including `maximum`, `minimum`, `maximumnum`, and
`minimumnum`. These operators accept floating-point inputs only.
- It updates the LLVM lowering of the `cir.atomic.fetch` operation. The
LLVM lowering now will lower `maximum`, `minimum`, `maximumnum`, and
`minimumnum` atomic fetch operators to the corresponding LLVM
`atomicrmw` operations, which are `fmaximum`, `fminimum`, `fmaximumnum`,
and `fminimumnum`, respectively, aligning with the OGCG behavior.
- It updates the CIRGen path for atomic operations and add supports for
these atomic builtin functions.
Assisted-by: GitHub Copilot / gpt-5.4 xhigh
Exclude casts precisely matching `this` and `*this` (through
parens/implicit casts), without matching member accesses like
`this->m_field`.
rdar://173770064
Currently the `DanglingPtrDeref` checker only records the whole object's
region as deallocated. However, dangling pointers often refer to
subobjects (e.g., a struct field or an element of an array). With the
change in this PR, `isDeallocated` now checks whether a region's base
region is in the `DeallocatedSourceSet`.
In `BuildReturnStmt()`, use `getCurFunctionDecl()` to get the current
function rather than attempting to cast `CurContext` to a
`FunctionDecl`, which breaks inside an expansion statement because the
current `DeclContext` will be that of the expansion statement, not the
function. `getCurFunctionDecl()` knows how to handle this case and we
already call it earlier in that function, so just reuse the result of
that call.
Fixes#211917.
Rewrite the remaining small test directories (CodeGenCXX, Misc, Sema,
SemaCUDA, SemaCXX) cc1 RUN lines to the new subarch triple form,
dropping the redundant -target-cpu.
Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
Rewrite CIR/CodeGenHIP cc1 test RUN lines to the new subarch triple
form, dropping the redundant -target-cpu, and regenerate autogenerated
CHECK lines.
Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
Previous contributions added alias analysis and strengthened soundness
by invalidating out-parameters in beta mode. The latter feature
introduced a distinction between the contexts before and after a
function call, because the invalidation assumes that an argument passed
by pointer or reference may be changed by the function.
This requires two-state semantics for handling function attributes.
Specifically, AcquireCapability and AssertCapability, which both ensure
that some locks are held after the call, should be associated with the
post-state. Other function attributes, like RequireCapability or
ReleaseCapability, are associated with the pre-state.
This commit implements these semantics. This change only affects beta
mode.
A previous discussion about these semantics:
https://github.com/llvm/llvm-project/pull/190154
rdar://171209196
This bug showed up as a failed assertion that was asserting that if
not in a function or method context we should be in the global/file
context.
The root cause is that when determining the linkage context for a
decl we were failing to account for the existence of expansion
contexts. Ignoring the assertion failure, the functional effect of
this is that we would fail to detect incorrect local extern
declarations inside expansion contexts. The fix here is to make
sure that we use `getEnclosingNonExpansionStatementContext()` to
find the true DeclContext for the current scope.
The initial report only identified local extern function declarations
but the same bug occurred with extern var decls, but the path did
not lead to an assertion firing, just incorrect behaviour.
Thanks to Sirraide for explaining why this was going wrong, and
confirming this was the correct fix.
Also fixes#211912
This establishes a new canonical predefine for *-fuchsia targets:
`__Fuchsia_Compiler_ABI__` is set to an integer for the version
number of the Fuchsia Compiler ABI the compiler supports. The
value will change as appropriate with changes to *-fuchsia target
ABI expectations. It is not anticipated that the compiler will
support selecting target ABI versions, only the latest as the
canonical target-specific behavior. Fuchsia Compiler ABI
versions are unrelated to the Fuchsia API levels supported by
Fuchsia systems; newly-built programs may target older API levels
with `-ffuchsia-api-level`, but everything relying on the Fuchsia
Compiler ABI is built and deployed together as an isolated unit.
Rewrite OpenMP cc1 test RUN lines to the new subarch triple form,
dropping the redundant -target-cpu, and regenerate autogenerated CHECK
lines. Tests that intentionally assert the "target-cpu" attribute are
left unchanged.
Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
Guard hasTagDefinition() against invalid type-specifier state so
recovery from invalid auto/tag combinations does not assert.
Fixes#210014
---------
Signed-off-by: Osama Abdelkader <osama.abdelkader@gmail.com>
Changes: The patch was originally landed as af0c933e (#209465), but
there was an issue with strictfp functions being inlined into
non-strictfp functions. The issue has since been resolved by a2b42b10a
([IR] Reject inlining strictfp alwaysinline callee into non-strictfp
caller, #210701) and the re-land is identical.
Although the section on constrainedfp in the LangRef clearly states "All
function definitions that use constrained floating point intrinsics must
have the strictfp attribute", indicating that a function with strictfp
calls must be marked with strictfp, the general description of strictfp
does not specify this. Refine its semantics and make it so, eliminating
the inconsistency.
Adds CIR codegen support for the NVVM global uniform load builtins
`nvvm_ldu_*` ,including the integer, floating-point, and vector
variants.
These are lowered to the corresponding `llvm.nvvm.ldu.global.*`
intrinsics based on the pointee type.
Rewrite Headers cc1 test RUN lines to the new subarch triple form,
dropping the redundant -target-cpu, and regenerate autogenerated CHECK
lines.
Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
Currently if the compiler install is not under SYSROOT, we don't try to
compute the relative path to `libLLVMSYCL.so` based on the compiler
binary installation directory, resulting us never setting
`SYCLRTLibPath` so when we try to geenerate a linker call we get a raw
`libLLVMSYCL.so` which fails unless the user happens to be running the
compiler from a directory with `libLLVMSYCL.so` inside it.
It seems we never use the result from SYCLInstallationDetector on
Windows, so I can't add a test, however change the code to be consistent
in case we start to use it in the future.
---------
Signed-off-by: Nick Sarnie <nick.sarnie@intel.com>
Reverts llvm/llvm-project#210154
Broke some build bots.
https://github.com/llvm/llvm-project/pull/210154#issuecomment-5071830822https://lab.llvm.org/buildbot/#/builders/144/builds/60200
```
# | error: 'expected-error' diagnostics seen but not expected:
# | File /home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/llvm-project/clang/test/Analysis/string-search-modeling.c Line 515: use of undeclared identifier 'u'
# | File /home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/llvm-project/clang/test/Analysis/string-search-modeling.c Line 527: use of undeclared identifier 'u'
# | File /home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/llvm-project/clang/test/Analysis/string-search-modeling.c Line 538: use of undeclared identifier 'U'
# | File /home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/llvm-project/clang/test/Analysis/string-search-modeling.c Line 550: use of undeclared identifier 'u'
# | File /home/buildbot/buildbot-root/llvm-clang-x86_64-sie-ubuntu-fast/llvm-project/clang/test/Analysis/string-search-modeling.c Line 578: use of undeclared identifier 'u'
```
Rewrite CodeGenHIP cc1 test RUN lines to the new subarch triple form,
dropping the redundant -target-cpu, and regenerate autogenerated CHECK
lines. Tests whose behavior depends on the implicit wave32 default
(which is not enabled by a bare subarch triple) are left for a later change.
Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
Rewrite CodeGenCUDA cc1 test RUN lines from `-triple amdgcn...
-target-cpu gfxNNN` to the new subarch triple form, dropping the redundant
-target-cpu.
Autogenerated CHECK lines are regenerated. Tests that intentionally
assert the "target-cpu" function attribute are left unchanged.
Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
Mechanically rewrite cc1 test RUN lines from the old
`-triple amdgcn... -target-cpu gfxNNN` form to the new subarch triple
form (e.g. `-triple amdgpu9.00-amd-amdhsa`), dropping the now-redundant
-target-cpu. The subarch encodes the exact target, so the emitted IR no
longer carries a "target-cpu" function attribute; autogenerated CHECK
lines are regenerated accordingly.
This batch covers the small CodeGen, Frontend, Layout, and Preprocessor
test directories.
Co-authored-by: Claude (Opus 4.8) <noreply@anthropic.com>
When both the source string and the search target are compile-time
constants, determine the outcome precisely and only emit the feasible
branch (found or not-found).
Handles strchr, strrchr, strchrnul, memchr, strstr, and strpbrk.
Fixes#209905
Assisted by: Kiro-cli
---------
Co-authored-by: Vladislav Aranov <vladislav.aranov@ericsson.com>
The CoroSplit and CoroFrame generate several control flow instructions
(`br`, `select`, `switch`) that previously lacked `!prof` branch weight
metadata.
When a coroutine is split, most basic blocks are simply cloned into the
generated functions (`.resume`, `.destroy`, and `.cleanup`) and don't
actually change their internal structure or layout. This PR changes:
1. Dispatch Branch Weights:
Since the original coroutine already ran through PGO, we already have
the `SuspendFreqs` records telling us exactly how many times each
suspension point was executed in the real world.
In the new clone `.resume` functions, the compiler generates new routing
`switch` instruction to direct the traffic. Instead of guessing the
probabilities for these new routes, we simply look back at the
`SuspendFreqs` records, calculate the exact execution frequency and
directly onto the new routing `switch` instructions as `!prof` data.
2. Function Entry Count:
We compute the entry count for the generated `.resume` function by
summing up the frequencies of all suspension target blocks, ensuring the
`.resume` function's entry metadata accurately reflects its true
invocation frequency rather than inheriting original counts. Two new
test cases is added see:
```
llvm/test/Transforms/Coroutines/coro-split-resume-entry-count-no-suspend.ll
llvm/test/Transforms/Coroutines/coro-split-resume-entry-count.ll
```
3. Others updates add branch weight metadata in several locations within
these passes:
* **CoroSplit.cpp**:
* `handleFinalSuspend`: Added an equal (50/50) weight to conditional
branches handling final-suspend conditions via
`setExplicitlyUnknownBranchWeightsIfProfiled`.
* `updateCoroFrame`: Adds an equal (50/50) weight to the select
instruction that chooses either the `destroy` or `cleanup` function by
using `setExplicitlyUnknownBranchWeightsIfProfiled`.
* **CoroFrame.cpp**:
* `rewritePHIsForCleanupPad`: Adds a branch weight of {0, 1, 1} to
two-way switch instructions driven by PHI nodes generated in the EH
dispatch block (.corodispatch). This provides accurate probabilistic
information for `SimplifyCFG`, which typically translates such `switch`
```
cleanup2.corodispatch: ; preds = %catch.dispatch.2, %handler2
%1 = phi i8 [ 0, %handler2 ], [ 1, %catch.dispatch.2 ]
%2 = cleanuppad within %h1 []
switch i8 %1, label %unreachable [
i8 0, label %cleanup2.from.handler2
i8 1, label %cleanup2.from.catch.dispatch.2
]
```
into `icmp` + `br`.
```
cleanup2.corodispatch: ; preds = %catch.dispatch.2, %handler2
%1 = phi i8 [ 0, %handler2 ], [ 1, %catch.dispatch.2 ]
%2 = cleanuppad within %h1 []
%3 = icmp eq i8 %1, 0
br i1 %3, label %cleanup2.from.handler2, label
%cleanup2.from.catch.dispatch.2
```
* **CoroCleanup.cc**
* Setting the `unknown` profile to `NoopFn`/`__NoopCoro_ResumeDestroy`
to avoid the false warnings. because this function is generated by this
the pass, PGO has no profile count for it.
Co-authored-by: Jin Huang <jingold@google.com>
Allow `i128` values to be used with the `f` inline assembly constraint
when targeting LSX.
Although `i128` is not a legal LSX value type, it naturally maps to a
single 128-bit LSX vector register for inline assembly. This enables
instructions such as `vadd.q` to operate directly on `__int128` operands
without requiring explicit vector types.
Users and tools sometimes need to know which C++ standard library Clang
selected, and which include directories the driver added for it. Today
they have to inspect verbose or `-###` output.
Add options to print this information directly:
`--print-cxx-stdlib`
`--print-cxx-stdlib-include-dirs`
For MSVC targets, the default printed library is `msvcstl`. Explicit
`-stdlib=` values are still reported as requested. The include-dir query
reuses toolchain logic, including the MSVC STL include path for the
default MSVC case.
ASan emits a symbol for a static global in `TestTransformation.cpp` that
causes link issues in green dragon.
Added `__attribute__((no_sanitize("address")))` to that static global to
fix the test.
rdar://182623740
GCC 7.5.0 fails to compile this code. Use explicit upcasts from
std::unique_ptr<Derived> to std::unique_ptr<Base> in deserializeSummary
and deserializeAnalysisResult. This resolves a compilation error where
llvm::Expected<std::unique_ptr<Base>> could not be constructed from
unique_ptr of derived summary/result types.
Previously when using `-cl-fast-relaxed-math` flag along with
`fhonor-nans` or `fhonor-infinities` the honor flags did not override
the relaxed math flag. This behaviour is something that is not seen in
case of ffast-math for general targets.
This patch makes adjustments to how the driver and cc1 handles the
relaxed math flag for opencl. The flag was in the path of `fast-math` so
when someone used the `-cl-fast-relaxed-math` flag they were ultimately
overriding everything with fast-math. This was the main reason why honor
flags were not overriding relaxed math (atleast that's what I have
understood from my time working on this).
I have added tests for this as well and modified CodeGen cc1 tests
according to the changes in the patch.
I have personally not tested this on any AMD targets myself yet. So I am
unsure about this breaking anything (hopefully it should rather fix).
closes#178514
Fixes#210234
As per my investigation (mostly following stack traces and dumping
variable values), a default empty `DeclarationNameInfo` was being
returned after template substitution [over
here](c45b4e4d00/clang/lib/Sema/SemaTemplateInstantiateDecl.cpp (L3270)).
```cpp
// D-.>getNameInfo() has actual data here
DeclarationNameInfo NameInfo
= SemaRef.SubstDeclarationNameInfo(D->getNameInfo(), TemplateArgs);
// NameInfo has default values
```
This was being passed on directly to `CXXDestructorDecl::Create` leading
to the assertion being hit. This PR adds a check that ensures `NameInfo`
actually contains a valid destructor name before constructing a
`CXXDestructorDecl`. This fixes the assertion being hit in the
reproducer from the linked issue.
Split out from #179612 to make review easier. No functional change.
This introduces `LateParsedAttrType`, a new AST placeholder type used
during late parsing of type attributes. The actual late parsing
mechanism that uses this type is in #179612 and will be split into a
follow-up PR.
Add Clang IR coverage for `#pragma weak alias = target` on Darwin.
The test verifies that Clang:
- emits the alias with weak linkage;
- keeps calls referencing the alias instead of replacing them with the
aliasee.
This is a test-only follow-up to #198148 and covers the Clang lowering
path used by #111321.
Coverity static analysis scans on clang are unhappy with
[this](e55d3bca36/clang/lib/Lex/Preprocessor.cpp (L920))
invocation of `HandleModuleContextualKeyword` due to the fact that
_technically_ nothing is stopping `CurPPLexer` reference in
`Preprocessor` from being `nullptr`, although AFAICT the current code
ensures this doesn't happen when `Preprocessor` is in file-lexing mode.
However, an assertion could be added to `HandleModuleContextualKeyword`
for future debugging's sake.
---------
Co-authored-by: Yihan Wang <yronglin777@gmail.com>
This PR introduces PtrRefSafetyModel to abstract away type checks for
various smart pointer types in WebKit to share more code between
different checkers.
This patch adds the operation cir.std.strlen and teaches the recognizer
to raise strlen calls, following the ClangIR incubator. A C library
function carries no identity tag, so strlen is matched by its callee
symbol, which works since C names have no mangling.
The symbol alone is not enough when builtins are disabled, so the
recognizer honors the no builtin state CIRGen records, the mark on the
call and the list on the calling function. A call is raised only when it
is a direct call named strlen with one pointer to an 8 bit character of
either signedness, since the signedness of plain char follows the
target, and a fundamental unsigned integer result. A _BitInt is excluded
even at width 8.
The raised operation lowers back through the same generic function as
the other raised operations, and every call attribute is carried across,
so a no builtin mark or list survives the round trip. Tests cover the
raise, the symbol match, the no builtin cases, and the type guard.
Aided by Claude Opus 4.8
Fixes#206798
A reversed ("Yoda") null check `nullptr == p` produced a false
`core.NullDereference` when `p` is the address of a field of a symbolic
region (e.g. `&r->s`). The natural form (`p == nullptr`) worked fine.
Sema::isMemberAccessibleForDeletion treats AR_delayed as unreachable,
but CheckAccess returns AR_delayed whenever it runs inside an enclosing
delayed-diagnostics scope. That happens when deletion checking runs
synchronously while parsing a later declaration -- e.g. while explaining
why a defaulted operator<=> is deleted for an expression in that
declaration's initializer. The caller cannot consume a delayed
diagnostic, so letting CheckAccess delay always hits
llvm_unreachable("cannot delay =delete computation") and crashes.
Force an immediate answer by wrapping the CheckAccess call in
DelayedDiagnostics.pushUndelayed()/popUndelayed() via llvm::scope_exit,
mirroring the existing Sema::CheckEnableIf pattern in SemaOverload.cpp.
Fixes https://github.com/llvm/llvm-project/issues/210692
Co-authored-by: Claude-Sonnet
On x86_64-windows-msvc after 8ecec45518, clang applies the MSVC
size-based global-alignment scheme (Microsoft64BitMinGlobalAlign) and
does not apply the Sys V "large array" alignment increase. Users may
want to preserve the earlier ABI for compatibility with objects produced
by older clang releases.
Gate this behavior on the Clang ABI compatibility level. When
`-fclang-abi-compat=22` (or lower) is in effect,
MicrosoftX86_64TargetInfo restores LargeArrayMinWidth/LargeArrayAlign to
128 and getMinGlobalAlign skips the Microsoft64BitMinGlobalAlign step,
matching the older alignment choices.
Assisted by Claude (Anthropic).
FAIL: Clang :: Frontend/ast-main.c
FAIL: Clang :: Frontend/ast-main.cpp
were failing on z/OS; this change fixes these lit failures.
The issue here is that on z/OS the original source code language needs
to be passed through to the IR so that the backend can encode this
information in the PPA2 in the object file. That means that it needs to
be exported to the AST so that going from saved AST -> IR will carry the
language through.
Several checkers and ExprEngine declare a ProgramStateRef local that is
never read (typically `State = C.getState();` immediately followed by
code that re-fetches the state directly). These are not flagged by
-Wunused-variable because ProgramStateRef has a non-trivial destructor.
Found with a clang-query matcher over clang/lib/StaticAnalyzer.
Assisted-by: claude
computeObjectUnderConstruction stashed the program state into
PreElideState "before trying to elide, as it'll get overwritten", but
never used it. That comment and stash are fossils of the old
prepareForObjectConstruction, which returned and threaded the state
(`std::tie(State, V) = ...`); the failure path then reverted it with
`State = PreElideState;`.
The refactor to the SVal-returning computeObjectUnderConstruction (State
is now passed by value and the state updates moved to
updateObjectsUnderConstruction) dropped that revert but left the stash
and comment behind. State is never overwritten here anymore, so remove
the dead PreElideState and reword the comment to describe only the
CallOpts stash, which is still needed (CallOpts is passed by reference
and genuinely overwritten by the elision attempt).
Found with a clang-query matcher over clang/lib/StaticAnalyzer.
Assisted-by: claude
I used to get these errors on M4 with `LLVM_ENABLE_Z3_SOLVER`:
```
error: 'expected-error' diagnostics seen but not expected:
File clang/test/Analysis/z3/z3-bitint-arithmetic.c Line 26: unsigned _BitInt of bit sizes greater than 128 not supported
File clang/test/Analysis/z3/z3-bitint-arithmetic.c Line 29: unsigned _BitInt of bit sizes greater than 128 not supported
```
Fixes up #210525
Another nail in the coffin of #184695
This patch intends to clarify the current behaviors, not to state the
expected/desirable behaviors.
---------
Co-authored-by: Tarun Prabhu <tarunprabhu@gmail.com>
This is part of the commit series to gradually remove the class
`NodeBuilder` from the analyzer codebase.
This was a relatively complex situation because there were many
different `generateNode` calls and two situations where the the node
from `CheckedSet` was left in `EvalSet` without changes (which is
implicit with the `NodeBuilder` but now requires explicit
`EvalSet.insert(N)` calls).
Extractors might not always add summaries for all the TUs. If they don't
add any summaries to the TU result, then loading this summary for a
summary analysis would cause a failure.
This patch handles the situation gracefully by accepting such cases.
Split from: #209354
---------
Co-authored-by: Ziqing Luo <ziqing_luo@apple.com>
When evaluating whether an allocated type contains a pointer to generate
the alloc_token metadata, typeContainsPointer() previously only checked
for PointerType.
Expand typeContainsPointer() to check isAnyPointerType(),
isReferenceType(), isMemberFunctionPointerType(), and
isBlockPointerType().
These leaks were causing false test failures due to my global
.clang-format being in an ancestor directory of the build directory.
These changes prevent those issues when running the tests on my system.
I used MiMo v2.5 Pro agentically in Zed to find and fix the issue. But I
understand the changes and judge them to be safe and a clear improvement
over the status quo.