Compare commits

...

194 Commits

Author SHA1 Message Date
Oliver Hunt
ad7bb1cc45
[clang][Obj-C][PAC] Make block descriptor pointer signing configurable (#153700)
Pointer auth protection of the block descriptor pointer is only
supported in some constrained environments so we do actually need it to
be configurable.

We had made it non configurable in the first PR to protect block
metadata because we believed that was an option but subsequently
realised it does need to remain configurable.

This PR revives the flags that permit this.
2025-08-22 14:18:22 +02:00
Oliver Hunt
7575bda7e1
[clang][Obj-C][PAC] Add support for authenticating block metadata (#152978)
Introduces the use of pointer authentication to protect the invocation,
copy and dispose, reference, and descriptor pointers in Objective-C
block objects.

Resolves #141176
2025-08-22 14:18:22 +02:00
erichkeane
69890718e2
Move OpenACC Release Note-
It was pointed out in the review that this ended up in the wrong place!
Moving it.  Note this is a modification of the 21.x release notes, so
doesn't have a corresponding trunk change.
2025-08-21 08:15:06 +02:00
Jacques Pienaar
0eba8cf2fb
[mlir] Make parser not rely on terminating null. (#151007)
Used in follow up to parse slices of buffer.

(cherry picked from commit 217f9e57d1cc46de51d3b36177c4ba4049aaa805)
2025-08-21 08:12:50 +02:00
Simon Pilgrim
5d71f7c2ac
[X86] SimplifyDemandedVectorEltsForTargetNode - don't split X86ISD::CVTTP2UI nodes without AVX512VL (#154504)
Unlike CVTTP2SI, CVTTP2UI is only available on AVX512 targets, so we
don't fallback to the AVX1 variant when we split a 512-bit vector, so we
can only use the 128/256-bit variants if we have AVX512VL.

Fixes #154492

(cherry picked from commit d770567a514716cdb250a2dee635435c22622e34)
2025-08-21 08:11:13 +02:00
Amy Kwan
65b0685821
Add PowerPC/AIX related release notes to LLVM 21.1.0 2025-08-21 08:10:40 +02:00
Alexandre Ganea
333bdbb852
On Windows, in the release build script, fix detecting if clang-cl is in PATH (#149597)
The checks for detecting if `clang-cl` and `lld-link` are in `%PATH`
were wrong.

This fixes the comment in
https://github.com/llvm/llvm-project/pull/135446#discussion_r2215511129

(cherry picked from commit 13391ce183fc0b4c326829caad3eaec847c7b255)
2025-08-21 08:10:08 +02:00
Aaron Ballman
53aa823691
[C] Fix issue with -Wimplicit-void-ptr-cast (#154351)
The changes from https://github.com/llvm/llvm-project/pull/136855 missed
a change with atomic assignment constraints. This fixes a bug where we'd
accidentally drop a non-atomic-to-atomic conversion step.

Fixes #154157

co-authored-by: @ahatanak
(cherry picked from commit ae434cdd0ba572ab1b11629c8a10073dea7d2f3f)
2025-08-21 08:09:39 +02:00
Simon Pilgrim
1672f7db87
[X86] lowerShuffleAsLanePermuteAndPermute - ensure we've simplified the demanded shuffle mask elts before testing for a matching shuffle (#153554)
When lowering using sublane shuffles, we can sometimes end up with the
same mask as we started with. We already bail in these occasions, but we
weren't fully simplifying the new shuffle mask before testing if it
matched.

Fixes #153457

(cherry picked from commit c96d0da62b7ae83b613fc2b9c134cc42402ae2c4)
2025-08-21 08:09:13 +02:00
Oliver Hunt
27fc211bf0
[NFC][Clang][Docs] Update Pointer Authentication documentation (#152596)
This updates the pointer authentication documentation to include a
complete description of the existing functionaliy and behaviour, details
of the more complex aspects of the semantics and security properties,
and the Apple arm64e ABI design.

Co-authored-by: Ahmed Bougacha
Co-authored-by: Akira Hatanaka
Co-authored-by: John Mccall

---------

Co-authored-by: Ahmed Bougacha <ahmed@bougacha.org>
Co-authored-by: Akira Hatanaka <ahatanak@gmail.com>
Co-authored-by: John Mccall <rjmccall@apple.com>
(cherry picked from commit 62d2a8e6823de0310ba3a8b014ddcb2db356a1bb)
2025-08-21 08:08:45 +02:00
Oliver Hunt
7d6969bc6f
[clang][ObjC] Fix incorrect return type inference for discarded blocks (#154109)
When parsing a block expression we were not entering a new eval context
and as a result when parsing the block body we continue to treat any
return statements as discarded so infer a `void` result.

This fixes the problem by introducing an evaluation context around the
parsing of the body.

(cherry picked from commit ec4e6aaac4612af26322b2b10b8f518ecf053c74)
2025-08-21 08:07:51 +02:00
Oliver Hunt
45300aad3c
[clang][PAC] ptrauth_qualifier and ptrauth_intrinsic should only be available on Darwin (#153912)
For backwards compatibility reasons the `ptrauth_qualifier` and
`ptrauth_intrinsic` features need to be testable with `__has_feature()`
on Apple platforms, but for other platforms this backwards compatibility
issue does not exist.

This PR resolves these issues by making the `ptrauth_qualifier` and
`ptrauth_intrinsic` tests conditional upon a darwin target. This also
allows us to revert the ptrauth_qualifier check from an extension to a
feature test again, as is required on these platforms.

At the same time we introduce a new predefined macro `__PTRAUTH__` that
answers the same question as `__has_feature(ptrauth_qualifier)` and
`__has_feature(ptrauth_intrinsic)` as those tests are synonymous and
only exist separately for compatibility reasons.

The requirement to test for the `__PTRAUTH__` macro also resolves the
hazard presented by mixing the `ptrauth_qualifier` flag (that impacts
ABI and security policies) with `-pedantics-errors`, which makes
`__has_extension` return false for all extensions.

---------

Co-authored-by: Aaron Ballman <aaron@aaronballman.com>
(cherry picked from commit 624b724ca6df5d2d3ea16b9ed232851e5d061be4)
2025-08-21 08:07:17 +02:00
zhijian lin
2cf40a6ca8
[POWERPC] Fixes an error in the handling of the MTVSRBMI instruction for big-endian (#151565)
The patch fixed a bug introduced patch [[PowePC] using MTVSRBMI
instruction instead of constant pool in
power10+](https://github.com/llvm/llvm-project/pull/144084#top).

The issue arose because the layout of vector register elements differs
between little-endian and big-endian modes — specifically, the elements
appear in reverse order. This led to incorrect behavior when loading
constants using MTVSRBMI in big-endian configurations.

(cherry picked from commit 23b320311364f1bc1249500c7542d077d70098bf)
2025-08-21 08:06:54 +02:00
Oliver Hunt
16bea73be5
[clang] return type not correctly deduced for discarded lambdas (#153921)
The early return for lamda expressions with deduced return types in
Sema::ActOnCapScopeReturnStmt meant that we were not actually perform
the required return type deduction for such lambdas when in a discarded
context.

This PR removes that early return allowing the existing return type
deduction steps to be performed.

Fixes #153884

Fix developed by, and

Co-authored-by: Corentin Jabot <corentinjabot@gmail.com>
(cherry picked from commit bcab8ac126c0b4c439caa3104d66d33d0f70f86f)
2025-08-21 08:06:21 +02:00
yronglin
fe59f72b9a
[clang] Allow trivial pp-directives before C++ module directive (#153641)
Consider the following code:

```cpp
# 1 __FILE__ 1 3
export module a;
```

According to the wording in
[P1857R3](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p1857r3.html):
```
A module directive may only appear as the first preprocessing tokens in a file (excluding the global module fragment.)
```

and the wording in
[[cpp.pre]](https://eel.is/c++draft/cpp.pre#nt:module-file)
```
module-file:
    pp-global-module-fragment[opt] pp-module group[opt] pp-private-module-fragment[opt]
```

`#` is the first pp-token in the translation unit, and it was rejected
by clang, but they really should be exempted from this rule. The goal is
to not allow any preprocessor conditionals or most state changes, but
these don't fit that.

State change would mean most semantically observable preprocessor state,
particularly anything that is order dependent. Global flags like being a
system header/module shouldn't matter.

We should exempt a brunch of directives, even though it violates the
current standard wording.

In this patch, we introduce a `TrivialDirectiveTracer` to trace the
**State change** that described above and propose to exempt the
following kind of directive: `#line`, GNU line marker, `#ident`,
`#pragma comment`, `#pragma mark`, `#pragma detect_mismatch`, `#pragma
clang __debug`, `#pragma message`, `#pragma GCC warning`, `#pragma GCC
error`, `#pragma gcc diagnostic`, `#pragma OPENCL EXTENSION`, `#pragma
warning`, `#pragma execution_character_set`, `#pragma clang
assume_nonnull` and builtin macro expansion.

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

---------

Signed-off-by: yronglin <yronglin777@gmail.com>
(cherry picked from commit e6e874ce8f055f5b8c5d7f8c7fb0afe764d1d350)
2025-08-21 08:04:17 +02:00
Florian Hahn
c587c24db5
[TailDup] Delay aggressive computed-goto taildup to after RegAlloc. (#150911)
Back-ports additional tests (eb9febb4a6b0, dc697de12792), refactoring
(43c9c14577db) and functional change (18f1369297f4) in a single PR.

https://github.com/llvm/llvm-project/pull/114990 allowed more aggressive
tail duplication for computed-gotos in both pre- and post-regalloc tail
duplication.

In some cases, performing tail-duplication too early can lead to worse
results, especially if we duplicate blocks with a number of phi nodes.

This is causing a ~3% performance regression in some workloads using
Python 3.12.

This patch updates TailDup to delay aggressive tail-duplication for
computed gotos to after register allocation.

This means we can keep the non-duplicated version for a bit longer
throughout the backend, which should reduce compile-time as well as
allowing a number of optimizations and simplifications to trigger before
drastically expanding the CFG.

For the case in https://github.com/llvm/llvm-project/issues/106846, I
get the same performance with and without this patch on Skylake.

PR: https://github.com/llvm/llvm-project/pull/150911
2025-08-20 11:06:54 +01:00
Oliver Hunt
993c5643ce [clang][PAC][darwin] Set correct default ptrauth features for arm64e-darwin (#153722)
This PR makes sure that when targeting arm64e on darwin platforms the
correct flags are set for the userspace platform ABI.

(cherry picked from commit 19c4e86f3e8582c3f087a9fec5ac036838e58ec4)
2025-08-20 00:57:03 +00:00
Owen Pan
41cf77340d
release/21.x: [clang-format] Don't annotate class property specifiers as StartOfName (#153525) 2025-08-18 07:59:18 +02:00
owenca
fcb91597e2
[clang-format] Fix a bug in breaking before FunctionDeclarationName (#153924)
Fixes #153891

(cherry picked from commit a21d17f1d7173cdbc25f141595a0be9056760f77)
2025-08-18 07:58:52 +02:00
owenca
228a893b03
[clang-format] Allow breaking before bit-field colons (#153529)
Fixes #153448

(cherry picked from commit 5e57a10f502c8fc524bd119a53ddbf643686c7a0)
2025-08-18 07:58:20 +02:00
Koakuma
6d631510f9
[SPARC] Use FMA instructions when we have UA2007 (#148434)
(cherry picked from commit 111219ed2797703923be8ccb849a21d6ace550f5)
2025-08-18 07:57:14 +02:00
XChy
54766969b2
[VectorCombine] Apply InstSimplify in scalarizeOpOrCmp to avoid infinite loop (#153069)
Fixes #153012

As we tolerate unfoldable constant expressions in `scalarizeOpOrCmp`, we
may fold
```llvm
define void @bug(ptr %ptr1, ptr %ptr2, i64 %idx) #0 {
entry:
  %158 = insertelement <2 x i64> <i64 5, i64 ptrtoint (ptr @val to i64)>, i64 %idx, i32 0
  %159 = or disjoint <2 x i64> splat (i64 2), %158
  store <2 x i64> %159, ptr %ptr2
  ret void
}
```

to

```llvm
define void @bug(ptr %ptr1, ptr %ptr2, i64 %idx) {
entry:
  %.scalar = or disjoint i64 2, %idx
  %0 = or <2 x i64> splat (i64 2), <i64 5, i64 ptrtoint (ptr @val to i64)>
  %1 = insertelement <2 x i64> %0, i64 %.scalar, i64 0
  store <2 x i64> %1, ptr %ptr2, align 16
  ret void
}
```
And it would be folded back in `foldInsExtBinop`, resulting in an
infinite loop.

This patch forces scalarization iff InstSimplify can fold the constant
expression.

(cherry picked from commit 3a4a60deffdf5bbe622326b2813583acc37cccce)
2025-08-18 07:56:51 +02:00
Amy Kwan
482e2ffd4c
[PowerPC][CodeGen] Expand ISD::AssertNoFPClass for ppc_fp128 (#152357)
780054d3ff18075a6bc433029f336931792b1d2d added support for
`ISD::AssertNoFPClass`.

This ISD node can be used with the `ppc_fp128` type, which is really
just two `f64s` and requires expanding when used with
`ISD::AssertNoFPClass`. Without the support for expanding the result, we
get an assertion because the legalizer does not know how to expand the
results of `ppc_fp128` with `ISD::AssertNoFPClass`.
```
ExpandFloatResult #0: t7: ppcf128 = AssertNoFPClass t5, TargetConstant:i32<3>

LLVM ERROR: Do not know how to expand the result of this operator!
```
Thus, this patch aims to add support for the expand so we no longer
assert.

This fixes #151375.

(cherry picked from commit 63cc2e390db57cbc400b519771b7005eab1fc76a)
2025-08-18 07:55:22 +02:00
Ami-zhang
08b5797556
[clang][LoongArch] Ensure target("lasx") implies LSX support (#153542)
Currently, `__attribute__((target("lasx")))` does not automatically
enable LSX support, causing Clang to fail with `-mno-lsx`. Since
LASX depends on LSX, enabling LASX should implicitly enable LSX to
avoid clang error.

Fixes #149512.

Depends on #153541

(cherry picked from commit a1b6e7ff393533a5c4f3bdfd4efe5da106e2de2b)
2025-08-18 07:54:58 +02:00
Ami-zhang
9bf61a610c
[NFC] Precommit test for issue #149512 (#153541)
(cherry picked from commit 793a6b4fd402c929e04f9da407fe4491d5d9d22e)
2025-08-18 07:54:58 +02:00
Craig Topper
5a351e93fb
[RISCV][MoveMerge] Don't copy kill flag when moving past an instruction that reads the register. (#153644)
If we're moving the second copy before another instruction that reads
the copied register, we need to clear the kill flag on the combined
move.

Fixes #153598.

(cherry picked from commit defbbf0129d5c1ac360c6ffd9eaa2f07ab07d622)
2025-08-18 07:54:16 +02:00
Sam Elliott
08289ad13a
[RISCV] Track Linker Relaxable through Assembly Relaxation (#152602)
Span-dependent instructions on RISC-V interact in a complex manner with
linker relaxation. The span-dependent assembler algorithm implemented in
LLVM has to start with the smallest version of an instruction and then
only make it larger, so we compress instructions before emitting them to
the streamer.

When the instruction is streamed, the information that the instruction
(or rather, the fixup on the instruction) is linker relaxable must be
accurate, even though the assembler relaxation process may transform a
not-linker-relaxable instruction/fixup into one that that is linker
relaxable, for instance `c.jal` becoming `qc.e.jal`, or `bne` getting
turned into `beq; jal` (the `jal` is linker relaxable).

In order for this to work, the following things have to happen:
- Any instruction/fixup which might be relaxed to a linker-relaxable
instruction/fixup, gets marked as `RelaxCandidate = true` in
RISCVMCCodeEmitter.
- In RISCVAsmBackend, when emitting the `R_RISCV_RELAX` relocation, we
have to check that the relocation/fixup kind is one that may need a
relax relocation, as well as that it is marked as linker relaxable (the
latter will not be set if relaxation is disabled).
- Linker Relaxable instructions streamed to a Relaxable fragment need to
mark the fragment and its section as linker relaxable.

I also added more debug output for Sections/Fixups which are marked
Linker Relaxable.

This results in more relocations, when these PC-relative fixups cross an
instruction with a fixup that is resolved as not linker-relaxable but
caused the fragment to be marked linker relaxable at streaming time
(i.e. `c.j`).

(cherry picked from commit 9e8f7acd2b3a71dad473565a6a6f3ba51a3e6bca)

Fixes: #150071
2025-08-18 07:51:49 +02:00
Richard Smith
af18c6f22e
Work around documented Linux mmap bug. (#152595)
On Linux, mmap doesn't always zero-fill slack bytes ([man page]),
despite being required to do so by POSIX. If the final page of a file is
in the page cache and the bytes past the end of the file get overwritten
by some process, those bytes then remain non-zero until the page falls
out of the cache or another process overwrites them.

Stop trusting that mmap behaves properly and instead check
whether the buffer was indeed properly terminated. If not, fall back to
using `read` to read the file contents.

This fixes an obscure clang crash bug that can occur if another program
(such as an editor) mmap's a source file and writes past the end of the
mmap'd region shortly before clang or clangd attempts to parse the file.

 [man page]: https://man7.org/linux/man-pages/man2/mmap.2.html#BUGS

(cherry picked from commit 85cd3d98686c47d015dbcc17f1f7d0714b00e172)
2025-08-18 07:50:14 +02:00
Nikolas Klauser
83f2150717
[libc++] Fix std::variant evaluating template arguments too eagerly (#151028)
This has been reported in https://github.com/llvm/llvm-project/pull/116709#issuecomment-3105095648.

Fixes #151328

(cherry picked from commit f5f582451e913581ef214b8b771a13d3912394d5)
2025-08-18 07:49:47 +02:00
Stephen Long
8e0e800222
PreISelIntrinsicLowering: Lower llvm.log to a loop if scalable vec arg (#129744)
Similar to ab976a1, but for llvm.log.

(cherry picked from commit 19ada02086c371dda75ec9704e50e1e28f1758bb)
2025-08-18 07:49:02 +02:00
Tobias Hieta
6096d35ea9
Bump version to 21.1.0-rc3 2025-08-12 10:48:24 +02:00
Jonathon Penix
a619e46315
[clang][Driver] Prefer non-Linux emulations for baremetal Arm/AArch64 targets (#149235)
I'm unsure if there is an official source for which targets use/support
which emulations, but for the baremetal GNU Arm/AArch64 toolchains or
binutils builds I've tried to use, GNU ld either did not support the
Linux emulations (resulting in errors unless overriding the emulation)
or the Linux emulations were supported but GCC passed the non-Linux
emulations by default.

These emulations all seem to be accepted by lld as well, so try to align
with what it seems GCC is doing and prefer the non-Linux emulations for
baremetal Arm/AArch64 targets.

(cherry picked from commit ee63c1f3520bca0acb859fcb4da49d3eb667c1ad)
2025-08-12 10:44:02 +02:00
hanbeom
6f5c887e55
[GVN] Check IndirectBr in Predecessor Terminators (#151188)
Critical edges with an IndirectBr terminator cannot be split.
Add a check it to prevent assertion failures.

Fixes: #150229
(cherry picked from commit a750fcb52bbf0ec0dc2022f73b1d48a4d43d8a07)
2025-08-11 14:12:09 +02:00
Yingwei Zheng
f64406b824
[IR] Handle fabs LHS in fcmpImpliesClass (#152913)
Closes https://github.com/llvm/llvm-project/issues/152824.

(cherry picked from commit d8b1b46cd39c91830bcf49ed91d80f38f78c2168)
2025-08-11 14:11:19 +02:00
A. Jiang
c092e2af14
[libc++] Fix uses of non-empty transparent comparator in <map> (#152624)
The `__get_value()` member function was removed in LLVM 21, but the
calls in `<map>` weren't removed. This patch completes the removal and
adds regression test cases.

Fixes #152543.

(cherry picked from commit 7ae1424286203e37f6238e9349b1bfbe873ebabf)
2025-08-11 14:10:52 +02:00
Ayke
ba87d05c55
[AVR] Fix codegen after getConstant assertions got enabled (#152269)
This fixes https://github.com/llvm/llvm-project/issues/152097

This commit fixes two instances of a (somewhat) recently enabled
assertion. One with a test, the other I can't reproduce (might be dead
code) but certainly looks like an instance of the same problem.

The PR that introduced the regression:
https://github.com/llvm/llvm-project/pull/117558

With this patch, the AVR backend is usable again for TinyGo.

(cherry picked from commit aeeb9b507750553f0e85584bda20b8d2373b3bda)
2025-08-11 14:10:12 +02:00
Nikita Popov
7be867f19d
[SystemZ] Remove incorrect areInlineCompatible hook (#152494)
This reverts https://github.com/llvm/llvm-project/pull/132976.

The PR incorrectly claimed that this makes inlining more liberal,
referencing the string comparison in TargetTransformInfoImpl.h.

However, the implementation that actually applies is the one in
BasicTTIImpl.h, which performs a feature subset comparison. As such,
this regressed inlining, most concerningly of functions without +vector
into functions with +vector.

Revert the change to restore the previous behavior.

(cherry picked from commit 18e4f775c33af123772409ffde69dd424b98814a)
2025-08-11 14:09:32 +02:00
Paul Murphy
3e55c84ab6
[PowerPC] fix lowering of SPILL_CRBIT on pwr9 and pwr10 (#146424)
If a copy exists between creation of a crbit and a spill, machine-cp
may delete the copy since it seems unaware of the relation between a cr
and crbit. A fix was previously made for the generic ppc64 lowering. It
should be applied to the pwr9 and pwr10 variants too.

Likewise, relax and extend the pwr8 test to verify pwr9 and pwr10
codegen too.

This fixes #143989.

(cherry picked from commit 5f864560a6514bb74ecc1e0c7d3ff8c412228bfe)
2025-08-11 14:09:06 +02:00
Csanád Hajdú
17c39c1e05
[compiler-rt][AArch64] Add GCS property in assembly files (#152502)
Only BTI and PAC properties were added previously.

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

(cherry picked from commit c088b5ffca4c4b81a8fa0e7f006e9391eba1f191)
2025-08-11 14:08:26 +02:00
Corentin Jabot
3aee9c7371
[libc++] Fix tests after #144220
This is a backport of the test fixes made in #151935

Fixes #150601
2025-08-11 14:07:52 +02:00
Carlos Seo
e239f1fc58
[Flang] Fix crash with parametrized derived types usage (#150289)
The current mangleName implementation doesn't take a FoldingContext,
which prevents the proper evaluation of expressions containing parameter
references to an integer constant. Since parametrized derived types are
not yet implemented, the compiler will crash there in some cases (see
example in issue #127424).

This is a workaround so that doesn't happen until the feature is
properly implemented.

Fixes #127424

(cherry picked from commit 89e4d9f905f7abbf5803c011ab6fba26796ced30)
2025-08-11 14:07:21 +02:00
Amy Kwan
768c3245b4
[AIX] Handle arbitrary sized integers when lowering formal arguments passed on the stack (#149351)
When arbitrary sized (non-simple type, or non-power of two types)
integers are passed on the stack, these integers are not handled when
lowering formal arguments on AIX as we always assume we will encounter
simple type integers.

However, it is possible for frontends to generate arbitrary sized
immediate values in IR. Specifically in rustc, it will generate an
integer value in LLVM IR for small structures that are less than a
pointer size, which is done for optimization purposes for the Rust ABI.
For example, if a Rust structure of three characters is passed into
function on the stack,
```
struct my_struct {
  field1: u8,
  field2: u8,
  field3: u8,
}
```
This will generate an `i24` type in LLVM IR.

Currently, it is not obvious for the backend to distinguish an integer
versus something that wasn't an integer to begin with (such as a
struct), and the latter case would not have an extend on the parameter.
Thus, this PR allows us to perform a truncation and extend on integers,
both non-simple and simple types.

(cherry picked from commit f48a8da34292b367ba8a5e7b25065172df966848)
2025-08-11 14:06:48 +02:00
Louis Dionne
3290ca0fdd
[libc++] Add checks for misused hardening macros (#150669)
Libc++ hardening went through several iterations, sometimes within a
single release. However, some folks in the wild have picked up these
macros that were either public at some point or that were used
temporarily on `main`, and unfortunately those are now ignored.

This can lead to some users thinking they enable hardening when in
reality they don't, which is a pretty big deal. This patch simply checks
various old hardening-related macros and ensures that they are not set,
which will catch such misuse.

(cherry picked from commit 955ece4fa53e5309dd38795efd6a357ddf52963b)
2025-08-11 14:05:54 +02:00
Simon Pilgrim
0fb2434e9a [RISCV] Add test coverage for #148084 2025-08-08 12:19:00 +02:00
Simon Pilgrim
c8f64bbe68 [DAG] visitFREEZE - limit freezing of multiple operands (#149797)
This is a partial revert of #145939 (I've kept the BUILD_VECTOR(FREEZE(UNDEF), FREEZE(UNDEF), elt2, ...) canonicalization) as we're getting reports of infinite loops (#148084).

The issue appears to be due to deep chains of nodes and how visitFREEZE replaces all instances of an operand with a common frozen version - other users of the original frozen node then get added back to the worklist but might no longer be able to confirm a node isn't poison due to recursion depth limits on isGuaranteedNotToBeUndefOrPoison.

The issue still exists with the old implementation but by only allowing a single frozen operand it helps prevent cases of interdependent frozen nodes.

I'm still working on supporting multiple operands as its critical for topological DAG handling but need to get a fix in for trunk and 21.x.

Fixes #148084
2025-08-08 12:19:00 +02:00
Harald-R
d51ce3406a [clangd] Use resolved path when checking AngledHeaders/QuotedHeaders in IncludeInserter (#148371)
This makes IncludeInserter's behavior consistent with include-cleaner,
as discussed in https://github.com/llvm/llvm-project/pull/140594.

(cherry picked from commit ff0093cecd0c807d122cfb6b74634074c962ade9)
2025-08-08 12:17:01 +02:00
Oliver Hunt
3c754bfd9b [clang][PAC] Fix PAC codegen for final class dynamic_cast optimization (#152227)
The codegen for the final class dynamic_cast optimization fails to
consider pointer authentication. This change resolves this be simply
disabling the optimization when pointer authentication enabled.

(cherry picked from commit 726847829553079a13b1b7104f2c2db9dcda9c1d)
2025-08-08 12:14:38 +02:00
David Truby
2555a85378 [flang-rt] Use correct flang-rt build for flang-rt unit tests on Windows (#152318)
Currrently flang-rt assumes that LLVM was always built with the dynamic
MSVC runtime. This may not be the case, if the user has specified a
different runtime with -DCMAKE_MSVC_RUNTIME_LIBRARY. Since this flag is
implied by -DLLVM_ENABLE_RPMALLOC=On, which is used by the Windows
release script, this is causing that script to fail.

Fixes #151920

(cherry picked from commit f73a3028c2d46928280d69d9e953ff79d2eb0fbb)
2025-08-08 12:14:17 +02:00
David Spickett
b398447cbc [llvm][cmake] Remove version number from runtimes in PROJECTS warnings (#152457)
Judging from the reaction to
https://github.com/llvm/llvm-project/pull/152302, we are not ready to
make this a fatal error.

Remove the specific version number, and update the libc message to match
the others' wording.

(cherry picked from commit 6cd6de5bc0c8b09b3a252bfb8a62870c1cdede4c)
2025-08-08 12:13:58 +02:00
Michael Kruse
9ec748cfb1 [Flang] Search flang_rt in clang_rt path (#151954)
The clang/flang driver has two separate systems for find the location of
clang_rt (simplified):

* `getCompilerRTPath()`, e.g. `../lib/clang/22/lib/windows`,
   used when `LLVM_ENABLE_PER_TARGET_RUNTIME_DIR=0`
* `getRuntimePath()`, e.g. `../lib/clang/22/lib/x86_64-pc-windows-msvc`,
   used when `LLVM_ENABLE_PER_TARGET_RUNTIME_DIR=1`

To simplify the search path, Flang-RT normally assumes only
`getRuntimePath()`, i.e. ignoring `LLVM_ENABLE_PER_TARGET_RUNTIME_DIR`
and always using the `LLVM_ENABLE_PER_TARGET_RUNTIME_DIR=1` mechanism.
There is an exception for Apple Darwin triples where `getRuntimePath()`
returns nothing. The flang-rt/compiler-rt CMake code for library
location also ignores `LLVM_ENABLE_PER_TARGET_RUNTIME_DIR` but uses the
`LLVM_ENABLE_PER_TARGET_RUNTIME_DIR=0` path instead. Since only
`getRuntimePath()` is automatically added to the linker command line,
this patch explicitly adds `getCompilerRTPath()` to the path when
linking flang_rt.

Fixes #151031

(cherry picked from commit 8de481913353a1e37264687d5cc73db0de19e6cc)
2025-08-08 12:13:37 +02:00
Michael Kruse
79f3653fbd [flang][cmake] Fix bbc dependencies (#152306)
Re-apply "[flang][cmake] Fix bcc dependencies (#125822)"

It was overwritten due to an automatic merge gone wrong for #124416.

`git cherry-pick f9af5c145f40480d46874b643ca2b1237e9fbb2a` applied in
97cf061e83a0d0cada38d8a2d75c8a840b01ba26 ignored the renaming of
FortranCommon into FortranSupport after #125822.

Original commit message:

The Fortran libraries are not part of MLIR, so they should use
target_link_libraries() rather than mlir_target_link_libraries().
This fixes an issue introduced in #20966.

(cherry picked from commit 2bb23d444767540c59c32ccdb86f7ef6e35fd96e)
2025-08-08 12:13:16 +02:00
Hubert Tong
6203ddea9f Remove reference to reverted PR #130742
Based on the file history in https://github.com/dtcxzyw/llvm-project/commits/main/llvm/test/CodeGen/AMDGPU/memcpy-crash-issue63986.ll, it appears #130742 was reverted by #138168 and never re-applied.
2025-08-08 12:12:53 +02:00
Nathan Ridge
d1f761c8d7 [clangd] Add clangd 21 release notes 2025-08-08 12:12:15 +02:00
Aaron Ballman
460ff1eb0e [C23] AST equivalence of attributes (#151196)
Implicitly declared types (like __NSConstantString_tag, etc) will be
declared with visibility attributes. This causes problems when merging
ASTs because we currently reject declaration merging for declarations
with attributes.

This relaxes that restriction somewhat; implicit declarations can now
have attributes when merging; we assume that if the compiler generated
it, it's fine.

(cherry picked from commit 30a5d569b2102bba1cfb5d253bd73ec2ebce7ee0)
2025-08-08 12:11:57 +02:00
Tommy MᶜMichen
bf0f8eae0a [llvm][sroa] Disable support for invariant.group (#151743)
Resolves #151574.

> SROA pass does not perform aggregate load/store rewriting on a pointer
whose source is a `launder.invariant.group`.
>
> This causes failed assertion in `AllocaSlices`.
>
> ```
> void (anonymous
namespace)::AllocaSlices::SliceBuilder::visitStoreInst(StoreInst &):
> Assertion `(!SI.isSimple() || ValOp->getType()->isSingleValueType())
&&
>  "All simple FCA stores should have been pre-split"' failed.
> ```

Disables support for `{launder,strip}.invariant.group` intrinsics in
SROA.

Updates SROA test for `invariant.group` support.

(cherry picked from commit 155359c1f2bda7fb8d4e8001157ecea03689df68)
2025-08-08 12:11:28 +02:00
Sudharsan Veeravalli
f24efe19dc [Hexagon] Add nounwind to hexagon-strcpy.ll (#151293)
The test does not check for anything related to cfi information so we
don't really need them in the test checks. Also it looks like there were
some failures on the Alpine Linux builders due to the placement of the
cfi information in the output assembly.

I have also changed `-march` to `-mtriple` in the run line similar to
2208c97

(cherry picked from commit 3796efb5dc08d4596aa986bd03a1290c43e2e995)
2025-08-08 12:10:51 +02:00
Alex Rønne Petersen
496a49d4a2 [libunwind] Fix return type of DwarfFDECache::findFDE() in definition (#146308)
Needed to resolve this compilation error on some systems:

lib/libunwind/src/UnwindCursor.hpp:153:38: error: return type of
out-of-line definition of 'libunwind::DwarfFDECache::findFDE' differs
from that in the declaration
    typename A::pint_t DwarfFDECache<A>::findFDE(pint_t mh, pint_t pc) {
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^
lib/libunwind/src/libunwind.cpp:31:10: note: in file included from
lib/libunwind/src/libunwind.cpp:31:
    #include "UnwindCursor.hpp"
             ^
lib/libunwind/src/UnwindCursor.hpp💯17: note: previous declaration is
here
      static pint_t findFDE(pint_t mh, pint_t pc);
             ~~~~~~~^

(cherry picked from commit eb0d8f9272f7c734cdaf31bc33a18e1619e021e4)
2025-08-08 12:10:00 +02:00
Aaron Ballman
3d6fb12dfc [C23] More improved type compatibility for enumerations (#150946)
The structural equivalence checker was not paying attention to whether
enumerations had compatible fixed underlying types or not.

Fixes #150594
2025-08-05 08:24:28 -04:00
bd1976bris
400d8b0675 [Test] Adjust quoting in archive-thin.test for spaces in paths (#151707)
As suggested in review (see: #149425), I believed that using single
quotes was a nicer quoting scheme that correctly handled paths with
spaces. Alas, build bot failures have demonstrated that this is not the
case.

Revert to the original quoting scheme (see: #146749).

(cherry picked from commit 73ce0aca72348a80dc2c2175516a0993ab8d6be3)
2025-08-05 10:51:55 +00:00
Younan Zhang
7ee100cced [Clang] Don't allow implicit this access when checking function constraints (#151276)
We allowed implicit this access when checking associated constraints
after CWG2369. As a result, some of the invalid function call
expressions were not properly SFINAE'ed out and ended up as hard errors
at evaluation time.

We tried fixing that by mucking around the CurContext, but that spawned
additional breakages and I think it's probably safe to revert to the
previous behavior to avoid churns.

Though there is CWG2589, which justifies the previous change, it's not
what we're pursuing now.

Fixes https://github.com/llvm/llvm-project/issues/151271
Fixes https://github.com/llvm/llvm-project/issues/145505
2025-08-05 10:59:43 +02:00
Utkarsh Saxena
6419104d18 [LifetimeSafety] Add language option for experimental lifetime safety (#149592)
Add a language option flag for experimental lifetime safety analysis in C++.

This change provides a language option to control the experimental lifetime safety analysis feature, making it more explicit and easier to enable/disable. Previously, the feature was controlled indirectly through a diagnostic warning flag, which we do not want to accidentally enable with `-Weverything` (atm)!

- Added a new language option `EnableLifetimeSafety` in `LangOptions.def` for experimental lifetime safety analysis in C++
- Added corresponding driver options `-fexperimental-lifetime-safety` and `-fno-experimental-lifetime-safety` in `Options.td`
- Modified `AnalysisBasedWarnings.cpp` to use the new language option flag instead of checking if a specific diagnostic is ignored
- Updated a test case to use the new flag instead of relying on the warning flag alone

(cherry picked from commit 0d0478903474b2e53c874427e3d6eb2ed7567e50)
2025-08-05 10:59:05 +02:00
Aaron Ballman
d502822e68 [C] static_assert in a for loop is not an extension (#151955)
The original wording can be squinted at to pretend this was always
allowed. GCC squints at it that way, so we're doing the same and no
longer issuing an extension diagnostic for use of static_assert in the
condition-1 of a for loop in C.

Fixes #149633

(cherry picked from commit cb50d78a0063244434d883d89ddda7f74abbffc9)
2025-08-05 10:57:49 +02:00
Keno Fischer
1d46440e9f [Driver][MinGW] Always put libc argument last, even if non-standard (#149434)
I was attempting to build openblas with clang in msys2's `ucrt64`
environment (I'm aware of the `clang64` environment, but I wanted
libstdc++). The openblas link failed with the following:

```
clang -march=native -mtune=native -m64  -O2 -fno-asynchronous-unwind-tables -O2 -DSMALL_MATRIX_OPT -DMS_ABI -DMAX_STACK_ALLOC=2048 -Wall -m64 -DF_INTERFACE_GFORT -DDYNAMIC_ARCH -DSMP_SERVER -DNO_WARMUP -DMAX_CPU_NUMBER=512 -DMAX_PARALLEL_NUMBER=1 -DBUILD_SINGLE=1 -DBUILD_DOUBLE=1 -DBUILD_COMPLEX=1 -DBUILD_COMPLEX16=1 -DVERSION=\"0.3.29\" -UASMNAME -UASMFNAME -UNAME -UCNAME -UCHAR_NAME -UCHAR_CNAME -DASMNAME= -DASMFNAME=_ -DNAME=_ -DCNAME= -DCHAR_NAME=\"_\" -DCHAR_CNAME=\"\" -DNO_AFFINITY -I..  libopenblas64_.def dllinit.obj \
-shared -o ../libopenblas64_.dll -Wl,--out-implib,../libopenblas64_.dll.a \
-Wl,--whole-archive ../libopenblas64_p-r0.3.29.a -Wl,--no-whole-archive -LC:/msys64/ucrt64/bin/../lib/gcc/x86_64-w64-mingw32/15.1.0 -LC:/msys64/ucrt64/bin/../lib/gcc -LC:/msys64/ucrt64/bin/../lib/gcc/x86_64-w64-mingw32/15.1.0/../../../../x86_64-w64-mingw32/lib/../lib -LC:/msys64/ucrt64/bin/../lib/gcc/x86_64-w64-mingw32/15.1.0/../../../../lib -LC:/msys64/ucrt64/bin/../lib/gcc/x86_64-w64-mingw32/15.1.0/../../../../x86_64-w64-mingw32/lib -LC:/msys64/ucrt64/bin/../lib/gcc/x86_64-w64-mingw32/15.1.0/../../..  -lgfortran -lmingwex -lmsvcrt -lquadmath -lm -lpthread -lmingwex -lmsvcrt  -defaultlib:advapi32 -lgfortran -defaultlib:advapi32 -lgfortran

C:/msys64/ucrt64/bin/ld: C:/msys64/ucrt64/bin/../lib/gcc/x86_64-w64-mingw32/15.1.0/../../../../lib/libmingw32.a(lib64_libmingw32_a-pseudo-reloc.o): in function `__report_error':
D:/W/B/src/mingw-w64/mingw-w64-crt/crt/pseudo-reloc.c:157:(.text+0x59): undefined reference to `abort'
C:/msys64/ucrt64/bin/ld: C:/msys64/ucrt64/bin/../lib/gcc/x86_64-w64-mingw32/15.1.0/../../../../lib/libmingw32.a(lib64_libmingw32_a-tlsthrd.o): in function `___w64_mingwthr_add_key_dtor':
D:/W/B/src/mingw-w64/mingw-w64-crt/crt/tlsthrd.c:48:(.text+0xa5): undefined reference to `calloc'
C:/msys64/ucrt64/bin/ld: C:/msys64/ucrt64/bin/../lib/gcc/x86_64-w64-mingw32/15.1.0/../../../../lib/libmingw32.a(lib64_libmingw32_a-pesect.o): in function `_FindPESectionByName':
D:/W/B/src/mingw-w64/mingw-w64-crt/crt/pesect.c:79:(.text+0xfd): undefined reference to `strncmp'
```

These symbols come from the `-lmingw32` dep that the driver added and
are ordinarily found in `-lmsvcrt`, which got skipped here, because
openblas passed `-lmsvcrt` explicitly earlier in the link line. Since we
always add these libraries at the end here, I think that clang is "at
fault" (as opposed to a user or packaging mistake) and should have added
some crt here.

To preserve the intent of letting the user override which crt is chosen,
duplicate the (first) user chosen crt `-l` into this position, although
we should perhaps consider an explicit `-mcrtdll` like gcc has as well.

(cherry picked from commit 7f470586e10543aa12efc7e04d4d4ac814eaca35)
2025-08-05 10:57:19 +02:00
Konstantin Varlamov
16bd92cdca [libc++][hardening] Add a greppable prefix to assertion messages. (#150560)
The current assertion failure messages produced by Hardening are not
very grep-friendly (the common part is rarther generic and requires
wildcards to match). While it's possible to use `__FILE__` for grepping,
it's easier and more straighforward to simply add a libc++-specific
prefix; this is especially important for the planned `observe` mode that
might produce many assertion failure messages over the course of the
program's execution that later need to be filtered and examined.

(cherry picked from commit 4ef92469ab341ac1bee39a9413ffaa845e307414)
2025-08-05 10:56:59 +02:00
Aaron Puchert
d4046ae6df Thread safety analysis: Don't warn on acquiring reentrant capability (#150857)
The point of reentrant capabilities is that they can be acquired
multiple times, so they should probably be excluded from requiring a
negative capability on acquisition via -Wthread-safety-negative.

However, we still propagate explicit negative requirements.

(cherry picked from commit a048aeb06e5de571eadd646860c320b9a67d1efc)
2025-08-05 10:56:39 +02:00
Jessica Clarke
f5ad8dc687 [ELF][Hexagon] Fix host endianness assumption
Fixes: b42f96bc057f ("[lld] Add thunks for hexagon (#111217)")
(cherry picked from commit 723b40a8d92f76fc913ef21061fc3d74e8c47441)
2025-08-05 10:56:10 +02:00
Jessica Clarke
74a0c1e962 [NFC][ELF][Hexagon] Avoid pointless ArrayRef::drop_front
Fixes: b42f96bc057f ("[lld] Add thunks for hexagon (#111217)")
(cherry picked from commit de15d365743e16848a9d15fc32ae6ab98d399ec2)
2025-08-05 10:56:10 +02:00
Jessica Clarke
489d36cedc [NFC][ELF] Add missing blank line between functions
Fixes: b42f96bc057f ("[lld] Add thunks for hexagon (#111217)")
(cherry picked from commit b03d1e1e2e8e4b0b4b9e035b7ad9fb86dccefb93)
2025-08-05 10:56:10 +02:00
Craig Topper
863f9963c3 [RISCV] vsha2cl intrinsics should select vsha2cl instructions.
Fixes #151814.

(cherry picked from commit a585d5758847dd7e4cd7d8137bea6c1577c53009)
2025-08-05 10:55:42 +02:00
James Y Knight
c7ac782942 [clang-format] Google Style: disable DerivePointerAlignment. (#149602)
The [Google C++ Style
Guide](https://google.github.io/styleguide/cppguide.html#Pointer_and_Reference_Expressions)
is being changed to specify that spaces should go after the
asterisk/ampersand, rather than permitting either before or after on a
file-by-file basis.

The new requirement is:
> When referring to a pointer or reference (variable declarations or
> definitions, arguments, return types, template parameters, etc.),
> you must not place a space before the asterisk/ampersand. Use a
> space to separate the type from the declared name (if present).

The [Google ObjC
style](https://google.github.io/styleguide/objcguide.html) is silent on
this matter, but the de-facto style is not being modified at this time.
So, keep DerivePointerAlignment enabled for ObjC language mode.

(cherry picked from commit 9281797a577b7954521fb9192d41e457ca2ca42e)
2025-08-05 10:55:22 +02:00
Zhaoxin Yang
ca8b2f3777 [lld][LoongArch] GOT indirection to PC relative optimization (#123743)
In LoongArch, we try GOT indirection to PC relative optimization in
normal or medium code model, whether or not with R_LARCH_RELAX
relocation.

From:
* pcalau12i $a0, %got_pc_hi20(sym_got)
* ld.w/d $a0, $a0, %got_pc_lo12(sym_got)

To:
* pcalau12i $a0, %pc_hi20(sym)
* addi.w/d $a0, $a0, %pc_lo12(sym)

If the original code sequence can be relaxed into a single instruction
`pcaddi`, this patch will not be taken (see
https://github.com/llvm/llvm-project/pull/123566).
The optimization related to GOT is split into two locations because the
`relax()` function is part of an iteration fixed-point algorithm. We
should minimize it to achieve better linker performance.

Note: Althouth the optimization has been performed, the GOT entries
still exists, similarly to AArch64. Eliminating the entries will
increase code complexity.

(cherry picked from commit 283c47b4c5231a1baf528355f7119a73ac168968)
2025-08-05 10:55:01 +02:00
Samarth Narang
087cb2e91c [clang] Avoid inheriting [[noreturn]] in explicit function template specializations (#150003)
This patch fixes incorrect behavior in Clang where [[noreturn]] (either
spelled or inferred) was being inherited by explicit specializations of
function templates or member function templates, even when those
specializations returned normally.

Follow up on https://github.com/llvm/llvm-project/pull/145166

(cherry picked from commit 22fef005225b129d73ade4ed995fc0ec0c7be044)
2025-08-05 10:54:39 +02:00
Andreas Schwab
8d38ccbb5a Remove reference to obsolete termio ioctls
The termio ioctls are no longer used after commit 59978b21ad9c
("[sanitizer_common] Remove interceptors for deprecated struct termio
(#137403)"), remove them.  Fixes this build error:

../../../../libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cpp:765:27: error: invalid application of ‘sizeof’ to incomplete type ‘__sanitizer::termio’
  765 |   unsigned IOCTL_TCGETA = TCGETA;
      |                           ^~~~~~
../../../../libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cpp:769:27: error: invalid application of ‘sizeof’ to incomplete type ‘__sanitizer::termio’
  769 |   unsigned IOCTL_TCSETA = TCSETA;
      |                           ^~~~~~
../../../../libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cpp:770:28: error: invalid application of ‘sizeof’ to incomplete type ‘__sanitizer::termio’
  770 |   unsigned IOCTL_TCSETAF = TCSETAF;
      |                            ^~~~~~~
../../../../libsanitizer/sanitizer_common/sanitizer_platform_limits_posix.cpp:771:28: error: invalid application of ‘sizeof’ to incomplete type ‘__sanitizer::termio’
  771 |   unsigned IOCTL_TCSETAW = TCSETAW;
      |                            ^~~~~~~
Part-of: https://github.com/llvm/llvm-project/pull/138822
Closes: https://github.com/llvm/llvm-project/pull/138822

(cherry picked from commit c99b1bcd505064f2e086e6b1034ce0b0c91ea5b9)
2025-08-05 10:54:10 +02:00
cqwrteur
9869d43fc2 [sanitizer] Remove usage of termios ioctl constants on Linux glibc since 2.41 (#149140)
glibc 2.42 made all usage of termios ioctl constants strictly internal

Therefore, we remove all usage for those removed constants.

This should only apply for Linux.

Fix #149103

Reference:

3d3572f590

@fweimer-rh @tstellar

(cherry picked from commit 0a17483c481d82eace3b36aee9cacb619eb027af)
2025-08-05 10:54:10 +02:00
bd1976bris
d9ddd18544 [DTLTO][LLD][ELF] Support bitcode members of thin archives (#149425)
This patch adds support for bitcode members of thin archives to DTLTO
(https://llvm.org/docs/DTLTO.html) in ELF LLD.

For DTLTO, bitcode identifiers must be valid paths to bitcode files on
disk. Clang does not support archive inputs for ThinLTO backend
compilations. This patch adjusts the identifier for bitcode members of
thin archives in DTLTO links so that it is the path to the member file
on disk, allowing such members to be supported in DTLTO.

This patch is sufficient to allow for self-hosting an LLVM build with
DTLTO when thin archives are used.

Note: Bitcode members of non-thin archives remain unsupported. This will
be addressed in a future change.

Testing:
- LLD lit test coverage has been added to check that the identifier is
adjusted appropriately.
- A cross-project lit test has been added to show that a DTLTO link can
succeed when linking bitcode members of thin archives.

For the design discussion of the DTLTO feature, see: #126654.

(cherry picked from commit 673476d96bed306be6ed81a8174f481a9a4b2934)
2025-08-05 10:48:37 +02:00
bd1976bris
8b85cf53a1 [DTLTO][Clang][Docs] Update for COFF support (#149988)
As the COFF linker is usually invoked independently, update the Clang
DTLTO section to show an example. This follows what is done earlier in
the document.

Also some minor fixes and improvements:
- Use generic distributor names to avoid implying anything about what an
Incredibuild distributor may or should support.
- Use subheadings for readability.
- Correct a mis-cased hyperlink.

(cherry picked from commit c129d65995babf8bf56499c3f8b9b6df073190ef)
2025-08-05 10:48:08 +02:00
David Spickett
1f17474592 [llvm][docs] Add release note for LLDB MTE changes
Goes with https://github.com/llvm/llvm-project/pull/151111.
2025-08-05 10:47:45 +02:00
Sergio Afonso
b38f35757b [Flang][OpenMP][Docs] Update target-related support in Flang docs, NFC (#150443)
Update docs to state that reduction is supported on OpenMP `loop` and
`teams` standalone and compound constructs.

(cherry picked from commit 15980624ac516ae2dbbf1f2cd24d63de0f9fd2be)
2025-08-05 10:47:24 +02:00
Phoebe Wang
78ce57ca69 [X86][AVX10.2] Fix VNNIINT16 maskz intrinsics arguments order (#151077)
For maskz intrinsics, the first argument is always the mask.

(cherry picked from commit 3ea3e334cc19cdd34416b546ac4b4a24b2018a28)
2025-08-05 10:41:53 +02:00
Zhaoxin Yang
80a6bc76cf [lld][LoongArch] Check that the relocation addend is zero before applying relaxation to R_LARCH_GOT_PC_{HI20,LO12} (#151264)
Linker relaxation to R_LARCH_GOT_PC_{HI20,LO12} is only possible when
the addend of the relocation is zero.

Note: For `ld.bfd`, GOT references with non-zero addends will trigger an
assert in LoongArch, but `lld` handles these cases without any errors.
```
ld.bfd: BFD (GNU Binutils) 2.44.0 assertion fail
/usr/src/debug/binutils/binutils-gdb/bfd/elfnn-loongarch.c:4248
```

(cherry picked from commit 4ec8503e4c480f52426ddd03619b017f19a2f452)
2025-08-01 09:12:18 +02:00
Serge Pavlov
f207cb4ed2 [Analysis] Prevent revisiting block when searching for noreturn vars (#150582)
When searching for noreturn variable initializations, do not visit CFG
blocks that are already visited, it prevents hanging the analysis.

It must fix https://github.com/llvm/llvm-project/issues/150336.

(cherry picked from commit 330b40e11fd20e9a29b9c24de17e4ba23afeedc6)
2025-08-01 09:11:33 +02:00
Owen Pan
2dbbc27292 [clang-format] Disable IntegerLiteralSeparator for C++ before c++14 (#151273)
Fixes #151102

(cherry picked from commit 5fc482cfc0fa70c98e14d64d83dffbf7da03c303)
2025-08-01 09:10:57 +02:00
Martin Storsjö
71f9b12e1b [llvm-objcopy] [COFF] Ignore associative sections in executables (#151143)
COFF associative sections is a feature where relocatable object files
can have section snippets marked as related to another section snippet,
so they are kept or discarded in relation to that other section snippet.

When llvm-objcopy removes sections, it also removes sections that are
marked as associative to the removed section (as the associative
sections otherwise would end up orphaned).

In a linked executable module (EXE or DLL), section associativity is
meaningless - thus, we should ignore those fields from the input.

After linking, GNU ld keeps the SectionDefinition auxillary part of
symbols intact as it was in the source object file, which means that it
references section numbers in the source object files.

This fixes https://github.com/llvm/llvm-project/issues/53433.

(cherry picked from commit fcbbcffd2e6ea30097809ba0cd1e3b6003fa862f)
2025-08-01 09:10:24 +02:00
Evgenii Kudriashov
773b718c25 [LLD][X86] Match delayLoad thunk with MSVC (#149521)
Previously we saved registers in the shadow space of callee before
calling __delayLoadHelper2. Now we save arguments in the shadow space of
the caller and allocate shadow space for the callee.

Fixes #51941

---------

Co-authored-by: Benjamin Santerre <benjamin.santerre@gmail.com>
(cherry picked from commit 75b79c9238bc083cdff2d2364be40633fdf4d1ad)
2025-08-01 09:09:50 +02:00
Fabio D'Urso
d436146305 [scudo] Make Ptr volatile so that the malloc and free calls are not optimized out (#149944)
This fixes the test failure seen in the discussion about
https://github.com/llvm/llvm-project/pull/148066.

(cherry picked from commit fcdcc4ea7ac960c79246b3bd428f14ea350e63e2)
2025-08-01 09:09:10 +02:00
Aaron Ballman
3b53c84e33 [C23] Handle type compatibility for enumerations better (#150282)
An enumeration is compatible with its underlying type, which means that
code like the following should be accepted:

  struct A { int h; };
  void func() {
    extern struct A x;
    enum E : int { e };
    struct A { enum E h; };
    extern struct A x;
  }

because the structures are declared in different scopes, the two
declarations of 'x' are both compatible.

Note, the structural equivalence checker does not take scope into
account, but that is something the C standard requires. This means we
are accepting code we should be rejecting per the standard, like:

  void func() {
    struct A { int h; };
    extern struct A x;
    enum E : int { e };
    struct A { enum E h; };
    extern struct A x;
  }

Because the structures are declared in the same scope, the type
compatibility rule require the structures to use the same types, not
merely compatible ones.

Fixes #149965

(cherry picked from commit 315e2e28b13285a352d409b739ba31fb453d661b)
2025-08-01 09:06:25 +02:00
David Spickett
6df1a2879a [llvm][release] Add links to commonly used release packages (#147719)
This adds download links to the GitHub release pages for common
platforms. The automatically built packages' links are automatically
revealed once the builds are complete. For packages built by hand,
hidden links are included in the text for release uploaders to reveal
later.

The approach taken:
* "LLVM x.y.z Release" becomes the title for this links section.
* Automatically built packages are commented out with special markers so
we can find them to uncomment them later.
* There is placeholder text for the time between release creation and
release tasks finishing.
* Hand built packages have release links but these will need to be
un-commented by release uploaders.
* I have used vendor names for the architectures, that casual users
would recognise.
* Their signature file is linked as well. I expect most will ignore this
but better to show it to remind people it exists.
* I called it "signature" as a generic term to cover the .jsonl and .sig
files. Instructions to use these were added to the text in a previous
change.

(cherry picked from commit e8b7183d866f9d51511d5570f5f1f632046ef983)
2025-08-01 09:05:47 +02:00
David Spickett
b1c834f27c [lldb][AArch64][Linux] Show MTE store only setting in mte_ctrl (#145033)
This controls whether tag checking is performed for loads and
stores, or stores only.

It requires a specific architecture feature which we detect
with a HWCAP3 and cpuinfo feature.

Live process tests look for this and adjust expectations
accordingly, core file tests are using an updated file with
this feature enabled.

The size of the core file has increased and there's nothing
I can do about that. Could be the presence of new architecure
features or kernel changes since I last generated them.

I can generate a smaller file that has the tag segment,
but that segment does not actually contain tag data. So
that's no use.

(cherry picked from commit 0209e76fe6440bc45a9ed61b9671d9593db10957)
2025-08-01 09:05:14 +02:00
David Spickett
9ad630fcb7 [lldb][AArch64] Add HWCAP3 to register field detection (#145029)
This will be used to detect the presence of Arm's new Memory Tagging
store only checking feature. This commit just adds the plumbing to get
that value into the detection function.

FreeBSD has not allocated a number for HWCAP3 and already has AT_ARGV
defined as 29. So instead of attempting to read from FreeBSD processes,
I've explicitly passed 0. We don't want to be reading some other entry
accidentally.

If/when FreeBSD adds HWCAP3 we can handle it like we do for
AUXV_FREEBSD_AT_HWCAP.

No extra tests here, those will be coming with the next change for MTE
support.

(cherry picked from commit d26ca8b87266024546501051ccaf75cb3756aee3)
2025-08-01 09:05:13 +02:00
Daniil Kovalev
614544048c [PAC][compiler-rt] Fix init/fini array signing schema (#150691)
When `ptrauth_calls` is present but `ptrauth_init_fini` is not, compiler
emits raw unsigned pointers in `.init_array`/`.fini_array` sections.
Previously, `__do_init`/`__do_fini` pointers, which are explicitly added
to the sections, were implicitly signed (due to the presense of
`ptrauth_calls`), while all the other pointers in the sections were
implicitly added by the compiler and thus non-signed.. As a result, the
sections contained a mix of unsigned function pointers and function
pointers signed with default signing schema.

This patch introduces use of inline assembly for this particular case,
so we can manually specify that we do not want to sign the pointers.

Note that we cannot use `__builtin_ptrauth_strip` for this purpose since
its result is not a constant expression.

(cherry picked from commit 19ba224fb8a925d095d84836bc9896bf564dfd99)
2025-08-01 09:04:25 +02:00
Konstantin Varlamov
6943f1bf77 [libc++][hardening] Introduce assertion semantics. (#149459)
Assertion semantics closely mimic C++26 Contracts evaluation semantics.
This brings our implementation closer in line with C++26 Library Hardening
(one particular benefit is that using the `observe` semantic makes adopting
hardening easier for projects).

(cherry picked from commit 3eee9fc2c4d1973904b1a26fa96a8c7473ef6a5e)
2025-08-01 09:02:53 +02:00
kikairoya
8c3ef23106 [clang][DebugInfo] Disable VTable debug info (#130255) on COFF platforms
On COFF platform, d1b0cbff806b50d399826e79b9a53e4726c21302 generates
a debug info linked with VTable even if that is dllimport-ed. That
causes an access violation while performing runtime pseudo-relocation
if the debug section is stripped.
For the release branch, we simply disable VTable debug info on COFF
platform to avoid this problem.

Fixes #149639
2025-08-01 08:59:39 +02:00
Aaron Ballman
4ca9a4bb35 [[gnu::nonstring]] should work on pointers too (#150974)
Clang's current implementation only works on array types, but GCC (which
is where we got this attribute) supports it on pointers as well as
arrays.

Fixes #150951

(cherry picked from commit 837b2d464ff16fe0d892dcf2827747c97dd5465e)
2025-08-01 08:55:21 +02:00
Jacek Caban
7e51c08c82 [LLD][COFF] Allow symbols with empty chunks to have no associated output section in the PDB writer (#149523)
If a chunk is empty and there are no other non-empty chunks in the same
section, `removeEmptySections()` will remove the entire section. In this
case, use a section index of 0, as the MSVC linker does, instead of
asserting.

(cherry picked from commit 1ab04fc94c5f68ad0dc6755e3914f2895b85e720)
2025-08-01 08:54:34 +02:00
Tobias Hieta
d8e9216c27 Bump version to 21.1.0-rc2 2025-07-29 16:33:06 +02:00
Younan Zhang
2ec38abcba [Clang] Fix a partial ordering bug involving CTAD injected template arguments (#149782)
The synthesized deduction guides use injected template arguments for
distinguishment of explicit and implicit deduction guides.

In partial ordering, we may substitute into these injected types when
checking consistency. Properly substituting them needs the instantiated
class template specializations which isn't the case at that point. So
instead, we check their template specialization types.

No release note because I think we want a backport, after baking it for
a couple of days.

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

(cherry picked from commit 07faafe4a4d0a5bd82b648aa9717783f001ddfae)
2025-07-29 12:58:25 +02:00
Trevor Gross
a3d182bfe3 [X86] Align f128 and i128 to 16 bytes when passing on x86-32 (#138092)
The i386 psABI specifies that `__float128` has 16 byte alignment and
must be passed on the stack; however, LLVM currently stores it in a
stack slot that has an offset of 4. Add a custom lowering to correct
this alignment to 16-byte.

i386 does not specify an `__int128`, but it seems reasonable to keep the
same behavior as `__float128` so this is changed as well. There also
isn't a good way to distinguish whether a set of four registers came
from an integer or a float.

The main test demonstrating this change is `store_perturbed` in
`llvm/test/CodeGen/X86/i128-fp128-abi.ll`.

Referenced ABI:
https://gitlab.com/x86-psABIs/i386-ABI/-/wikis/uploads/14c05f1b1e156e0e46b61bfa7c1df1e2/intel386-psABI-2020-08-07.pdf
Fixes: https://github.com/llvm/llvm-project/issues/77401

(cherry picked from commit a78a0f8d204393a0cce367b63395bad90311c1b8)
2025-07-29 12:56:58 +02:00
cmtice
317403d705 [LLDB] Switch to using DIL as default implementation for 'frame var'. (#147887)
(cherry picked from commit f5c676d6d95dc63b8dcb43dd2e4dfc913a9c5a50)
2025-07-29 10:00:12 +02:00
Jacek Caban
bbc8346e6b [LLD][COFF] Avoid resolving symbols with -alternatename if the target is undefined (#149496)
This change fixes an issue with the use of `-alternatename` in the MSVC
CRT on ARM64EC, where both mangled and demangled symbol names are
specified. Without this patch, the demangled name could be resolved to
an anti-dependency alias of the target. Since chaining anti-dependency
aliases is not allowed, this results in an undefined symbol.

The root cause isn't specific to ARM64EC, it can affect other targets as
well, even when anti-dependency aliases aren't involved. The
accompanying test case demonstrates a scenario where the symbol could be
resolved from an archive. However, because the archive member is pulled
in after the first pass of alternate name resolution, and archive
members don't override weak aliases, eager resolution would incorrectly
skip it.

(cherry picked from commit ac31d64a64e8a648f6834f4cf9de10c56c8d1083)
2025-07-29 09:58:55 +02:00
Jacek Caban
f1bca175af [LLD][COFF] Move resolving alternate names to SymbolTable (NFC) (#149495)
(cherry picked from commit 38cd66a6ceef5a3208367967d8537b6a7e31ebc0)
2025-07-29 09:58:55 +02:00
Eli Friedman
dc90bf0329 [clang] Fix const eval of constexpr-unknown relational comparisons. (#150088)
Like in other places, ignore the reference type of the base. (It might
make sense to refactor this at some point.)

Fixes #150015.

(cherry picked from commit bba846773c7dfce0f95b8846672d8dd5fa8912be)
2025-07-29 09:57:43 +02:00
Nikita Popov
81a3436485 [CodeGen] More consistently expand float ops by default (#150597)
These float operations were expanded for scalar f32/f64/f128, but not
for f16 and more problematically, not for vectors. A small subset of
them was separately set to expand for vectors.

Change these to always expand by default, and adjust targets to mark
these as legal where necessary instead.

This is a much safer default, and avoids unnecessary legalization
failures because a target failed to manually mark them as expand.

Fixes https://github.com/llvm/llvm-project/issues/110753.
Fixes https://github.com/llvm/llvm-project/issues/121390.

(cherry picked from commit fe0dbe0f2950d95071be7140c7b4680f17a7ac4e)
2025-07-29 09:57:11 +02:00
Felix Weiglhofer
431af6d04c opencl: Ensure printf symbol is not mangled. (#150210)
Fixes #122453.

(cherry picked from commit a22d010002baf761f84d0a8fa5fcaaf6f3b1455f)
2025-07-29 09:55:29 +02:00
Martin Storsjö
67cec1afdb [lldb] [Windows] Silence format string warnings (#150886)
This fixes the following build warnings in a mingw environment:

../../lldb/source/Host/windows/MainLoopWindows.cpp:226:50: warning:
format specifies type 'int' but the argument has type
'IOObject::WaitableHandle' (aka 'void *') [-Wformat]
226 | "File descriptor %d already monitored.", waitable_handle);
| ~~ ^~~~~~~~~~~~~~~
../../lldb/source/Host/windows/MainLoopWindows.cpp:239:49: warning:
format specifies type 'int' but the argument has type 'DWORD' (aka
'unsigned long') [-Wformat]
238 | error = Status::FromErrorStringWithFormat("Unsupported file type
%d",
| ~~
| %lu
      239 |                                                 file_type);
          |                                                 ^~~~~~~~~
    2 warnings generated.

(cherry picked from commit 98ec927fcb8697a6f6df64298835917aa1d0d3c1)
2025-07-29 09:54:48 +02:00
Nikita Popov
c52ff1a825 Revert "[MIPS]Fix QNaNs in the MIPS legacy NaN encodings" (#150773)
Reverts llvm/llvm-project#139829.

We can't just randomly change the value of constants during lowering.

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

(cherry picked from commit 525090e83ca392753d371602b5e64f06e7debd9a)
2025-07-29 09:54:17 +02:00
Rainer Orth
d4955d9b95 [Driver] Default to -mv8plus on 32-bit Solaris/SPARC (#150176)
While investigating PR #149990, I noticed that while both the Oracle
Studio compilers and GCC default to `-mv8plus` on 32-bit Solaris/SPARC,
Clang does not.

This patch fixes this by enabling the `v8plus` feature.

Tested on `sparcv9-sun-solaris2.11` and `sparc64-unknown-linux-gnu`.

(cherry picked from commit 06233892e84f96a3b4e05338cd4f6c12b8f5a185)
2025-07-29 09:53:42 +02:00
Zhaoxin Yang
16d81f85e9 [lld][LoongArch] Support relaxation during TLSDESC GD/LD to IE/LE conversion (#123730)
Complement https://github.com/llvm/llvm-project/pull/123715. When
relaxation enable, remove redundant NOPs.

(cherry picked from commit 2a5cd50c469891a0bc918b42785cbf6fd6132a50)
2025-07-29 09:51:50 +02:00
yingopq
bde97f2cef [Mips] Fix wrong ELF FP ABI info when inline asm was empty (#146457)
When Mips process emitStartOfAsmFile and updateABIInfo, it did not know
the real value of IsSoftFloat and STI.useSoftFloat(). And when inline
asm instruction was empty, Mips did not process asm parser, so it would
not do TS.updateABIInfo(STI) again and at this time the value of
IsSoftFloat is correct.

Fix #135283.

(cherry picked from commit 778fb76e6308534a63239a91b98f5dad055f6fdb)
2025-07-29 09:44:28 +02:00
David Truby
949c6cc95a [flang-rt] Remove hard-coded dependency on compiler-rt path on Windows (#150244)
This fixes an issue where if the build folder is no longer present flang
cannot link anything on Windows because the path to compiler-rt in the
binary is hard-coded. Flang already links compiler-rt on Windows so it
isn't necessary for flang-rt to specify that it depends on compiler-rt
at all, other than for the unit tests, so instead we can move that logic
into the unit test compile lines.

(cherry picked from commit c20a95a7ddd8219f3e587e335a0a8e3f4613fc47)
2025-07-29 09:43:38 +02:00
Yingwei Zheng
8c7cf7c06d [CodeGenPrepare] Make sure that AddOffset is also a loop invariant (#150625)
Closes https://github.com/llvm/llvm-project/issues/150611.

(cherry picked from commit 2d0ca09305fcece75e2c501f1ec74aa6eada69a0)
2025-07-29 09:37:27 +02:00
cvspvr
9ebb0abb02 [lldb] Allow building using Mingw-w64 on Windows. (#150398)
I wasn't able to build lldb using Mingw-w64 on Windows without changing
these 3 lines. It seems like `std::atomic<bool>` wasn't being found
without `#include <atomic>` and `ceil` was defaulting to `std::ceil`
instead of `std::chrono::ceil`, but I'm not smart enough to know the
root cause. I'm sure I'm not the first people to try and compile lldb
(and clang and lld) with Mingw-w64 and I don't know if something is
wrong with my Mingw-w64, but my changes shouldn't have any affect if
they aren't needed.

(cherry picked from commit 1a32bcb4379fb90d2b764ac33b917de1431c6b16)
2025-07-29 08:56:03 +02:00
Garvit Gupta
c198dc74d0 Remove extraneous addition of -X flag in baremetal toolchain (#148855)
Commit 597ee88 moved the -X flag to a new position in the baremetal
toolchain's linker job, but unintentionally left the original instance in place.

This patch removes the redundant flag, ensuring -X is passed only once.

(cherry picked from commit 81651e9fd0a744423fc0435f199ef79fb3a91f02)
2025-07-29 08:55:40 +02:00
Aiden Grossman
b00e0d2a7e [CI] Backport recent changes to release branch
This patch backports all of the recent changes to the release branch. This
will get the CI functioning again. This backport also includes a couple
refactorings, but those will probably end up being necessary for backporting
future patches. They are relatively safe because they have already been
extensively tested on main and only impact the CI.
2025-07-28 13:21:44 +00:00
Eli Friedman
ece444008a [clang] Fix potential constant expression checking with constexpr-unknown.
071765749a70b22fb62f2efc07a3f242ff5b4c52 improved constexpr-unknown
diagnostics, but potential constant expression checking broke in the
process: we produce diagnostics in more cases. Suppress the diagnostics
as appropriate.

This fix affects -Winvalid-constexpr and the enable_if attribute. (The
-Winvalid-constexpr diagnostic isn't really important right now, but it
will become important if we allow constexpr-unknown with pre-C++23
standards.)

Fixes #149041.  Fixes #149188.
(cherry picked from commit 6a60f18997d62b0e2842a921fcb6beb3e52ed823)
2025-07-28 10:59:44 +02:00
Hervé Poussineau
52dfd4a272 [docs] Add clang/llvm release notes for mipsel-windows-* targets 2025-07-28 09:43:41 +02:00
Sudharsan Veeravalli
0d8606fc85 [RISCV] Pass sign-extended value to isInt check in expandMul (#150211)
In the `isInt` check that was added in #147661 we were passing the
zero-extended `uint64_t` value instead of the sign-extended one.

(cherry picked from commit d3937e2d12648caa49fd80f9520a391fde2f7ba5)
2025-07-28 09:40:38 +02:00
Rainer Orth
be21c1395e [Driver] Default to -mcpu=ultrasparc3 on Solaris/SPARC (#149990)
Prompted by PR #149652, this patch changes the Solaris/SPARC default to
-mcpu, matching both the Oracle Studio 12.6 compilers and GCC 16:
[[PATCH] Default to -mcpu=ultrasparc3 on
Solaris/SPARC](https://gcc.gnu.org/pipermail/gcc-patches/2025-July/690191.html).
This is equivalent to enabling the `vis2` feature.

Tested on `sparcv9-sun-solaris2.11` and `sparc64-unknown-linux-gnu`.

(cherry picked from commit 0f235695709d2505651a55ec7f3c8b7fba2b2dbb)
2025-07-28 09:40:11 +02:00
Slava "nerfur" Voronzoff
aae69e9f84 Adding Loongarch64 to OpenBSD parts (#149737)
Adding Loongarch64 to OpenBSD parts

(cherry picked from commit 5eecbc018bfdf6f262647de739f35230596a1b8f)
2025-07-28 09:39:42 +02:00
Konstantin Varlamov
ee86ae0a69 [libc++][hardening] Add an experimental function to log hardening errors (#149452)
Unlike `verbose_abort`, this function merely logs the error but does not
terminate execution. It is intended to make it possible to implement the
`observe` semantic for Hardening.

(cherry picked from commit d750c6de8a75cbe2bc16c136764195471be8f0b7)
2025-07-28 09:39:10 +02:00
Simon Pilgrim
1ddf4e3887 [X86] getTargetConstantBitsFromNode - early-out if the element bitsize doesn't align with the source bitsize (#150184)
As we use getTargetConstantBitsFromNode in a wider variety of places we can't guarantee that all the sources match (or are legal) anymore - better to early out than assert.

Fixes #150117

(cherry picked from commit 33455825428f9e1b7998a66e228da7f6d483acf8)
2025-07-28 09:38:40 +02:00
Owen Pan
6077f45cfb [clang-format] Add AfterNot to SpaceBeforeParensOptions (#150367)
Closes #149971

(cherry picked from commit 97c953406d68357dddb8b624cd32c8e435a9fcfb)
2025-07-28 09:38:15 +02:00
Krzysztof Parzyszek
9554152c8a [flang][OpenMP] Avoid analyzing assumed-size array bases (#150324)
A check for character substrings masquerading as array sections was
using expression analyzer on the array base. When this array happened to
be an assumed-size array, the analyzer emitted a semantic error that did
not correspond to any issue with the source code.

To avoid that, check whether the object is an assumed-size array before
using the expression analyzer on it.

While at it, replace the call to GetShape with a simple check for rank,
since that's the only information needed.

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

(cherry picked from commit 8fcbd06b25fd0c1b4bc4a4c8775129f7dab1affd)
2025-07-28 09:37:49 +02:00
circuit10
704f542b3d [X86] Fix misassemble due to not storing registers to state machine on RParen (#150252)
This fixes #116883.

The x86 parser saves any register it encounters to a TmpReg field in its
state machine, then on encountering the next valid token immediately
afterwards saves it to either BaseReg, or IndexReg if BaseReg was
already filled. However, this saving logic was missing on the RParen
token handler, causing the parser to "forget" the register immediately
beforehand. This also would prevent later validation logic from
detecting the addressing mode as invalid, leading to a silent
misassembly rather than an error.

(cherry picked from commit a073cbbb1aeaaeac01b12e818fe47e4c04080aac)
2025-07-28 09:37:08 +02:00
Dunbobbin
fd13e381e4 [DTLTO] Add Clang release note for LLVM 21
DTLTO-related Clang changes were cherry-picked to the LLVM 21
branch in https://github.com/llvm/llvm-project/pull/149978.

This commit adds the corresponding release note.
2025-07-28 09:35:14 +02:00
Orlando Cazalet-Hyams
ede9fbeac8 [KeyInstr] Inline asm atoms (#149076)
(cherry picked from commit bbe912f1e74252f1f57b5d6c6d97a418947f4aa0)
2025-07-28 09:34:47 +02:00
Jessica Clarke
3378b765f8 [Sparc] Remove bogus stack adjustment for LD/GD TLS (#149890)
This argument is the number of bytes to adjust the stack by for the
duration of the call. In most cases, PEI is able to eliminate the
corresponding call frame pseudos, folding them into the initial stack
frame allocation (rounded up to stack alignment), where it just ends up
allocating more space than needed. However, in the rare case where this
cannot be done, e.g. due to the use of a dynamic alloca, the 1 byte
stack adjustment persists and results in a misaligned stack for the
duration of the call. This has been the case ever since TLS support was
added in cb1dca602c43 ("[Sparc] Add support for TLS in sparc."), and I
can only assume that 1 was used erroneously thinking that it is the
number of arguments (as there is 1 register argument for the call), not
the number of bytes for on-stack arguments.

Fixes: https://github.com/llvm/llvm-project/issues/149808
(cherry picked from commit 4b99eb2eb49d8fcdb29ba494501e481cf09831ae)
2025-07-28 09:33:39 +02:00
Jessica Clarke
509ec13f26 [NFC][Sparc] Pre-commit a test showing inefficient and broken LD/GD TLS
(cherry picked from commit dd36a6901249796a175c3058a50d97cc3a7ba52c)
2025-07-28 09:33:39 +02:00
Luke Lau
5345dc9cd3 [RISCV] Don't lose elements from False in vmerge -> vmv peephole (#149720)
In the vmerge peephole, we currently allow different AVLs for the vmerge
and its true operand.
If vmerge's VL > true's VL, vmerge can "preserve" elements from false
that would otherwise be clobbered with a tail agnostic policy on true.

    mask	1 1 1 1 0 0 0 0
    true	x x x x|. . . . AVL=4
    vmerge	x x x x f f|. . AVL=6

If we convert this to vmv.v.v we will lose those false elements:

    mask	1 1 1 1 0 0 0 0
    true	x x x x|. . . . AVL=4
    vmv.v.v	x x x x . .|. . AVL=6

Fix this by checking that vmerge's AVL is <= true's AVL.

Should fix #149335

(cherry picked from commit eafe31b293a5166522fff4f3e2d88c2b5c881381)
2025-07-28 09:30:12 +02:00
Ryotaro Kasuga
ba5aa84b54 [MachinePipeliner] Fix incorrect dependency direction (#149436)
This patch fixes a bug introduced in #145878. A dependency was added in
the wrong direction, causing an assertion failure due to broken
topological order.

(cherry picked from commit 6df012ab48ececd27359bdc9448ee101b39eea7a)
2025-07-28 09:29:43 +02:00
Florian Hahn
6df2bfd66b [AArch64,TTI] Remove RealUse check for vector insert/extract costs. (#146526)
getVectorInstrCostHelper would return costs of zero for vector
inserts/extracts that move data between GPR and vector registers, if
there was no 'real' use, i.e. there was no corresponding existing
instruction.

This meant that passes like LoopVectorize and SLPVectorizer, which
likely are the main users of the interface, would understimate the cost
of insert/extracts that move data between GPR and vector registers,
which has non-trivial costs.

The patch removes the special case and only returns costs of zero for
lane 0 if it there is no need to transfer between integer and vector
registers.

This impacts a number of SLP test, and most of them look like general
improvements.I think the change should make things more accurate for any
AArch64 target, but if not it could also just be Apple CPU specific.

I am seeing +2% end-to-end improvements on SLP-heavy workloads.

PR: https://github.com/llvm/llvm-project/pull/146526
2025-07-28 09:28:14 +02:00
Brian Cain
f6c4f0eb70 [lld] Add thunks for hexagon (#111217)
Without thunks, programs will encounter link errors complaining that the
branch target is out of range. Thunks will extend the range of branch
targets, which is a critical need for large programs. Thunks provide
this flexibility at a cost of some modest code size increase.

When configured with the maximal feature set, the hexagon port of the
linux kernel would often encounter these limitations when linking with
`lld`.

The relocations which will be extended by thunks are:

* R_HEX_B22_PCREL, R_HEX_{G,L}D_PLT_B22_PCREL, R_HEX_PLT_B22_PCREL
relocations have a range of ± 8MiB on the baseline
* R_HEX_B15_PCREL: ±65,532 bytes
* R_HEX_B13_PCREL: ±16,380 bytes
* R_HEX_B9_PCREL: ±1,020 bytes

Fixes #149689

Co-authored-by: Alexey Karyakin <akaryaki@quicinc.com>

---------

Co-authored-by: Alexey Karyakin <akaryaki@quicinc.com>
(cherry picked from commit b42f96bc057fd9e31572069b241ba130c21144e5)
2025-07-28 09:27:54 +02:00
Nikolas Klauser
564ed8e064 [libc++] Fix hash_multi{map,set}::insert (#149290)
(cherry picked from commit be3d614cc13f016b16634e18e10caed508d183d2)
2025-07-28 09:27:10 +02:00
Carlos Seo
3db29aaee5 [Flang] Fix a crash when equivalence and namelist statements are used (#150081)
Check for equivalence when generating namelist descriptors in IO.cpp.

Fixes #124489
2025-07-24 12:07:34 +02:00
Volodymyr Sapsai
1db54c705a [clang][deps] Add a release note for fixing crashes in clang-scan-deps. (#149857)
(cherry picked from commit dbc41dd5d827a3e13625a66fd2bfa83a8a4dfe83)
2025-07-24 12:04:01 +02:00
Carlos Seo
e43496bacf [Flang] Fix ASSIGN statement (#149941)
Handle the case where the assigned variable also has a pointer
attribute.

Fixes #121721

(cherry picked from commit fc0a978327215aa8883ae6f18d1e316f3c04520a)
2025-07-24 12:03:42 +02:00
Kareem Ergawy
4d6604adf1 [flang][OpenMP] Restore reduction processor behavior broken by #145837 (#150178)
Fixes #149089 and #149700.

Before #145837, when processing a reduction symbol not yet supported by
OpenMP lowering, the reduction processor would simply skip filling in
the reduction symbols and variables. With #145837, this behvaior was
slightly changed because the reduction symbols are populated before
invoking the reduction processor (this is more convenient to shared the
code with `do concurrent`).

This PR restores the previous behavior.

(cherry picked from commit 36c37b019b5daae79785e8558d693e6ec42b0ebd)
2025-07-24 12:03:24 +02:00
Florian Hahn
a91da31dd3 [LV] Vectorize maxnum/minnum w/o fast-math flags. (#148239)
Update LV to vectorize maxnum/minnum reductions without fast-math flags,
by adding an extra check in the loop if any inputs to maxnum/minnum are
NaN, due to maxnum/minnum behavior w.r.t to signaling NaNs. Signed-zeros
are already handled consistently by maxnum/minnum.

If any input is NaN,
 *exit the vector loop,
 *compute the reduction result up to the vector iteration that contained
   NaN inputs and
 * resume in the scalar loop

New recurrence kinds are added for reductions using maxnum/minnum
without fast-math flags.

PR: https://github.com/llvm/llvm-project/pull/148239
2025-07-24 12:02:55 +02:00
Heejin Ahn
dbe3ba0767 [WebAssembly] Unstackify registers with no uses in ExplicitLocals (#149626)
There are cases we end up removing some intructions that use stackified
registers after RegStackify. For example,

```wasm
bb.0:
  %0 = ...    ;; %0 is stackified
  br_if %bb.1, %0
bb.1:
```

In this code, br_if will be removed in CFGSort, so we should unstackify
%0 so that it can be correctly dropped in ExplicitLocals.

Rather than handling this in case-by-case basis, this PR just
unstackifies all stackifies register with no uses in the beginning of
ExplicitLocals, so that they can be correctly dropped.

Fixes #149097.

(cherry picked from commit b13bca7387a7aad6eaf3fa1c55bd06fe091f65ed)
2025-07-24 12:02:33 +02:00
Dunbobbin
132d231605 [DTLTO] Add COFF LLD release note for LLVM 21
DTLTO-related COFF LLD changes were cherry-picked to the LLVM 21
release branch in:
  https://github.com/llvm/llvm-project/pull/149979

This commit adds the corresponding release note, modeled after
the previously added note for ELF LLD DTLTO support.
2025-07-24 11:59:52 +02:00
Dunbobbin
6cd82c569d [DTLTO] Add LLVM release note for LLVM 21
Add a release note for the core LLVM changes for DTLTO.
2025-07-24 11:59:36 +02:00
bd1976bris
64a274fada [LLD][COFF] Make /wholearchive thin-archive member identifiers consistent (#145487)
A thin archive is an archive/library format where the archive itself
contains only references to member object files on disk, rather than
embedding the file contents.

For the non-/wholearchive case, we use the path to the archive member as
the identifier for thin-archive members (see comments in
`enqueueArchiveMember`). This patch modifies the /wholearchive path to
behave the same way.

Apart from consistency, my motivation for fixing this is DTLTO
(#126654), where having the member identifier be the path on disk allows
distribution of bitcode members during ThinLTO.

(cherry picked from commit 9f733f4324412ef89cc7729bf027cdcab912ceff)
2025-07-24 11:59:11 +02:00
Justus Klausecker
f66e874504 [LoopSimplifyCFG] Add check for missing loop preheader (#149743)
Closes #147869
Closes #149679

Adds a check for a missing loop preheader during analysis. This fixes a
nullptr dereference that happened whenever LoopSimplify was unable to
generate a preheader because the loop was entered by an indirectbr
instruction (as stated in the LoopSimplify.cpp doc comment).

(cherry picked from commit 04107209856bb39e041aa38cf40de0afa90a6b2d)
2025-07-24 11:58:40 +02:00
Orlando Cazalet-Hyams
233fdcb395 [KeyInstr] goto stmt atoms (#149101)
(cherry picked from commit 5c7c8558c856712a5ef11ff5f4e7ea7d3567f625)
2025-07-24 11:58:11 +02:00
bd1976bris
54c87e7fdd [DTLTO][LLD][COFF] Add support for Integrated Distributed ThinLTO (#148594)
This patch introduces support for Integrated Distributed ThinLTO (DTLTO)
in COFF LLD.

DTLTO enables the distribution of ThinLTO backend compilations via
external distribution systems, such as Incredibuild, during the
traditional link step: https://llvm.org/docs/DTLTO.html.

Note: Bitcode members of non-thin archives are not currently supported.
This will be addressed in a future change. This patch is sufficient to
allow for self-hosting an LLVM build with DTLTO if thin archives are
used.

Testing:
- LLD `lit` test coverage has been added, using a mock distributor to
avoid requiring Clang.
- Cross-project `lit` tests cover integration with Clang.

For the design discussion of the DTLTO feature, see:
https://github.com/llvm/llvm-project/pull/126654

(cherry picked from commit bbbbc093febffcae262cde1baa429b950842d76e)
2025-07-24 11:57:30 +02:00
bd1976bris
475ff348f1 [DTLTO][Clang] Add support for Integrated Distributed ThinLTO (#147265)
This patch introduces support for Integrated Distributed ThinLTO (DTLTO)
in Clang.

DTLTO enables the distribution of ThinLTO backend compilations via
external distribution systems, such as Incredibuild, during the
traditional link step: https://llvm.org/docs/DTLTO.html.

Testing:
- `lit` test coverage has been added to Clang's Driver tests.
- The DTLTO cross-project tests will use this Clang support.

For the design discussion of the DTLTO feature, see:
  https://github.com/llvm/llvm-project/pull/126654

(cherry picked from commit 5004c59803fdeb3389d30439a6cc8b1ff874df0c)
2025-07-24 11:54:36 +02:00
tangaac
6dde087056 [LoongArch] Strengthen stack size estimation for LSX/LASX extension (#146455)
This patch adds an emergency spill slot when ran out of registers.
PR #139201 introduces `vstelm` instructions with only 8-bit imm offset,
it causes no spill slot to store the spill registers.

(cherry picked from commit 64a0478e08829ec6bcae2b05e154aa58c2c46ac0)
2025-07-24 11:52:01 +02:00
Jens Reidel
02b2a77edb [compiler-rt][Mips] Fix stat size check on mips64 musl (#143301)
The sizes of the struct stat on MIPS64 differ in musl vs glibc.

See https://godbolt.org/z/qf9bcq8Y8 for the proof. Prior to this change,
compilation for MIPS64 musl would fail.

Signed-off-by: Jens Reidel <adrian@travitia.xyz>
(cherry picked from commit a5d6fa68e399dee9eb56f2671670085b26c06b4a)
2025-07-24 11:50:10 +02:00
Louis Dionne
da20f10b5d [libc++][NFC] Fix typos in the libc++ 21 release notes (#149536)
(cherry picked from commit d737fe2c91391a41a5b5ee8e3062d78a01936c61)
2025-07-24 11:49:46 +02:00
Ryan Prichard
1ad3d3aea6 [libc++][Android] Reenable 2 tests for Android (#149415)
Now that the Android clang has been upgraded to clang-r563880
(llvm.org/pr148998), these two tests pass again.
2025-07-24 11:49:10 +02:00
Orlando Cazalet-Hyams
c568a207d8 [KeyInstr] Fix verifier check (#149043)
The verifier check was in the wrong place, meaning it wasn't actually
checking many instructions.

Fixing that causes a test failure (coro-dwarf-key-instrs.cpp) because
coros turn off the feature but still annotate instructions with the
metadata (which is a supported situation, but the verifier doesn't like
it, and it's hard to teach the verifier to like it).

Fix that by avoiding emitting any key instruction metadata if the
DISubprogram has opted out of key instructions.

(cherry picked from commit 653872f782e1faaabc1da23769e6b35b10e74bde)
2025-07-24 11:48:40 +02:00
mintsuki
756f489266 LoongArch: Improve detection of valid TripleABI (#147952)
If the environment is considered to be the triple component as a whole,
so, including the object format, if any, and if that is the intended
behaviour, then the loongarch64 function `computeTargetABI()` should be
changed to not rely on `hasEnvironment()`, but, rather, to check if
there is a non-unknown environment set.

Without this change, using a (ideally valid) target of
loongarch64-unknown-none-elf, with a manually specified ABI of lp64s,
will result in a completely superfluous warning:

```
warning: triple-implied ABI conflicts with provided target-abi 'lp64s', using target-abi
```

(cherry picked from commit 9ed8816dc63776259d2190bdc8a7a29698c62749)
2025-07-22 10:44:55 +02:00
Alexandre Ganea
aaaa54269b [LLD][COFF] Follow up comments on pr146610 (#147152)
This is a follow-up PR for post-commit comments in
https://github.com/llvm/llvm-project/pull/146610

- Changed "exporteddllmain" references to "importeddllmain".
- Add support for x86 target and test coverage.
- Changed a comment to better express why we're skipping importing
`DllMain`.

(cherry picked from commit fcacd4e880c9a0b3f2bdaa43603aeddfa1b1cd2e)
2025-07-22 10:44:33 +02:00
Hervé Poussineau
3d520be273 [Mips] Correctly define IntPtrType (#145158)
Mips was the only architecture having PtrDiffType = SignedInt and
IntPtrType = SignedLong

This fixes a problem on mipsel-windows-gnu triple, where uintptr_t was
wrongly defined as unsigned long instead of unsigned int, leading to
problems in compiler-rt.

compiler-rt/lib/interception/interception_type_test.cpp:24:17: error:
static assertion failed due to requirement
'__sanitizer::is_same<unsigned long, unsigned int>::value':
24 | COMPILER_CHECK((__sanitizer::is_same<__sanitizer::uptr,
::uintptr_t>::value));
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

compiler-rt/lib/interception/../sanitizer_common/sanitizer_internal_defs.h:369:44:
note: expanded from macro 'COMPILER_CHECK'
      369 | #define COMPILER_CHECK(pred) static_assert(pred, "")
          |                                            ^~~~
compiler-rt/lib/interception/interception_type_test.cpp:25:17: error:
static assertion failed due to requirement '__sanitizer::is_same<long,
int>::value':
25 | COMPILER_CHECK((__sanitizer::is_same<__sanitizer::sptr,
::intptr_t>::value));
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

compiler-rt/lib/interception/../sanitizer_common/sanitizer_internal_defs.h:369:44:
note: expanded from macro 'COMPILER_CHECK'
      369 | #define COMPILER_CHECK(pred) static_assert(pred, "")
          |                                            ^~~~
compiler-rt/lib/interception/interception_type_test.cpp:27:17: error:
static assertion failed due to requirement '__sanitizer::is_same<long,
int>::value':
27 | COMPILER_CHECK((__sanitizer::is_same<::PTRDIFF_T,
::ptrdiff_t>::value));
| ^~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

compiler-rt/lib/interception/../sanitizer_common/sanitizer_internal_defs.h:369:44:
note: expanded from macro 'COMPILER_CHECK'
      369 | #define COMPILER_CHECK(pred) static_assert(pred, "")

(cherry picked from commit 13906724ff7aa1bc58202faac62690570dfe0dc3)
2025-07-22 10:44:08 +02:00
hev
7fd16eecf8 [LoongArch] Fix failure to widen operand for [X]VMSK{LT,GE,NE}Z (#149442)
Reported-by: tangyan <tangyan01@loongson.cn>
(cherry picked from commit 8a307ae61963a3f967052f7ea3c89aafa56934cf)
2025-07-22 10:43:28 +02:00
Timothy Herchen
25c1d7a357 [clang] Don't warn on zero literals with -std=c2y (#149688)
Fixes #149669; the old check compared with the end of the literal, but
we can just check that after parsing digits, we're pointing to one
character past the token start.

(cherry picked from commit 8366dc207a2e6b50cb8afe2d98fca68bd78bd0fa)
2025-07-22 10:43:04 +02:00
Abinaya Saravanan
17658dbedd [HEXAGON] Add AssertSext in sign-extended mpy (#149061)
The pattern i32xi32->i64, should be matched to the sign-extended
multiply op, instead of explicit sign- extension of the operands
followed by non-widening multiply (this takes 4 operations instead of
one). Currently, if one of the operands of multiply inside a loop is a
constant, the sign-extension of this constant is hoisted out of the loop
by LICM pass and this pattern is not matched by the ISEL.

This change handles multiply operand with Opcode of the type AssertSext
which is seen when the sign-extension is hoisted out-of the loop.
Modifies the DetectUseSxtw() to check for this.

(cherry picked from commit fcabb53f0c349885167ea3d0e53915e6c42271a7)
2025-07-22 10:39:51 +02:00
Sudharsan Veeravalli
cb92bc511e [RISCV] Swap source register operands in QC_SHLADD ISEL patterns (#149697)
The instruction does `rd = (rs1 << shamt) + rs2` but the ISEL patterns
had `rs1` and `rs2` the other way around which is incorrect.

(cherry picked from commit 84e689b1db02be1687c3093d66ace913250780bd)
2025-07-22 10:39:03 +02:00
Koakuma
5c69f70244 [SPARC][Driver] Move feature mode selection to Arch/Sparc.cpp (#149652)
This is so that it's performed also for flang and not just for clang.

This should fix https://github.com/llvm/llvm-project/issues/138494.

(cherry picked from commit 38fc453afdb6a4511b7c8e189f12a92559ecc396)
2025-07-22 10:38:31 +02:00
Brian Cain
51245ebda1 [lld] [hexagon] guard allocateAux: only if idx nonzero (#149690)
While building libclang_rt.asan-hexagon.so, lld would assert in
lld:🧝:hexagonTLSSymbolUpdate().

Fixes #132766

(cherry picked from commit 3e9ceae29f39456508eef5b4af4d3c895048706a)
2025-07-22 10:37:04 +02:00
Michał Górny
275fa26b0c Revert "[libclc] Add prepare-<triple> targets (#146700)"
This reverts commit 85d09de5fa19a32bbcc400928d55f9d633077640. This
change caused broken symlinks in the build directory, and the subsequent
commits fixing that introduced other issues.
2025-07-22 10:35:08 +02:00
Michał Górny
7814dca9a8 Revert "[libclc] Make library output directories explicit (#146833)"
This reverts commit 81e6552a3d6835c4e10eb981402febfac9df6156. This
change caused libclc to start installing broken symlinks that contain
absolute paths to the build directory rather than relative paths
within the install directory.
2025-07-22 10:35:07 +02:00
Michał Górny
b475893a15 Revert "[libclc] Fix target dependency"
This reverts commit 222e795347c14afce49df1540926f3a1ae493de4.
2025-07-22 10:35:07 +02:00
Michał Górny
69ee6a0edd Revert "[libclc] Change symlinks to copies on Windows (#147759)"
This reverts commit 9b5959dd9a0eb0fc005b92be7ef7f3a5e3377b81.
2025-07-22 10:35:07 +02:00
Michał Górny
68cae18965 Revert "[libclc] Move CMake for prepare_builtins to a subdirectory (#148815)"
This reverts commit 8a7a64873b13e6fd931b748fbf50b3da26fe7fca.  It broke
standalone builds since the necessary variables are now limited in scope
to `libclc/utils` while they are used in the top-level CMakeLists.
2025-07-22 10:35:07 +02:00
quic-areg
b5043a0940 [Hexagon][llvm-objdump] Improve disassembly of Hexagon bundles (#145807)
Hexagon instructions are VLIW "bundles" of up to four instruction words
encoded as a single MCInst with operands for each sub-instruction.
Previously, the disassembler's getInstruction() returned the full
bundle, which made it difficult to work with llvm-objdump.

For example, since all instructions are bundles, and bundles do not
branch, branch targets could not be printed.

This patch modifies the Hexagon disassembler to return individual
sub-instructions instead of entire bundles, enabling correct printing of
branch targets and relocations. It also introduces
`MCDisassembler::getInstructionBundle` for cases where the full bundle
is still needed.

By default, llvm-objdump separates instructions with newlines. However,
this does not work well for Hexagon syntax:

  { inst1
    inst2
    inst3
    inst4 <branch> } :endloop0

Instructions may be followed by a closing brace, a closing brace with
`:endloop`, or a newline. Branches must appear within the braces.

To address this, `PrettyPrinter::getInstructionSeparator()` is added and
overridden for Hexagon.

(cherry picked from commit ac7ceb3dabfac548caa993e7b77bbadc78af4464)
2025-07-22 10:34:17 +02:00
Jannick Kremer
0da291f8a6 Revert "Move python binding tests to lit framework" (#149012)
This reverts commit f8707f994af2582f6dc58190106946efeb43bf05.

(cherry picked from commit 7a9bef0166951a61bc7094514a20471ae45f6090)
2025-07-22 10:33:35 +02:00
Aiden Grossman
cbe68e5140 [libcxx] Switch to release branch runners
This ensures that if/when we bump the toolchain versions in the main
container that we do not break tests on the release branch.
2025-07-22 10:32:35 +02:00
clubby789
186df07d01 [DSE] Remove uninitialized from allockind when creating dummy zeroed variant function (#149336)
cc https://github.com/llvm/llvm-project/pull/138299

rustc sets `allockind("uninitialized")` - if we copy the attributes
as-is when creating a dummy function, Verify complains about
`allockind("uninitialized,zeroed")` conflicting, so we need to clear the
flag.

Co-authored-by: Jamie Hill-Daniel <jamie@osec.io>
(cherry picked from commit 74c396afb26dec74c0b799e218c63f1a26e90d21)
2025-07-22 10:31:55 +02:00
Owen Pan
607677c861 [clang-format] Fix a regression of annotating PointerOrReference (#149039)
Fixes #149010

(cherry picked from commit a8f5e9ed6b44562938ce07e2790be90be8f0a6b5)
2025-07-22 10:31:35 +02:00
Tomohiro Kashiwada
e36a7daae2 [Support/BLAKE3] quick fix for Cygwin build (#148635)
BLAKE3 1.8.2 ( imported in d2ad63a193216d008c8161879a59c5f42e0125cc )
fails to build for the Cygwin target.

see: https://github.com/BLAKE3-team/BLAKE3/issues/494

As a temporary workaround, add `&& !defined(__CYGWIN__)` to BLAKE3
locally.

resolves https://github.com/llvm/llvm-project/issues/148365

(cherry picked from commit 8de61eb01c9752f0488ed8b52d01fe3d0873ff6c)
2025-07-22 10:30:43 +02:00
Tobias Hieta
f1846e747d Use Parallel xz for test-suite sources. (#149389)
(cherry picked from commit 867ff3001e4e1e68b3f26c5ead281ea2208c4c48)
2025-07-22 10:30:13 +02:00
Peter Collingbourne
728030a452 compiler-rt: test: Use the host instead of the target to select %expect_crash.
When running tests in a cross-compiled build, %expect_crash is
run on the host, not the target, so we need to check the host
OS. config.host_os surprisingly refers to the target OS because it
is derived from CMAKE_SYSTEM_NAME which specifies the target. See:
https://cmake.org/cmake/help/latest/variable/CMAKE_SYSTEM_NAME.html

Another speculative fix for:
https://lab.llvm.org/buildbot/#/builders/193/builds/9070

(cherry picked from commit 968d38d1d7d9de2d5717457876bba2663b36f620)
2025-07-22 10:29:54 +02:00
Raphael Moreira Zinsly
1abeeabd65 [RISCV] Pass the MachineInstr flag as argument to allocateStack (#147531)
When not in the prologue we do not want to set the FrameSetup flag, by
passing the flag as argument we can use allocateStack correctly on those
cases.
This fixes the allocation and probe in eliminateCallFramePseudoInstr.

(cherry picked from commit 1db9eb23209826d9e799e68a9a4090f0328bf70c)
2025-07-21 18:54:42 +02:00
Tobias Hieta
cbcb48a88c Bump version to 21.1.0-rc1 2025-07-17 21:02:34 +02:00
Corentin Jabot
7ac3c62282 Revert "[Clang] Do not treat Foo -> const Foo conversion sequences as perfect" (#149272)
Reverts llvm/llvm-project#148613

Considering object argument conversion qualifications perfect leads to
situations where we prefer a non-template const qualified function over
a non-qualified template function, which is very wrong indeed.

I explored solutions to work around that, but instead, we might want to
go the GCC road and prefer the friend overload in the #147374 example,
as this seems a lot more consistent and reliable

(cherry picked from commit 28e1e7e1b4b059a2e42f68061475cddb4ad0a6a3)
2025-07-17 18:00:22 +02:00
Sirraide
dd7710b7fd [Clang] Reintroduce obsolete symbols in libclang.map (#149190)
This is a follow-up to #149079. Seems like we forgot about the fact that
the symbols also need to be in `libclang.map`.

(cherry picked from commit 7e0fde0c2f6b0b9d727ce9196956b36e91961ac4)
2025-07-17 17:59:42 +02:00
Yuxuan Chen
ad9051049d [Clang] Fix FE crash during CGCoroutine GRO Alloca Emission (#148962)
Fixes: https://github.com/llvm/llvm-project/issues/148953

Currently when coroutine return object type is const qualified, we don't
do direct emission. The regular emission logic assumed that the auto var
emission will always result in an `AllocaInst`. However, based on my
findings, NRVO var emissions don't result in `AllocaInst`s. Therefore,
this
[assertion](1a940bfff9/clang/lib/CodeGen/CGCoroutine.cpp (L712))
will fail.

Since the NRVOed returned object don't live on the coroutine frame, we
won't have the problem of it outliving the coroutine frame, therefore,
we can safely omit this metadata.

(cherry picked from commit c36156de45a0f5e24e7a4ee2259c3302ea814785)
2025-07-17 17:56:53 +02:00
Eli Friedman
2067574f54 [clang] Fix pointer comparisons between pointers to constexpr-unknown (#147663)
A constexpr-unknown reference can be equal to an arbitrary value, except
values allocated during constant evaluation. Fix the handling.

The standard is unclear exactly which pointer comparisons count as
"unknown" in this context; for example, in some cases we could use
alignment to prove two constexpr-unknown references are not equal. I
decided to ignore all the cases involving variables not allocated during
constant evaluation.

While looking at this, I also spotted that there might be issues with
lifetimes, but I didn't try to address it.

(cherry picked from commit 20c8e3c2a4744524396cc473a370cfb7855850b6)
2025-07-17 17:56:24 +02:00
Jonas Devlieghere
38158a93d8 [lldb] Document MCP tools & resources (#148708)
Add documentation for the tools and resources exposed by LLDB's MCP
server.

(cherry picked from commit e8dc96d9de14c4b2317b11b8bc6e9310113697b3)
2025-07-17 12:40:58 +02:00
Jonas Devlieghere
68e17aec8f [lldb] Add a release note for MCP support 2025-07-17 12:35:56 +02:00
Nikita Popov
194dd6679f [Support][BLAKE3] Restore static on blake3_hash4_neon (#149046)
This was dropped in #147948 and causes symbol conflicts if libblake3 is
also linked.

(cherry picked from commit 1754a7d5733d5305e4ec25ef0945b39d6882bb28)
2025-07-17 12:26:26 +02:00
Matt Arsenault
7c2c20dd9c RuntimeLibcalls: Fix calling conv of win32 div libcalls (#149098)
There's probably an existing test this should be added to,
but our test coverage is really bad that this wasn't caught
by one.

(cherry picked from commit 0110168f6aa5c8a8d02ffd9e62c7929ce6d24d26)
2025-07-17 10:29:47 +02:00
Aiden Grossman
46c566f579 [CI][Github] Switch windows to server 2022 (#148743)
This patch switches the windows testing over to server 2022 by switching
to the recently introduced runner set.

(cherry picked from commit 3248a6d76abccbbe78e853c76bc022b70d594347)
2025-07-17 10:29:31 +02:00
Sirraide
6ee4eedc2a [Clang] Reintroduce obsolete libclang symbols to avoid an ABI break (#149079)
For more context, see
https://github.com/llvm/llvm-project/pull/119269#issuecomment-3075444493,
but briefly, when removing ARCMigrate, I also removed some symbols in
libclang, which constitutes an ABI break that we don’t want, so this pr
reintroduces the removed symbols; the declarations are marked as
deprecated for future removal, and the implementations print an error
and do nothing, which is what we used to do when ARCMigrate was
disabled.

(cherry picked from commit 1600450f9098e5c9cb26840bd53f1be8a2559b7d)
2025-07-17 10:29:12 +02:00
Jordan Rupprecht
adb453c8a6 [Support][BLAKE3] Prefix more blake3 methods (#149007)
Added by #147948, blake3_xof_many and blake3_compress_subtree_wide cause
conflicts when linking llvm and blake3 statically into the same binary.
Similar to #148607.

(cherry picked from commit 60579ec3059b2b6cc9dad90eaac1ed363fc395a7)
2025-07-17 10:28:09 +02:00
Eli Friedman
04d4be501d [libclang] Fix version for symbol clang_visitCXXMethods (#148958)
Happened to spot this while looking at libclang.map for other reasons.
clang_visitCXXMethods was added in LLVM 21, not LLVM 20.

(cherry picked from commit 116110e1a93531a64d82f049b6e36403bc14f278)
2025-07-17 10:27:47 +02:00
Sudharsan Veeravalli
b71c9a4366 [RISCV] Fix issues in ORI to QC.INSBI transformation (#148809)
The transformation done in #147349 was incorrect since we were not
passing the input node of the `OR` instruction to the `QC.INSBI`
instruction leading to the generated instruction doing the wrong thing.
In order to do this we first needed to add the output register to
`QC.INSBI` as being both an input and output.

The code produced after the above fix will need a copy (mv) to preserve
the register input to the OR instruction if it has more than one use
making the transformation net neutral ( `6-byte QC.E.ORI/ORAI` vs
`2-byte C.MV + 4-byte QC.INSB`I). Avoid doing the transformation if
there is more than one use of the input register to the OR instruction.

(cherry picked from commit d67d91a9906366585162cebf292f923a3f28c8a6)
2025-07-17 10:27:16 +02:00
Craig Topper
49722f1df1 [RISCV] Remove incorrect and untested FrameIndex support from SelectAddrRegImm9. (#148779)
To fold a FrameIndex, we need to teach eliminateFrameIndex to respect
the uimm9 range.

(cherry picked from commit 63d099af146a19bc8fd5a791d6184125e6cc42e7)
2025-07-17 10:26:45 +02:00
Krzysztof Parzyszek
a0895b4581 [Frontend][OpenMP] Move isPrivatizingClause to OMP.h, NFC (#148644) 2025-07-16 16:17:00 +02:00
Sjoerd Meijer
7d803c868a [AArch64] Set the cache line size to 64 for the V2 and V3. (#148213)
This sets the cache line size to 64 for the Neoverse V2 and V3. I've
tested this with loop-interchange: it doesn't result in extra
compile-times, but it does enable a lot more interchange.
2025-07-16 16:17:00 +02:00
Sander de Smalen
d1517ec622 [AArch64] Ensure bundle expansion of MOVPRFX gets correct implicit ops (#148824)
By finalizing the bundle _after_ copying over the implicit-ops, it also
adds any implicit-defs to the BUNDLE.

Fixes https://github.com/llvm/llvm-project/issues/148645
2025-07-16 16:17:00 +02:00
Sander de Smalen
588b813079 [AArch64] Use correct regclass for spills of ZPR2/ZPR4 (#148806)
Commit a6293228fdd5aba8c04c63f02f3d017443feb3f2 forced the register
class of ZPR[24]StridedOrContiguous for spills/fills of ZPR2 and ZPR4,
but this may result in issues when the regclass for the fill is a
ZPR2/ZPR4 which would allow the register allocator to pick `z1_z2`,
which is not a supported register for ZPR2StridedOrContiguous that only
supports tuples of the form (strided) `z0_z8`, `z1_z9` or (contiguous,
start at multiple of 2) `z0_z1`, `z2_z3`. For spills we could add a new
register class that supports any of the tuple forms, but I've decided
to use two pseudos similar to the fills for consistency.

Fixes https://github.com/llvm/llvm-project/issues/148655
2025-07-16 16:17:00 +02:00
Martin Erhart
18624ae54b [mlir][SliceAnalysis] Fix stack overflow in graph regions (#139694)
This analysis currently just crashes when applied to a graph region that
has a use-def cycle. This PR fixes that by keeping track of the
operations the DFS has already visited when following use-def edges and
stopping once we visit an operation again.
2025-07-16 16:16:59 +02:00
Tobias Hieta
6296ebd45d Bump version to 21.1.0-git 2025-07-15 15:59:05 +02:00
598 changed files with 20861 additions and 8518 deletions

View File

@ -19,6 +19,7 @@ import sys
PROJECT_DEPENDENCIES = {
"llvm": set(),
"clang": {"llvm"},
"CIR": {"clang", "mlir"},
"bolt": {"clang", "lld", "llvm"},
"clang-tools-extra": {"clang", "llvm"},
"compiler-rt": {"clang", "lld"},
@ -55,6 +56,7 @@ DEPENDENTS_TO_TEST = {
".ci": {
"llvm",
"clang",
"CIR",
"lld",
"lldb",
"bolt",
@ -128,6 +130,7 @@ PROJECT_CHECK_TARGETS = {
"lldb": "check-lldb",
"llvm": "check-llvm",
"clang": "check-clang",
"CIR": "check-clang-cir",
"bolt": "check-bolt",
"lld": "check-lld",
"flang": "check-flang",
@ -141,6 +144,23 @@ PROJECT_CHECK_TARGETS = {
RUNTIMES = {"libcxx", "libcxxabi", "libunwind", "compiler-rt", "libc"}
# Meta projects are projects that need explicit handling but do not reside
# in their own top level folder. To add a meta project, the start of the path
# for the metaproject should be mapped to the name of the project below.
# Multiple paths can map to the same metaproject.
META_PROJECTS = {
("clang", "lib", "CIR"): "CIR",
("clang", "test", "CIR"): "CIR",
("clang", "include", "clang", "CIR"): "CIR",
("*", "docs"): "docs",
("llvm", "utils", "gn"): "gn",
(".github", "workflows", "premerge.yaml"): ".ci",
("third-party",): ".ci",
}
# Projects that should not run any tests. These need to be metaprojects.
SKIP_PROJECTS = ["docs", "gn"]
def _add_dependencies(projects: Set[str], runtimes: Set[str]) -> Set[str]:
projects_with_dependents = set(projects)
@ -233,21 +253,34 @@ def _compute_runtimes_to_build(
return _exclude_projects(runtimes_to_build, platform)
def _path_matches(matcher: tuple[str], file_path: tuple[str]) -> bool:
if len(file_path) < len(matcher):
return False
for match_part, file_part in zip(matcher, file_path):
if match_part == "*" or file_part == "*":
continue
if match_part != file_part:
return False
return True
def _get_modified_projects_for_file(modified_file: str) -> Set[str]:
modified_projects = set()
path_parts = pathlib.Path(modified_file).parts
for meta_project_files in META_PROJECTS.keys():
if _path_matches(meta_project_files, path_parts):
meta_project = META_PROJECTS[meta_project_files]
if meta_project in SKIP_PROJECTS:
return set()
modified_projects.add(meta_project)
modified_projects.add(pathlib.Path(modified_file).parts[0])
return modified_projects
def _get_modified_projects(modified_files: list[str]) -> Set[str]:
modified_projects = set()
for modified_file in modified_files:
path_parts = pathlib.Path(modified_file).parts
# Exclude files in the docs directory. They do not impact an test
# targets and there is a separate workflow used for ensuring the
# documentation builds.
if len(path_parts) > 2 and path_parts[1] == "docs":
continue
# Exclude files for the gn build. We do not test it within premerge
# and changes occur often enough that they otherwise take up
# capacity.
if len(path_parts) > 3 and path_parts[:3] == ("llvm", "utils", "gn"):
continue
modified_projects.add(pathlib.Path(modified_file).parts[0])
modified_projects.update(_get_modified_projects_for_file(modified_file))
return modified_projects
@ -267,6 +300,13 @@ def get_env_variables(modified_files: list[str], platform: str) -> Set[str]:
runtimes_check_targets_needs_reconfig = _compute_project_check_targets(
runtimes_to_test_needs_reconfig
)
# CIR is used as a pseudo-project in this script. It is built as part of the
# clang build, but it requires an explicit option to enable. We set that
# option here, and remove it from the projects_to_build list.
enable_cir = "ON" if "CIR" in projects_to_build else "OFF"
projects_to_build.discard("CIR")
# We use a semicolon to separate the projects/runtimes as they get passed
# to the CMake invocation and thus we need to use the CMake list separator
# (;). We use spaces to separate the check targets as they end up getting
@ -279,6 +319,7 @@ def get_env_variables(modified_files: list[str], platform: str) -> Set[str]:
"runtimes_check_targets_needs_reconfig": " ".join(
sorted(runtimes_check_targets_needs_reconfig)
),
"enable_cir": enable_cir,
}

View File

@ -1,7 +1,7 @@
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Does some stuff."""
"""Tests for compute_projects.py"""
import unittest
@ -104,6 +104,10 @@ class TestComputeProjects(unittest.TestCase):
env_variables["runtimes_check_targets_needs_reconfig"],
"check-cxx check-cxxabi check-unwind",
)
self.assertEqual(
env_variables["enable_cir"],
"OFF",
)
def test_clang_windows(self):
env_variables = compute_projects.get_env_variables(
@ -126,6 +130,32 @@ class TestComputeProjects(unittest.TestCase):
env_variables["runtimes_check_targets_needs_reconfig"],
"check-cxx check-cxxabi check-unwind",
)
self.assertEqual(env_variables["enable_cir"], "OFF")
def test_cir(self):
env_variables = compute_projects.get_env_variables(
["clang/lib/CIR/CMakeLists.txt"], "Linux"
)
self.assertEqual(
env_variables["projects_to_build"],
"clang;clang-tools-extra;lld;llvm;mlir",
)
self.assertEqual(
env_variables["project_check_targets"],
"check-clang check-clang-cir check-clang-tools",
)
self.assertEqual(
env_variables["runtimes_to_build"], "compiler-rt;libcxx;libcxxabi;libunwind"
)
self.assertEqual(
env_variables["runtimes_check_targets"],
"check-compiler-rt",
)
self.assertEqual(
env_variables["runtimes_check_targets_needs_reconfig"],
"check-cxx check-cxxabi check-unwind",
)
self.assertEqual(env_variables["enable_cir"], "ON")
def test_bolt(self):
env_variables = compute_projects.get_env_variables(
@ -158,6 +188,7 @@ class TestComputeProjects(unittest.TestCase):
self.assertEqual(env_variables["runtimes_to_build"], "")
self.assertEqual(env_variables["runtimes_check_targets"], "")
self.assertEqual(env_variables["runtimes_check_targets_needs_reconfig"], "")
self.assertEqual(env_variables["enable_cir"], "OFF")
def test_flang(self):
env_variables = compute_projects.get_env_variables(
@ -168,10 +199,11 @@ class TestComputeProjects(unittest.TestCase):
self.assertEqual(env_variables["runtimes_to_build"], "")
self.assertEqual(env_variables["runtimes_check_targets"], "")
self.assertEqual(env_variables["runtimes_check_targets_needs_reconfig"], "")
self.assertEqual(env_variables["enable_cir"], "OFF")
def test_invalid_subproject(self):
env_variables = compute_projects.get_env_variables(
["third-party/benchmark/CMakeLists.txt"], "Linux"
["llvm-libgcc/CMakeLists.txt"], "Linux"
)
self.assertEqual(env_variables["projects_to_build"], "")
self.assertEqual(env_variables["project_check_targets"], "")
@ -237,7 +269,7 @@ class TestComputeProjects(unittest.TestCase):
)
self.assertEqual(
env_variables["project_check_targets"],
"check-bolt check-clang check-clang-tools check-flang check-lld check-lldb check-llvm check-mlir check-polly",
"check-bolt check-clang check-clang-cir check-clang-tools check-flang check-lld check-lldb check-llvm check-mlir check-polly",
)
self.assertEqual(
env_variables["runtimes_to_build"],
@ -276,6 +308,66 @@ class TestComputeProjects(unittest.TestCase):
self.assertEqual(env_variables["runtimes_check_targets"], "check-libc")
self.assertEqual(env_variables["runtimes_check_targets_needs_reconfig"], "")
def test_premerge_workflow(self):
env_variables = compute_projects.get_env_variables(
[".github/workflows/premerge.yaml"], "Linux"
)
self.assertEqual(
env_variables["projects_to_build"],
"bolt;clang;clang-tools-extra;flang;libclc;lld;lldb;llvm;mlir;polly",
)
self.assertEqual(
env_variables["project_check_targets"],
"check-bolt check-clang check-clang-cir check-clang-tools check-flang check-lld check-lldb check-llvm check-mlir check-polly",
)
self.assertEqual(
env_variables["runtimes_to_build"],
"compiler-rt;libc;libcxx;libcxxabi;libunwind",
)
self.assertEqual(
env_variables["runtimes_check_targets"],
"check-compiler-rt check-libc",
)
self.assertEqual(
env_variables["runtimes_check_targets_needs_reconfig"],
"check-cxx check-cxxabi check-unwind",
)
def test_other_github_workflow(self):
env_variables = compute_projects.get_env_variables(
[".github/workflows/docs.yml"], "Linux"
)
self.assertEqual(env_variables["projects_to_build"], "")
self.assertEqual(env_variables["project_check_targets"], "")
self.assertEqual(env_variables["runtimes_to_build"], "")
self.assertEqual(env_variables["runtimes_check_targets"], "")
self.assertEqual(env_variables["runtimes_check_targets_needs_reconfig"], "")
def test_third_party_benchmark(self):
env_variables = compute_projects.get_env_variables(
["third-party/benchmark/CMakeLists.txt"], "Linux"
)
self.assertEqual(
env_variables["projects_to_build"],
"bolt;clang;clang-tools-extra;flang;libclc;lld;lldb;llvm;mlir;polly",
)
self.assertEqual(
env_variables["project_check_targets"],
"check-bolt check-clang check-clang-cir check-clang-tools check-flang check-lld check-lldb check-llvm check-mlir check-polly",
)
self.assertEqual(
env_variables["runtimes_to_build"],
"compiler-rt;libc;libcxx;libcxxabi;libunwind",
)
self.assertEqual(
env_variables["runtimes_check_targets"],
"check-compiler-rt check-libc",
)
self.assertEqual(
env_variables["runtimes_check_targets_needs_reconfig"],
"check-cxx check-cxxabi check-unwind",
)
if __name__ == "__main__":
unittest.main()

View File

@ -1,3 +1,13 @@
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Collects Github metrics and uploads them to Grafana.
This script contains machinery that will pull metrics periodically from Github
about workflow runs. It will upload the collected metrics to the specified
Grafana instance.
"""
import collections
import datetime
import github

View File

@ -0,0 +1,75 @@
# Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
# See https://llvm.org/LICENSE.txt for license information.
# SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
"""Tests for metrics.py"""
from dataclasses import dataclass
import requests
import unittest
import unittest.mock
import metrics
class TestMetrics(unittest.TestCase):
def test_upload_gauge_metric(self):
"""Test that we can upload a gauge metric correctly.
Also verify that we pass around parameters like API keys and user IDs
correctly to the HTTP POST request.
"""
test_metrics = [metrics.GaugeMetric("gauge_test", 5, 1000)]
return_value = requests.Response()
return_value.status_code = 204
with unittest.mock.patch(
"requests.post", return_value=return_value
) as post_mock:
metrics.upload_metrics(test_metrics, "test_userid", "test_api_key")
self.assertSequenceEqual(post_mock.call_args.args, [metrics.GRAFANA_URL])
self.assertEqual(
post_mock.call_args.kwargs["data"], "gauge_test value=5 1000"
)
self.assertEqual(
post_mock.call_args.kwargs["auth"], ("test_userid", "test_api_key")
)
def test_upload_job_metric(self):
"""Test that we can upload a job metric correctly."""
test_metrics = [
metrics.JobMetrics("test_job", 5, 10, 1, 1000, 7, "test_workflow")
]
return_value = requests.Response()
return_value.status_code = 204
with unittest.mock.patch(
"requests.post", return_value=return_value
) as post_mock:
metrics.upload_metrics(test_metrics, "test_userid", "test_aoi_key")
self.assertEqual(
post_mock.call_args.kwargs["data"],
"test_job queue_time=5,run_time=10,status=1 1000",
)
def test_upload_unknown_metric(self):
"""Test we report an error if we encounter an unknown metric type."""
@dataclass
class FakeMetric:
fake_data: str
test_metrics = [FakeMetric("test")]
with self.assertRaises(ValueError):
metrics.upload_metrics(test_metrics, "test_userid", "test_api_key")
def test_bad_response_code(self):
"""Test that we gracefully handle HTTP response errors."""
test_metrics = [metrics.GaugeMetric("gauge_test", 5, 1000)]
return_value = requests.Response()
return_value.status_code = 403
# Just assert that we continue running here and do not raise anything.
with unittest.mock.patch("requests.post", return_value=return_value) as _:
metrics.upload_metrics(test_metrics, "test_userid", "test_api_key")
if __name__ == "__main__":
unittest.main()

View File

@ -21,12 +21,7 @@ BUILD_DIR="${BUILD_DIR:=${MONOREPO_ROOT}/build}"
INSTALL_DIR="${BUILD_DIR}/install"
rm -rf "${BUILD_DIR}"
ccache --zero-stats
if [[ -n "${CLEAR_CACHE:-}" ]]; then
echo "clearing cache"
ccache --clear
fi
sccache --zero-stats
mkdir -p artifacts/reproducers
@ -36,7 +31,7 @@ export CLANG_CRASH_DIAGNOSTICS_DIR=`realpath artifacts/reproducers`
function at-exit {
retcode=$?
ccache --print-stats > artifacts/ccache_stats.txt
sccache --show-stats > artifacts/sccache_stats.txt
cp "${BUILD_DIR}"/.ninja_log artifacts/.ninja_log
cp "${BUILD_DIR}"/test-results.*.xml artifacts/ || :
@ -53,6 +48,7 @@ targets="${2}"
runtimes="${3}"
runtime_targets="${4}"
runtime_targets_needs_reconfig="${5}"
enable_cir="${6}"
lit_args="-v --xunit-xml-output ${BUILD_DIR}/test-results.xml --use-unique-output-file-name --timeout=1200 --time-tests"
@ -72,13 +68,15 @@ cmake -S "${MONOREPO_ROOT}"/llvm -B "${BUILD_DIR}" \
-G Ninja \
-D CMAKE_PREFIX_PATH="${HOME}/.local" \
-D CMAKE_BUILD_TYPE=Release \
-D CLANG_ENABLE_CIR=${enable_cir} \
-D LLVM_ENABLE_ASSERTIONS=ON \
-D LLVM_BUILD_EXAMPLES=ON \
-D COMPILER_RT_BUILD_LIBFUZZER=OFF \
-D LLVM_LIT_ARGS="${lit_args}" \
-D LLVM_ENABLE_LLD=ON \
-D CMAKE_CXX_FLAGS=-gmlt \
-D LLVM_CCACHE_BUILD=ON \
-D CMAKE_C_COMPILER_LAUNCHER=sccache \
-D CMAKE_CXX_COMPILER_LAUNCHER=sccache \
-D LIBCXX_CXX_ABI=libcxxabi \
-D MLIR_ENABLE_BINDINGS_PYTHON=ON \
-D LLDB_ENABLE_PYTHON=ON \

View File

@ -21,11 +21,6 @@ BUILD_DIR="${BUILD_DIR:=${MONOREPO_ROOT}/build}"
rm -rf "${BUILD_DIR}"
if [[ -n "${CLEAR_CACHE:-}" ]]; then
echo "clearing sccache"
rm -rf "$SCCACHE_DIR"
fi
sccache --zero-stats
function at-exit {
retcode=$?

View File

@ -10,15 +10,15 @@ on:
- 'main'
paths:
- 'clang/bindings/python/**'
- 'clang/test/bindings/python/**'
- 'clang/tools/libclang/**'
- 'clang/CMakeList.txt'
- '.github/workflows/libclang-python-tests.yml'
- '.github/workflows/llvm-project-tests.yml'
pull_request:
paths:
- 'clang/bindings/python/**'
- 'clang/test/bindings/python/**'
- 'clang/tools/libclang/**'
- 'clang/CMakeList.txt'
- '.github/workflows/libclang-python-tests.yml'
- '.github/workflows/llvm-project-tests.yml'

View File

@ -36,7 +36,7 @@ concurrency:
jobs:
stage1:
if: github.repository_owner == 'llvm'
runs-on: llvm-premerge-libcxx-runners
runs-on: llvm-premerge-libcxx-release-runners
continue-on-error: false
strategy:
fail-fast: false
@ -73,7 +73,7 @@ jobs:
**/crash_diagnostics/*
stage2:
if: github.repository_owner == 'llvm'
runs-on: llvm-premerge-libcxx-runners
runs-on: llvm-premerge-libcxx-release-runners
needs: [ stage1 ]
continue-on-error: false
strategy:
@ -128,6 +128,7 @@ jobs:
'generic-abi-unstable',
'generic-hardening-mode-debug',
'generic-hardening-mode-extensive',
'generic-hardening-mode-extensive-observe-semantic',
'generic-hardening-mode-fast',
'generic-hardening-mode-fast-with-abi-breaks',
'generic-merged',
@ -147,19 +148,19 @@ jobs:
'generic-static',
'bootstrapping-build'
]
machine: [ 'llvm-premerge-libcxx-runners' ]
machine: [ 'llvm-premerge-libcxx-release-runners' ]
include:
- config: 'generic-cxx26'
machine: llvm-premerge-libcxx-runners
machine: llvm-premerge-libcxx-release-runners
- config: 'generic-asan'
machine: llvm-premerge-libcxx-runners
machine: llvm-premerge-libcxx-release-runners
- config: 'generic-tsan'
machine: llvm-premerge-libcxx-runners
machine: llvm-premerge-libcxx-release-runners
- config: 'generic-ubsan'
machine: llvm-premerge-libcxx-runners
machine: llvm-premerge-libcxx-release-runners
# Use a larger machine for MSAN to avoid timeout and memory allocation issues.
- config: 'generic-msan'
machine: llvm-premerge-libcxx-runners
machine: llvm-premerge-libcxx-release-runners
runs-on: ${{ matrix.machine }}
steps:
- uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2

View File

@ -34,10 +34,6 @@ jobs:
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
fetch-depth: 2
- name: Setup ccache
uses: hendrikmuhs/ccache-action@a1209f81afb8c005c13b4296c32e363431bffea5 # v1.2.17
with:
max-size: "2000M"
- name: Build and Test
# Mark the job as a success even if the step fails so that people do
# not get notified while the new premerge pipeline is in an
@ -61,7 +57,20 @@ jobs:
export CC=/opt/llvm/bin/clang
export CXX=/opt/llvm/bin/clang++
./.ci/monolithic-linux.sh "${projects_to_build}" "${project_check_targets}" "${runtimes_to_build}" "${runtimes_check_targets}" "${runtimes_check_targets_needs_reconfig}"
# This environment variable is passes into the container through the
# runner pod definition. This differs between our two clusters which
# why we do not hardcode it.
export SCCACHE_GCS_BUCKET=$CACHE_GCS_BUCKET
export SCCACHE_GCS_RW_MODE=READ_WRITE
# Set the idle timeout to zero to ensure sccache runs for the
# entire duration of the job. Otherwise it might stop if we run
# several test suites in a row and discard statistics that we want
# to save in the end.
export SCCACHE_IDLE_TIMEOUT=0
sccache --start-server
./.ci/monolithic-linux.sh "${projects_to_build}" "${project_check_targets}" "${runtimes_to_build}" "${runtimes_check_targets}" "${runtimes_check_targets_needs_reconfig}" "${enable_cir}"
- name: Upload Artifacts
if: '!cancelled()'
uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.0
@ -76,7 +85,7 @@ jobs:
if: >-
github.repository_owner == 'llvm' &&
(github.event_name != 'pull_request' || github.event.action != 'closed')
runs-on: llvm-premerge-windows-runners
runs-on: llvm-premerge-windows-2022-runners
defaults:
run:
shell: bash
@ -85,11 +94,6 @@ jobs:
uses: actions/checkout@11bd71901bbe5b1630ceea73d27597364c9af683 # v4.2.2
with:
fetch-depth: 2
- name: Setup ccache
uses: hendrikmuhs/ccache-action@a1209f81afb8c005c13b4296c32e363431bffea5 # v1.2.17
with:
variant: "sccache"
max-size: "2000M"
- name: Compute Projects
id: vars
run: |
@ -112,7 +116,9 @@ jobs:
shell: cmd
run: |
call C:\\BuildTools\\Common7\\Tools\\VsDevCmd.bat -arch=amd64 -host_arch=amd64
bash .ci/monolithic-windows.sh "${{ steps.vars.outputs.windows-projects }}" "${{ steps.vars.outputs.windows-check-targets }}"
# See the comments above in the Linux job for why we define each of
# these environment variables.
bash -c "export SCCACHE_GCS_BUCKET=$CACHE_GCS_BUCKET; export SCCACHE_GCS_RW_MODE=READ_WRITE; export SCCACHE_IDLE_TIMEOUT=0; sccache --start-server; .ci/monolithic-windows.sh \"${{ steps.vars.outputs.windows-projects }}\" \"${{ steps.vars.outputs.windows-check-targets }}\""
- name: Upload Artifacts
if: '!cancelled()'
uses: actions/upload-artifact@65c4c4a1ddee5b72f698fdd19549f0f0fb45cf08 # v4.6.0

View File

@ -111,3 +111,31 @@ jobs:
# Called workflows don't have access to secrets by default, so we need to explicitly pass secrets that we use.
secrets:
RELEASE_TASKS_USER_TOKEN: ${{ secrets.RELEASE_TASKS_USER_TOKEN }}
uncomment-download-links:
name: Uncomment download links
runs-on: ubuntu-24.04
permissions:
contents: write # For updating the release message.
needs:
- validate-tag
- release-create
- release-binaries
steps:
- name: Install Dependencies
run: |
sudo apt-get update
sudo apt-get install python3-github
- name: Checkout LLVM
uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
with:
sparse-checkout: llvm/utils/release/github-upload-release.py
sparse-checkout-cone-mode: false
- name: Uncomment Download Links
env:
GITHUB_TOKEN: ${{ github.token }}
run: |
./llvm/utils/release/./github-upload-release.py --token "$GITHUB_TOKEN" --release ${{ needs.validate-tag.outputs.release-version }} uncomment_download_links

View File

@ -315,7 +315,7 @@ struct Fragment {
/// AngledHeaders (i.e. a header matches a regex in both QuotedHeaders and
/// AngledHeaders), system headers use <> and non-system headers use "".
/// These can match any suffix of the header file in question.
/// Matching is performed against the header text, not its absolute path
/// Matching is performed against the absolute path of the header
/// within the project.
std::vector<Located<std::string>> QuotedHeaders;
/// List of regexes for headers that should always be included with a
@ -323,7 +323,7 @@ struct Fragment {
/// AngledHeaders (i.e. a header matches a regex in both QuotedHeaders and
/// AngledHeaders), system headers use <> and non-system headers use "".
/// These can match any suffix of the header file in question.
/// Matching is performed against the header text, not its absolute path
/// Matching is performed against the absolute path of the header
/// within the project.
std::vector<Located<std::string>> AngledHeaders;
};

View File

@ -304,16 +304,17 @@ IncludeInserter::calculateIncludePath(const HeaderFile &InsertedHeader,
// FIXME: should we allow (some limited number of) "../header.h"?
if (llvm::sys::path::is_absolute(Suggested))
return std::nullopt;
auto HeaderPath = llvm::sys::path::convert_to_slash(InsertedHeader.File);
bool IsAngled = false;
for (auto &Filter : AngledHeaders) {
if (Filter(Suggested)) {
if (Filter(HeaderPath)) {
IsAngled = true;
break;
}
}
bool IsQuoted = false;
for (auto &Filter : QuotedHeaders) {
if (Filter(Suggested)) {
if (Filter(HeaderPath)) {
IsQuoted = true;
break;
}
@ -324,7 +325,7 @@ IncludeInserter::calculateIncludePath(const HeaderFile &InsertedHeader,
if (IsAngled && IsQuoted) {
elog("Header '{0}' matches both quoted and angled regexes, default will "
"be used.",
Suggested);
HeaderPath);
}
IsAngled = IsAngledByDefault;
}

View File

@ -938,7 +938,7 @@ TEST(CompletionTest, IncludeInsertionRespectsQuotedAngledConfig) {
{
Config C;
C.Style.AngledHeaders.push_back(
[](auto header) { return header == "bar.h"; });
[](auto header) { return header.contains("bar.h"); });
WithContextValue WithCfg(Config::Key, std::move(C));
Results = completions(TU, Test.point(), {Sym});
EXPECT_THAT(Results.Completions,
@ -947,7 +947,7 @@ TEST(CompletionTest, IncludeInsertionRespectsQuotedAngledConfig) {
{
Config C;
C.Style.QuotedHeaders.push_back(
[](auto header) { return header == "bar.h"; });
[](auto header) { return header.contains("bar.h"); });
WithContextValue WithCfg(Config::Key, std::move(C));
Results = completions(TU, Test.point(), {Sym});
EXPECT_THAT(Results.Completions,

View File

@ -344,6 +344,17 @@ TEST_F(HeadersTest, ShortenIncludesInSearchPathBracketed) {
EXPECT_EQ(calculate(BarHeader), "<sub/bar.h>");
}
TEST_F(HeadersTest, ShortenIncludesInSearchPathBracketedFilterByFullPath) {
// The filter receives the full path of the header, so it is able to filter by
// the parent directory, even if it is part of the include search path
AngledHeaders.push_back([](auto Path) {
llvm::Regex Pattern("sub/.*");
return Pattern.match(Path);
});
std::string BarHeader = testPath("sub/bar.h");
EXPECT_EQ(calculate(BarHeader), "<bar.h>");
}
TEST_F(HeadersTest, ShortenedIncludeNotInSearchPath) {
std::string BarHeader =
llvm::sys::path::convert_to_slash(testPath("sub-2/bar.h"));

View File

@ -46,14 +46,18 @@ Major New Features
Improvements to clangd
----------------------
Inlay hints
^^^^^^^^^^^
Language feature support
^^^^^^^^^^^^^^^^^^^^^^^^
Diagnostics
^^^^^^^^^^^
- Performance improvements and bugfixes to C++20 Modules support
- Improved support for C++23 "deducing this"
- Improvements to objective-c++ support
Semantic Highlighting
^^^^^^^^^^^^^^^^^^^^^
New Language Server Protocol features
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
- Added support for `textDocument/rangesFormatting`
- Added support for `positionEncoding`
Compile flags
^^^^^^^^^^^^^
@ -64,24 +68,58 @@ Compile flags
Hover
^^^^^
- Fixed a bug that would sometimes prevent documentation comments of standard library functions
from being shown
Code completion
^^^^^^^^^^^^^^^
Code actions
^^^^^^^^^^^^
Signature help
^^^^^^^^^^^^^^
- Added `HeaderInsertion` config option to control whether code completion inserts a missing
header needed for the symbol being completed. This is equivalent to the `--header-insertion`
command-line option.
- Added a `CodePatterns` config option to control whether code completion should offer code
patterns as completions in addition to symbols.
Cross-references
^^^^^^^^^^^^^^^^
Objective-C
- References to symbols are now collected in array designators
- Find-references now works for operators new and delete
- Improvements to code navigation in templated code
Call hierarchy
^^^^^^^^^^^^^^
- Call hierarchy now works with the remote index
- Fixed a bug where call hierarchy could sometimes return bogus results
Inlay hints
^^^^^^^^^^^
- Parameter hint forwarding now works for variadic forwarding functions declared in header files
- Improved presentation of block-end hints
Code actions
^^^^^^^^^^^^
- Improved the rename refactor's name collision checking logic
Clang-tidy integration
^^^^^^^^^^^^^^^^^^^^^^
- Disabled the cppcoreguidelines-macro-to-enum checker which is incompatible with clangd
Include-cleaner integration
^^^^^^^^^^^^^^^^^^^^^^^^^^^
- Clangd now respects the `AngledHeaders` and `QuotedHeaders` config options for headers
inserted to resolve include-cleaner diagnostics
Miscellaneous
^^^^^^^^^^^^^
- Various crash fixes and other stability improvements
Improvements to clang-doc
-------------------------

View File

@ -136,7 +136,7 @@ struct Header {
}
StringRef verbatim() const { return std::get<Verbatim>(Storage); }
/// For phiscal files, either absolute path or path relative to the execution
/// For physical files, either absolute path or path relative to the execution
/// root. Otherwise just the spelling without surrounding quotes/brackets.
llvm::StringRef resolvedPath() const;

View File

@ -536,6 +536,7 @@ if( CLANG_INCLUDE_TESTS )
clang_unit_site_config=${CMAKE_CURRENT_BINARY_DIR}/test/Unit/lit.site.cfg
)
add_subdirectory(test)
add_subdirectory(bindings/python/tests)
if(CLANG_BUILT_STANDALONE)
umbrella_lit_testsuite_end(check-all)

View File

@ -0,0 +1,66 @@
# Test target to run Python test suite from main build.
# Avoid configurations including '-include' from interfering with
# our tests by setting CLANG_NO_DEFAULT_CONFIG.
add_custom_target(check-clang-python
COMMAND ${CMAKE_COMMAND} -E env
CLANG_NO_DEFAULT_CONFIG=1
CLANG_LIBRARY_PATH=$<TARGET_FILE_DIR:libclang>
"${Python3_EXECUTABLE}" -m unittest discover
DEPENDS libclang
WORKING_DIRECTORY ${CMAKE_CURRENT_SOURCE_DIR}/..)
set(RUN_PYTHON_TESTS TRUE)
set_target_properties(check-clang-python PROPERTIES FOLDER "Clang/Tests")
# Tests require libclang.so which is only built with LLVM_ENABLE_PIC=ON
if(NOT LLVM_ENABLE_PIC)
set(RUN_PYTHON_TESTS FALSE)
endif()
# Do not try to run if libclang was built with sanitizers because
# the sanitizer library will likely be loaded too late to perform
# interception and will then fail.
# We could use LD_PRELOAD/DYLD_INSERT_LIBRARIES but this isn't
# portable so its easier just to not run the tests when building
# with ASan.
if(NOT LLVM_USE_SANITIZER STREQUAL "")
set(RUN_PYTHON_TESTS FALSE)
endif()
# Tests fail on Windows, and need someone knowledgeable to fix.
# It's not clear whether it's a test or a valid binding problem.
if(WIN32)
set(RUN_PYTHON_TESTS FALSE)
endif()
# The Python FFI interface is broken on AIX: https://bugs.python.org/issue38628.
if(${CMAKE_SYSTEM_NAME} MATCHES "AIX")
set(RUN_PYTHON_TESTS FALSE)
endif()
# AArch64, Hexagon, and Sparc have known test failures that need to be
# addressed.
# SystemZ has broken Python/FFI interface:
# https://reviews.llvm.org/D52840#1265716
if(${LLVM_NATIVE_ARCH} MATCHES "^(AArch64|Hexagon|Sparc|SystemZ)$")
set(RUN_PYTHON_TESTS FALSE)
endif()
# Tests will fail if cross-compiling for a different target, as tests will try
# to use the host Python3_EXECUTABLE and make FFI calls to functions in target
# libraries.
if(CMAKE_CROSSCOMPILING)
# FIXME: Consider a solution that allows better control over these tests in
# a crosscompiling scenario. e.g. registering them with lit to allow them to
# be explicitly skipped via appropriate LIT_ARGS, or adding a mechanism to
# allow specifying a python interpreter compiled for the target that could
# be executed using qemu-user.
message(WARNING "check-clang-python not added to check-all as these tests fail in a cross-build setup")
set(RUN_PYTHON_TESTS FALSE)
endif()
if(RUN_PYTHON_TESTS)
set_property(GLOBAL APPEND PROPERTY
LLVM_ALL_ADDITIONAL_TEST_TARGETS check-clang-python)
endif()

View File

@ -6390,6 +6390,14 @@ the configuration (without a prefix: ``Auto``).
IF (...) vs. IF(...)
<conditional-body> <conditional-body>
* ``bool AfterNot`` If ``true``, put a space between alternative operator ``not`` and the
opening parenthesis.
.. code-block:: c++
true: false:
return not (a || b); vs. return not(a || b);
* ``bool AfterOverloadedOperator`` If ``true``, put a space between operator overloading and opening
parentheses.

File diff suppressed because it is too large Load Diff

View File

@ -55,7 +55,7 @@ C/C++ Language Potentially Breaking Changes
case for old-style offsetof idioms like ``((int)(&(((struct S *)0)->field)))``, to
ensure they are not caught by these optimizations. It is also possible to use
``-fwrapv-pointer`` or ``-fno-delete-null-pointer-checks`` to make pointer arithmetic
on null pointers well-defined. (#GH130734, #GH130742, #GH130952)
on null pointers well-defined. (#GH130734, #GH130952)
C++ Specific Potentially Breaking Changes
-----------------------------------------
@ -359,6 +359,12 @@ Non-comprehensive list of changes in this release
ARC-managed pointers and other pointer types. The prior behavior was overly
strict and inconsistent with the ARC specification.
- Use of ``__has_feature`` to detect the ``ptrauth_qualifier`` and ``ptrauth_intrinsics``
features has been deprecated, and is restricted to the arm64e target only. The
correct method to check for these features is to test for the ``__PTRAUTH__``
macro.
New Compiler Flags
------------------
@ -376,6 +382,8 @@ New Compiler Flags
- New options ``-g[no-]key-instructions`` added, disabled by default. Reduces jumpiness of debug stepping for optimized code in some debuggers (not LLDB at this time). Not recommended for use without optimizations. DWARF only. Note both the positive and negative flags imply ``-g``.
- New options ``-fthinlto-distributor=`` and ``-Xthinlto-distributor=`` added for Integrated Distributed ThinLTO (DTLTO). DTLTO enables the distribution of backend ThinLTO compilations via external distribution systems, such as Incredibuild, during the traditional link step. (#GH147265, `ThinLTODocs <https://clang.llvm.org/docs/ThinLTO.html#integrated-distributed-thinlto-dtlto>`_).
Deprecated Compiler Flags
-------------------------
@ -800,6 +808,8 @@ Bug Fixes in This Version
declaration statements. Clang now emits a warning for these patterns. (#GH141659)
- Fixed false positives for redeclaration errors of using enum in
nested scopes. (#GH147495)
- Fixed a crash in `clang-scan-deps` when a module with the same name is found
in different locations (#GH134404, #GH146976).
Bug Fixes to Compiler Builtins
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
@ -949,7 +959,6 @@ Bug Fixes to C++ Support
- Fixed an access checking bug when initializing non-aggregates in default arguments (#GH62444), (#GH83608)
- Fixed a pack substitution bug in deducing class template partial specializations. (#GH53609)
- Fixed a crash when constant evaluating some explicit object member assignment operators. (#GH142835)
- Fixed an access checking bug when substituting into concepts (#GH115838)
- Fix a bug where private access specifier of overloaded function not respected. (#GH107629)
- Correctly handles calling an explicit object member function template overload set
through its address (``(&Foo::bar<baz>)()``).
@ -967,6 +976,7 @@ Bug Fixes to C++ Support
- Fix a crash with NTTP when instantiating local class.
- Fixed a crash involving list-initialization of an empty class with a
non-empty initializer list. (#GH147949)
- Fixed constant evaluation of equality comparisons of constexpr-unknown references. (#GH147663)
Bug Fixes to AST Handling
^^^^^^^^^^^^^^^^^^^^^^^^^
@ -993,6 +1003,19 @@ Miscellaneous Clang Crashes Fixed
OpenACC Specific Changes
------------------------
- OpenACC support, enabled via `-fopenacc` has reached a level of completeness
to finally be at least notionally usable. Currently, the OpenACC 3.4
specification has been completely implemented for Sema and AST creation, so
nodes will show up in the AST after having been properly checked. Lowering is
currently a work in progress, with compute, loop, and combined constructs
partially implemented, plus a handful of data and executable constructs
implemented. Lowering will only work in Clang-IR mode (so only with a compiler
built with Clang-IR enabled, and with `-fclangir` used on the command line).
However, note that the Clang-IR implementation status is also quite partial,
so frequent 'not yet implemented' diagnostics should be expected. Also, the
ACC MLIR dialect does not currently implement any lowering to LLVM-IR, so no
code generation is possible for OpenACC.
Target Specific Changes
-----------------------
@ -1071,6 +1094,8 @@ Windows Support
extensions are enabled. This allows for properly processing ``intsafe.h`` in
the Windows SDK.
- Clang now supports `mipsel-windows-gnu` and `mipsel-windows-msvc` targets.
LoongArch Support
^^^^^^^^^^^^^^^^^
@ -1119,9 +1144,19 @@ CUDA/HIP Language Changes
CUDA Support
^^^^^^^^^^^^
PowerPC Support
^^^^^^^^^^^^^^^
* Add `__dmr1024` type for Dense Math Facility.
* Add prototype for Dense Math Facility integer calculation builtins.
AIX Support
^^^^^^^^^^^
* Fixed `-print-runtime-dir` to fallback to the target subdirectory (rather than OS subdirectory) if the runtime path is not found.
* Fixed `-print-runtime-dir` to find the correct runtime path if the triple has "unknown" as the environment component.
* Changed AIX targets to use the per-target runtime directories for compiler runtimes (i.e. `lib/clang/20/lib/aix` became `lib/clang/21/lib/powerpc-ibm-aix` and `clang/21/lib/powerpc64-ibm-aix`).
NetBSD Support
^^^^^^^^^^^^^^
@ -1202,18 +1237,6 @@ New features
the runtime for the Blocks extension on Windows. This flag currently only
changes the code generation, and even then, only on Windows. This does not
impact the linker behaviour like the other `-static-*` flags.
- OpenACC support, enabled via `-fopenacc` has reached a level of completeness
to finally be at least notionally usable. Currently, the OpenACC 3.4
specification has been completely implemented for Sema and AST creation, so
nodes will show up in the AST after having been properly checked. Lowering is
currently a work in progress, with compute, loop, and combined constructs
partially implemented, plus a handful of data and executable constructs
implemented. Lowering will only work in Clang-IR mode (so only with a compiler
built with Clang-IR enabled, and with `-fclangir` used on the command line).
However, note that the Clang-IR implementation status is also quite partial,
so frequent 'not yet implemented' diagnostics should be expected. Also, the
ACC MLIR dialect does not currently implement any lowering to LLVM-IR, so no
code generation is possible for OpenACC.
- Implemented `P2719R5 Type-aware allocation and deallocation functions <https://wg21.link/P2719>`_
as an extension in all C++ language modes.

View File

@ -240,6 +240,53 @@ The ``BOOTSTRAP_LLVM_ENABLE_LTO=Thin`` will enable ThinLTO for stage 2 and
stage 3 in case the compiler used for stage 1 does not support the ThinLTO
option.
Integrated Distributed ThinLTO (DTLTO)
--------------------------------------
Integrated Distributed ThinLTO (DTLTO) enables the distribution of backend
ThinLTO compilations via external distribution systems, such as Incredibuild,
during the traditional link step.
The implementation is documented here: https://llvm.org/docs/DTLTO.html.
Command-Line Options
^^^^^^^^^^^^^^^^^^^^
DTLTO requires the LLD linker (``-fuse-ld=lld``).
``-fthinlto-distributor=<path>``
- Specifies the ``<path>`` to the distributor process executable for DTLTO.
- If specified, ThinLTO backend compilations will be distributed by LLD.
``-Xthinlto-distributor=<arg>``
- Passes ``<arg>`` to the distributor process (see ``-fthinlto-distributor=``).
- Can be specified multiple times to pass multiple options.
- Multiple options can also be specified by separating them with commas.
If ``-fthinlto-distributor=`` is specified, Clang supplies the path to a
compiler to be executed remotely to perform the ThinLTO backend
compilations. Currently, this is Clang itself.
Usage
^^^^^
Compilation is unchanged from ThinLTO. DTLTO options need to supplied for the link step:
.. code-block:: console
% clang -flto=thin -fthinlto-distributor=distribute.sh -Xthinlto-distributor=--verbose,--j10 -fuse-ld=lld file1.o file2.o
% clang -flto=thin -fthinlto-distributor=$(which python) -Xthinlto-distributor=distribute.py -fuse-ld=lld file1.o file2.o
When using lld-link:
.. code-block:: console
% lld-link /out:a.exe file1.obj file2.obj /thinlto-distributor:distribute.exe /thinlto-remote-compiler:${LLVM}\bin\clang.exe /thinlto-distributor-arg:--verbose
Note that currently, DTLTO is only supported in some LLD flavors. Support can
be added to other LLD flavours in the future.
See `DTLTO <https://lld.llvm.org/DTLTO.html>`_ for more information.
More Information
================

View File

@ -6953,6 +6953,21 @@ clang_getCursorUnaryOperatorKind(CXCursor cursor);
* @}
*/
CINDEX_DEPRECATED
typedef void *CXRemapping;
CINDEX_DEPRECATED CINDEX_LINKAGE CXRemapping clang_getRemappings(const char *);
CINDEX_DEPRECATED CINDEX_LINKAGE CXRemapping
clang_getRemappingsFromFileList(const char **, unsigned);
CINDEX_DEPRECATED CINDEX_LINKAGE unsigned clang_remap_getNumFiles(CXRemapping);
CINDEX_DEPRECATED CINDEX_LINKAGE void
clang_remap_getFilenames(CXRemapping, unsigned, CXString *, CXString *);
CINDEX_DEPRECATED CINDEX_LINKAGE void clang_remap_dispose(CXRemapping);
LLVM_CLANG_C_EXTERN_C_END
#endif

View File

@ -9417,9 +9417,9 @@ def NonStringDocs : Documentation {
let Category = DocCatDecl;
let Content = [{
The ``nonstring`` attribute can be applied to the declaration of a variable or
a field whose type is a character array to specify that the character array is
not intended to behave like a null-terminated string. This will silence
diagnostics with code like:
a field whose type is a character pointer or character array to specify that
the buffer is not intended to behave like a null-terminated string. This will
silence diagnostics with code like:
.. code-block:: c

View File

@ -507,6 +507,14 @@ def note_odr_number_of_bases : Note<
"class has %0 base %plural{1:class|:classes}0">;
def note_odr_enumerator : Note<"enumerator %0 with value %1 here">;
def note_odr_missing_enumerator : Note<"no corresponding enumerator here">;
def note_odr_incompatible_fixed_underlying_type : Note<
"enumeration %0 declared with incompatible fixed underlying types (%1 vs. "
"%2)">;
def note_odr_fixed_underlying_type : Note<
"enumeration %0 has fixed underlying type here">;
def note_odr_missing_fixed_underlying_type : Note<
"enumeration %0 missing fixed underlying type here">;
def err_odr_field_type_inconsistent : Error<
"field %0 declared with incompatible types in different "
"translation units (%1 vs. %2)">;

View File

@ -147,14 +147,17 @@ FEATURE(type_sanitizer, LangOpts.Sanitize.has(SanitizerKind::Type))
FEATURE(thread_sanitizer, LangOpts.Sanitize.has(SanitizerKind::Thread))
FEATURE(dataflow_sanitizer, LangOpts.Sanitize.has(SanitizerKind::DataFlow))
FEATURE(scudo, LangOpts.Sanitize.hasOneOf(SanitizerKind::Scudo))
FEATURE(ptrauth_intrinsics, LangOpts.PointerAuthIntrinsics)
EXTENSION(ptrauth_qualifier, LangOpts.PointerAuthIntrinsics)
FEATURE(ptrauth_intrinsics, LangOpts.PointerAuthIntrinsics &&
PP.getTargetInfo().getTriple().isOSDarwin())
FEATURE(ptrauth_qualifier, LangOpts.PointerAuthIntrinsics &&
PP.getTargetInfo().getTriple().isOSDarwin())
FEATURE(ptrauth_calls, LangOpts.PointerAuthCalls)
FEATURE(ptrauth_returns, LangOpts.PointerAuthReturns)
FEATURE(ptrauth_vtable_pointer_address_discrimination, LangOpts.PointerAuthVTPtrAddressDiscrimination)
FEATURE(ptrauth_vtable_pointer_type_discrimination, LangOpts.PointerAuthVTPtrTypeDiscrimination)
FEATURE(ptrauth_type_info_vtable_pointer_discrimination, LangOpts.PointerAuthTypeInfoVTPtrDiscrimination)
FEATURE(ptrauth_member_function_pointer_type_discrimination, LangOpts.PointerAuthCalls)
FEATURE(ptrauth_signed_block_descriptors, LangOpts.PointerAuthBlockDescriptorPointers)
FEATURE(ptrauth_function_pointer_type_discrimination, LangOpts.PointerAuthFunctionTypeDiscrimination)
FEATURE(ptrauth_indirect_gotos, LangOpts.PointerAuthIndirectGotos)
FEATURE(ptrauth_init_fini, LangOpts.PointerAuthInitFini)
@ -163,7 +166,7 @@ FEATURE(ptrauth_elf_got, LangOpts.PointerAuthELFGOT)
FEATURE(ptrauth_objc_isa, LangOpts.PointerAuthObjcIsa)
FEATURE(ptrauth_objc_interface_sel, LangOpts.PointerAuthObjcInterfaceSel)
FEATURE(ptrauth_objc_signable_class, true)
FEATURE(ptrauth_objc_signable_class, LangOpts.PointerAuthIntrinsics)
FEATURE(ptrauth_objc_method_list_pointer, LangOpts.PointerAuthCalls)
EXTENSION(swiftcc,

View File

@ -138,6 +138,8 @@ LANGOPT(PointerAuthObjcInterfaceSel, 1, 0, NotCompatible, "authentication of SEL
LANGOPT(PointerAuthObjcInterfaceSelKey, 16, 0, NotCompatible, "authentication key for SEL fields of ObjC interfaces")
LANGOPT(PointerAuthObjcClassROPointers, 1, 0, Benign, "class_ro_t pointer authentication")
LANGOPT(PointerAuthBlockDescriptorPointers, 1, 0, NotCompatible, "enable signed block descriptors")
LANGOPT(DoubleSquareBracketAttributes, 1, 0, NotCompatible, "'[[]]' attributes extension for all language standard modes")
LANGOPT(ExperimentalLateParseAttributes, 1, 0, NotCompatible, "experimental late parsing of attributes")
@ -496,6 +498,8 @@ LANGOPT(CheckConstexprFunctionBodies, 1, 1, Benign,
LANGOPT(BoundsSafety, 1, 0, NotCompatible, "Bounds safety extension for C")
LANGOPT(EnableLifetimeSafety, 1, 0, NotCompatible, "Experimental lifetime safety analysis for C++")
LANGOPT(PreserveVec3Type, 1, 0, NotCompatible, "Preserve 3-component vector type")
#undef LANGOPT

View File

@ -23,6 +23,10 @@
namespace clang {
/// Constant discriminator to be used with block descriptor pointers. The value
/// is ptrauth_string_discriminator("block_descriptor")
constexpr uint16_t BlockDescriptorConstantDiscriminator = 0xC0BB;
/// Constant discriminator to be used with function pointers in .init_array and
/// .fini_array. The value is ptrauth_string_discriminator("init_fini")
constexpr uint16_t InitFiniPointerConstantDiscriminator = 0xD9D4;
@ -223,6 +227,18 @@ struct PointerAuthOptions {
/// The ABI for function addresses in .init_array and .fini_array
PointerAuthSchema InitFiniPointers;
/// The ABI for block invocation function pointers.
PointerAuthSchema BlockInvocationFunctionPointers;
/// The ABI for block object copy/destroy function pointers.
PointerAuthSchema BlockHelperFunctionPointers;
/// The ABI for __block variable copy/destroy function pointers.
PointerAuthSchema BlockByrefHelperFunctionPointers;
/// The ABI for pointers to block descriptors.
PointerAuthSchema BlockDescriptorPointers;
/// The ABI for Objective-C method lists.
PointerAuthSchema ObjCMethodListFunctionPointers;

View File

@ -990,6 +990,13 @@ def Xlinker : Separate<["-"], "Xlinker">, Flags<[LinkerInput, RenderAsInput]>,
Visibility<[ClangOption, CLOption, FlangOption]>,
HelpText<"Pass <arg> to the linker">, MetaVarName<"<arg>">,
Group<Link_Group>;
def Xthinlto_distributor_EQ : CommaJoined<["-"], "Xthinlto-distributor=">,
Flags<[LinkOption]>,
Visibility<[ClangOption, CLOption]>,
HelpText<"Pass <arg> to the ThinLTO distributor process. Can be specified "
"multiple times or with comma-separated values.">,
MetaVarName<"<arg>">,
Group<Link_Group>;
def Xoffload_linker : JoinedAndSeparate<["-"], "Xoffload-linker">,
Visibility<[ClangOption, FlangOption]>,
HelpText<"Pass <arg> to the offload linkers or the ones identified by -<triple>">,
@ -1910,6 +1917,14 @@ defm bounds_safety : BoolFOption<
BothFlags<[], [CC1Option],
" experimental bounds safety extension for C">>;
defm lifetime_safety : BoolFOption<
"experimental-lifetime-safety",
LangOpts<"EnableLifetimeSafety">, DefaultFalse,
PosFlag<SetTrue, [], [CC1Option], "Enable">,
NegFlag<SetFalse, [], [CC1Option], "Disable">,
BothFlags<[], [CC1Option],
" experimental lifetime safety for C++">>;
defm addrsig : BoolFOption<"addrsig",
CodeGenOpts<"Addrsig">, DefaultFalse,
PosFlag<SetTrue, [], [ClangOption, CC1Option], "Emit">,
@ -4249,7 +4264,12 @@ def ffinite_loops: Flag<["-"], "ffinite-loops">, Group<f_Group>,
def fno_finite_loops: Flag<["-"], "fno-finite-loops">, Group<f_Group>,
HelpText<"Do not assume that any loop is finite.">,
Visibility<[ClangOption, CC1Option]>;
def fthinlto_distributor_EQ : Joined<["-"], "fthinlto-distributor=">,
Group<f_Group>,
HelpText<"Path to the ThinLTO distributor process. If specified, "
"ThinLTO backend compilations will be distributed by LLD">,
MetaVarName<"<path>">,
Visibility<[ClangOption, CLOption]>;
def ftrigraphs : Flag<["-"], "ftrigraphs">, Group<f_Group>,
HelpText<"Process trigraph sequences">, Visibility<[ClangOption, CC1Option]>;
def fno_trigraphs : Flag<["-"], "fno-trigraphs">, Group<f_Group>,
@ -4507,6 +4527,7 @@ defm aarch64_jump_table_hardening: OptInCC1FFlag<"aarch64-jump-table-hardening",
defm ptrauth_objc_isa : OptInCC1FFlag<"ptrauth-objc-isa", "Enable signing and authentication of Objective-C object's 'isa' field">;
defm ptrauth_objc_interface_sel : OptInCC1FFlag<"ptrauth-objc-interface-sel", "Enable signing and authentication of Objective-C object's 'SEL' fields">;
defm ptrauth_objc_class_ro : OptInCC1FFlag<"ptrauth-objc-class-ro", "Enable signing and authentication for ObjC class_ro pointers">;
defm ptrauth_block_descriptor_pointers : OptInCC1FFlag<"ptrauth-block-descriptor-pointers", "Enable signing and authentication of block descriptors">;
}
def fenable_matrix : Flag<["-"], "fenable-matrix">, Group<f_Group>,

View File

@ -4694,6 +4694,13 @@ struct FormatStyle {
/// <conditional-body> <conditional-body>
/// \endcode
bool AfterIfMacros;
/// If ``true``, put a space between alternative operator ``not`` and the
/// opening parenthesis.
/// \code
/// true: false:
/// return not (a || b); vs. return not(a || b);
/// \endcode
bool AfterNot;
/// If ``true``, put a space between operator overloading and opening
/// parentheses.
/// \code
@ -4742,9 +4749,9 @@ struct FormatStyle {
: AfterControlStatements(false), AfterForeachMacros(false),
AfterFunctionDeclarationName(false),
AfterFunctionDefinitionName(false), AfterIfMacros(false),
AfterOverloadedOperator(false), AfterPlacementOperator(true),
AfterRequiresInClause(false), AfterRequiresInExpression(false),
BeforeNonEmptyParentheses(false) {}
AfterNot(false), AfterOverloadedOperator(false),
AfterPlacementOperator(true), AfterRequiresInClause(false),
AfterRequiresInExpression(false), BeforeNonEmptyParentheses(false) {}
bool operator==(const SpaceBeforeParensCustom &Other) const {
return AfterControlStatements == Other.AfterControlStatements &&
@ -4753,6 +4760,7 @@ struct FormatStyle {
Other.AfterFunctionDeclarationName &&
AfterFunctionDefinitionName == Other.AfterFunctionDefinitionName &&
AfterIfMacros == Other.AfterIfMacros &&
AfterNot == Other.AfterNot &&
AfterOverloadedOperator == Other.AfterOverloadedOperator &&
AfterPlacementOperator == Other.AfterPlacementOperator &&
AfterRequiresInClause == Other.AfterRequiresInClause &&

View File

@ -143,9 +143,6 @@ class Lexer : public PreprocessorLexer {
/// True if this is the first time we're lexing the input file.
bool IsFirstTimeLexingFile;
/// True if current lexing token is the first pp-token.
bool IsFirstPPToken;
// NewLinePtr - A pointer to new line character '\n' being lexed. For '\r\n',
// it also points to '\n.'
const char *NewLinePtr;

View File

@ -0,0 +1,310 @@
//===--- NoTrivialPPDirectiveTracer.h ---------------------------*- C++ -*-===//
//
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
// See https://llvm.org/LICENSE.txt for license information.
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
//
//===----------------------------------------------------------------------===//
//
// This file defines the NoTrivialPPDirectiveTracer interface.
//
//===----------------------------------------------------------------------===//
#ifndef LLVM_CLANG_LEX_NO_TRIVIAL_PPDIRECTIVE_TRACER_H
#define LLVM_CLANG_LEX_NO_TRIVIAL_PPDIRECTIVE_TRACER_H
#include "clang/Lex/PPCallbacks.h"
namespace clang {
class Preprocessor;
/// Consider the following code:
///
/// # 1 __FILE__ 1 3
/// export module a;
///
/// According to the wording in
/// [P1857R3](https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2020/p1857r3.html):
///
/// A module directive may only appear as the first preprocessing tokens in a
/// file (excluding the global module fragment.)
///
/// and the wording in
/// [[cpp.pre]](https://eel.is/c++draft/cpp.pre#nt:module-file):
/// module-file:
/// pp-global-module-fragment[opt] pp-module group[opt]
/// pp-private-module-fragment[opt]
///
/// `#` is the first pp-token in the translation unit, and it was rejected by
/// clang, but they really should be exempted from this rule. The goal is to not
/// allow any preprocessor conditionals or most state changes, but these don't
/// fit that.
///
/// State change would mean most semantically observable preprocessor state,
/// particularly anything that is order dependent. Global flags like being a
/// system header/module shouldn't matter.
///
/// We should exempt a brunch of directives, even though it violates the current
/// standard wording.
///
/// This class used to trace 'no-trivial' pp-directives in main file, which may
/// change the preprocessing state.
///
/// FIXME: Once the wording of the standard is revised, we need to follow the
/// wording of the standard. Currently this is just a workaround
class NoTrivialPPDirectiveTracer : public PPCallbacks {
Preprocessor &PP;
/// Whether preprocessing main file. We only focus on the main file.
bool InMainFile = true;
/// Whether one or more conditional, include or other 'no-trivial'
/// pp-directives has seen before.
bool SeenNoTrivialPPDirective = false;
void setSeenNoTrivialPPDirective();
public:
NoTrivialPPDirectiveTracer(Preprocessor &P) : PP(P) {}
bool hasSeenNoTrivialPPDirective() const;
/// Callback invoked whenever the \p Lexer moves to a different file for
/// lexing. Unlike \p FileChanged line number directives and other related
/// pragmas do not trigger callbacks to \p LexedFileChanged.
///
/// \param FID The \p FileID that the \p Lexer moved to.
///
/// \param Reason Whether the \p Lexer entered a new file or exited one.
///
/// \param FileType The \p CharacteristicKind of the file the \p Lexer moved
/// to.
///
/// \param PrevFID The \p FileID the \p Lexer was using before the change.
///
/// \param Loc The location where the \p Lexer entered a new file from or the
/// location that the \p Lexer moved into after exiting a file.
void LexedFileChanged(FileID FID, LexedFileChangeReason Reason,
SrcMgr::CharacteristicKind FileType, FileID PrevFID,
SourceLocation Loc) override;
/// Callback invoked whenever an embed directive has been processed,
/// regardless of whether the embed will actually find a file.
///
/// \param HashLoc The location of the '#' that starts the embed directive.
///
/// \param FileName The name of the file being included, as written in the
/// source code.
///
/// \param IsAngled Whether the file name was enclosed in angle brackets;
/// otherwise, it was enclosed in quotes.
///
/// \param File The actual file that may be included by this embed directive.
///
/// \param Params The parameters used by the directive.
void EmbedDirective(SourceLocation HashLoc, StringRef FileName, bool IsAngled,
OptionalFileEntryRef File,
const LexEmbedParametersResult &Params) override {
setSeenNoTrivialPPDirective();
}
/// Callback invoked whenever an inclusion directive of
/// any kind (\c \#include, \c \#import, etc.) has been processed, regardless
/// of whether the inclusion will actually result in an inclusion.
///
/// \param HashLoc The location of the '#' that starts the inclusion
/// directive.
///
/// \param IncludeTok The token that indicates the kind of inclusion
/// directive, e.g., 'include' or 'import'.
///
/// \param FileName The name of the file being included, as written in the
/// source code.
///
/// \param IsAngled Whether the file name was enclosed in angle brackets;
/// otherwise, it was enclosed in quotes.
///
/// \param FilenameRange The character range of the quotes or angle brackets
/// for the written file name.
///
/// \param File The actual file that may be included by this inclusion
/// directive.
///
/// \param SearchPath Contains the search path which was used to find the file
/// in the file system. If the file was found via an absolute include path,
/// SearchPath will be empty. For framework includes, the SearchPath and
/// RelativePath will be split up. For example, if an include of "Some/Some.h"
/// is found via the framework path
/// "path/to/Frameworks/Some.framework/Headers/Some.h", SearchPath will be
/// "path/to/Frameworks/Some.framework/Headers" and RelativePath will be
/// "Some.h".
///
/// \param RelativePath The path relative to SearchPath, at which the include
/// file was found. This is equal to FileName except for framework includes.
///
/// \param SuggestedModule The module suggested for this header, if any.
///
/// \param ModuleImported Whether this include was translated into import of
/// \p SuggestedModule.
///
/// \param FileType The characteristic kind, indicates whether a file or
/// directory holds normal user code, system code, or system code which is
/// implicitly 'extern "C"' in C++ mode.
///
void InclusionDirective(SourceLocation HashLoc, const Token &IncludeTok,
StringRef FileName, bool IsAngled,
CharSourceRange FilenameRange,
OptionalFileEntryRef File, StringRef SearchPath,
StringRef RelativePath, const Module *SuggestedModule,
bool ModuleImported,
SrcMgr::CharacteristicKind FileType) override {
setSeenNoTrivialPPDirective();
}
/// Callback invoked whenever there was an explicit module-import
/// syntax.
///
/// \param ImportLoc The location of import directive token.
///
/// \param Path The identifiers (and their locations) of the module
/// "path", e.g., "std.vector" would be split into "std" and "vector".
///
/// \param Imported The imported module; can be null if importing failed.
///
void moduleImport(SourceLocation ImportLoc, ModuleIdPath Path,
const Module *Imported) override {
setSeenNoTrivialPPDirective();
}
/// Callback invoked when the end of the main file is reached.
///
/// No subsequent callbacks will be made.
void EndOfMainFile() override { setSeenNoTrivialPPDirective(); }
/// Callback invoked when start reading any pragma directive.
void PragmaDirective(SourceLocation Loc,
PragmaIntroducerKind Introducer) override {}
/// Called by Preprocessor::HandleMacroExpandedIdentifier when a
/// macro invocation is found.
void MacroExpands(const Token &MacroNameTok, const MacroDefinition &MD,
SourceRange Range, const MacroArgs *Args) override;
/// Hook called whenever a macro definition is seen.
void MacroDefined(const Token &MacroNameTok,
const MacroDirective *MD) override {
setSeenNoTrivialPPDirective();
}
/// Hook called whenever a macro \#undef is seen.
/// \param MacroNameTok The active Token
/// \param MD A MacroDefinition for the named macro.
/// \param Undef New MacroDirective if the macro was defined, null otherwise.
///
/// MD is released immediately following this callback.
void MacroUndefined(const Token &MacroNameTok, const MacroDefinition &MD,
const MacroDirective *Undef) override {
setSeenNoTrivialPPDirective();
}
/// Hook called whenever the 'defined' operator is seen.
/// \param MD The MacroDirective if the name was a macro, null otherwise.
void Defined(const Token &MacroNameTok, const MacroDefinition &MD,
SourceRange Range) override {
setSeenNoTrivialPPDirective();
}
/// Hook called whenever an \#if is seen.
/// \param Loc the source location of the directive.
/// \param ConditionRange The SourceRange of the expression being tested.
/// \param ConditionValue The evaluated value of the condition.
///
// FIXME: better to pass in a list (or tree!) of Tokens.
void If(SourceLocation Loc, SourceRange ConditionRange,
ConditionValueKind ConditionValue) override {
setSeenNoTrivialPPDirective();
}
/// Hook called whenever an \#elif is seen.
/// \param Loc the source location of the directive.
/// \param ConditionRange The SourceRange of the expression being tested.
/// \param ConditionValue The evaluated value of the condition.
/// \param IfLoc the source location of the \#if/\#ifdef/\#ifndef directive.
// FIXME: better to pass in a list (or tree!) of Tokens.
void Elif(SourceLocation Loc, SourceRange ConditionRange,
ConditionValueKind ConditionValue, SourceLocation IfLoc) override {
setSeenNoTrivialPPDirective();
}
/// Hook called whenever an \#ifdef is seen.
/// \param Loc the source location of the directive.
/// \param MacroNameTok Information on the token being tested.
/// \param MD The MacroDefinition if the name was a macro, null otherwise.
void Ifdef(SourceLocation Loc, const Token &MacroNameTok,
const MacroDefinition &MD) override {
setSeenNoTrivialPPDirective();
}
/// Hook called whenever an \#elifdef branch is taken.
/// \param Loc the source location of the directive.
/// \param MacroNameTok Information on the token being tested.
/// \param MD The MacroDefinition if the name was a macro, null otherwise.
void Elifdef(SourceLocation Loc, const Token &MacroNameTok,
const MacroDefinition &MD) override {
setSeenNoTrivialPPDirective();
}
/// Hook called whenever an \#elifdef is skipped.
/// \param Loc the source location of the directive.
/// \param ConditionRange The SourceRange of the expression being tested.
/// \param IfLoc the source location of the \#if/\#ifdef/\#ifndef directive.
// FIXME: better to pass in a list (or tree!) of Tokens.
void Elifdef(SourceLocation Loc, SourceRange ConditionRange,
SourceLocation IfLoc) override {
setSeenNoTrivialPPDirective();
}
/// Hook called whenever an \#ifndef is seen.
/// \param Loc the source location of the directive.
/// \param MacroNameTok Information on the token being tested.
/// \param MD The MacroDefiniton if the name was a macro, null otherwise.
void Ifndef(SourceLocation Loc, const Token &MacroNameTok,
const MacroDefinition &MD) override {
setSeenNoTrivialPPDirective();
}
/// Hook called whenever an \#elifndef branch is taken.
/// \param Loc the source location of the directive.
/// \param MacroNameTok Information on the token being tested.
/// \param MD The MacroDefinition if the name was a macro, null otherwise.
void Elifndef(SourceLocation Loc, const Token &MacroNameTok,
const MacroDefinition &MD) override {
setSeenNoTrivialPPDirective();
}
/// Hook called whenever an \#elifndef is skipped.
/// \param Loc the source location of the directive.
/// \param ConditionRange The SourceRange of the expression being tested.
/// \param IfLoc the source location of the \#if/\#ifdef/\#ifndef directive.
// FIXME: better to pass in a list (or tree!) of Tokens.
void Elifndef(SourceLocation Loc, SourceRange ConditionRange,
SourceLocation IfLoc) override {
setSeenNoTrivialPPDirective();
}
/// Hook called whenever an \#else is seen.
/// \param Loc the source location of the directive.
/// \param IfLoc the source location of the \#if/\#ifdef/\#ifndef directive.
void Else(SourceLocation Loc, SourceLocation IfLoc) override {
setSeenNoTrivialPPDirective();
}
/// Hook called whenever an \#endif is seen.
/// \param Loc the source location of the directive.
/// \param IfLoc the source location of the \#if/\#ifdef/\#ifndef directive.
void Endif(SourceLocation Loc, SourceLocation IfLoc) override {
setSeenNoTrivialPPDirective();
}
};
} // namespace clang
#endif // LLVM_CLANG_LEX_NO_TRIVIAL_PPDIRECTIVE_TRACER_H

View File

@ -82,6 +82,7 @@ class PreprocessorLexer;
class PreprocessorOptions;
class ScratchBuffer;
class TargetInfo;
class NoTrivialPPDirectiveTracer;
namespace Builtin {
class Context;
@ -353,6 +354,11 @@ private:
/// First pp-token source location in current translation unit.
SourceLocation FirstPPTokenLoc;
/// A preprocessor directive tracer to trace whether the preprocessing
/// state changed. These changes would mean most semantically observable
/// preprocessor state, particularly anything that is order dependent.
NoTrivialPPDirectiveTracer *DirTracer = nullptr;
/// A position within a C++20 import-seq.
class StdCXXImportSeq {
public:
@ -609,6 +615,8 @@ private:
return State == NamedModuleImplementation && !getName().contains(':');
}
bool isNotAModuleDecl() const { return State == NotAModuleDecl; }
StringRef getName() const {
assert(isNamedModule() && "Can't get name from a non named module");
return Name;
@ -3087,6 +3095,10 @@ public:
bool setDeserializedSafeBufferOptOutMap(
const SmallVectorImpl<SourceLocation> &SrcLocSeqs);
/// Whether we've seen pp-directives which may have changed the preprocessing
/// state.
bool hasSeenNoTrivialPPDirective() const;
private:
/// Helper functions to forward lexing to the actual lexer. They all share the
/// same signature.

View File

@ -86,12 +86,12 @@ public:
// macro stringizing or charizing operator.
CommaAfterElided = 0x200, // The comma following this token was elided (MS).
IsEditorPlaceholder = 0x400, // This identifier is a placeholder.
IsReinjected = 0x800, // A phase 4 token that was produced before and
// re-added, e.g. via EnterTokenStream. Annotation
// tokens are *not* reinjected.
FirstPPToken = 0x1000, // This token is the first pp token in the
// translation unit.
IsReinjected = 0x800, // A phase 4 token that was produced before and
// re-added, e.g. via EnterTokenStream. Annotation
// tokens are *not* reinjected.
HasSeenNoTrivialPPDirective =
0x1000, // Whether we've seen any 'no-trivial' pp-directives before
// current position.
};
tok::TokenKind getKind() const { return Kind; }
@ -321,8 +321,9 @@ public:
/// lexer uses identifier tokens to represent placeholders.
bool isEditorPlaceholder() const { return getFlag(IsEditorPlaceholder); }
/// Returns true if this token is the first pp-token.
bool isFirstPPToken() const { return getFlag(FirstPPToken); }
bool hasSeenNoTrivialPPDirective() const {
return getFlag(HasSeenNoTrivialPPDirective);
}
};
/// Information about the conditional stack (\#if directives)

View File

@ -350,11 +350,6 @@ class Sema;
LLVM_PREFERRED_TYPE(bool)
unsigned BindsToRvalue : 1;
/// Whether this was an identity conversion with qualification
/// conversion for the implicit object argument.
LLVM_PREFERRED_TYPE(bool)
unsigned IsImplicitObjectArgumentQualificationConversion : 1;
/// Whether this binds an implicit object argument to a
/// non-static member function without a ref-qualifier.
LLVM_PREFERRED_TYPE(bool)
@ -453,11 +448,11 @@ class Sema;
#endif
return true;
}
if (!C.hasSameType(getFromType(), getToType(2)))
return false;
if (BindsToRvalue && IsLvalueReference)
return false;
if (IsImplicitObjectArgumentQualificationConversion)
return C.hasSameUnqualifiedType(getFromType(), getToType(2));
return C.hasSameType(getFromType(), getToType(2));
return true;
}
ImplicitConversionRank getRank() const;

View File

@ -9836,7 +9836,7 @@ public:
SourceLocation ModuleLoc, ModuleDeclKind MDK,
ModuleIdPath Path, ModuleIdPath Partition,
ModuleImportState &ImportState,
bool IntroducerIsFirstPPToken);
bool SeenNoTrivialPPDirective);
/// The parser has processed a global-module-fragment declaration that begins
/// the definition of the global module fragment of the current module unit.

View File

@ -456,7 +456,9 @@ CheckStructurallyEquivalentAttributes(StructuralEquivalenceContext &Context,
const Decl *D1, const Decl *D2,
const Decl *PrimaryDecl = nullptr) {
// If either declaration has an attribute on it, we treat the declarations
// as not being structurally equivalent.
// as not being structurally equivalent unless both declarations are implicit
// (ones generated by the compiler like __NSConstantString_tag).
//
// FIXME: this should be handled on a case-by-case basis via tablegen in
// Attr.td. There are multiple cases to consider: one declaration with the
// attribute, another without it; different attribute syntax|spellings for
@ -468,7 +470,7 @@ CheckStructurallyEquivalentAttributes(StructuralEquivalenceContext &Context,
D1Attr = *D1->getAttrs().begin();
if (D2->hasAttrs())
D2Attr = *D2->getAttrs().begin();
if (D1Attr || D2Attr) {
if ((D1Attr || D2Attr) && !D1->isImplicit() && !D2->isImplicit()) {
const auto *DiagnoseDecl = cast<TypeDecl>(PrimaryDecl ? PrimaryDecl : D2);
Context.Diag2(DiagnoseDecl->getLocation(),
diag::warn_odr_tag_type_with_attributes)
@ -873,7 +875,29 @@ static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
else if (T1->getTypeClass() == Type::FunctionNoProto &&
T2->getTypeClass() == Type::FunctionProto)
TC = Type::FunctionNoProto;
else
else if (Context.LangOpts.C23 && !Context.StrictTypeSpelling &&
(T1->getTypeClass() == Type::Enum ||
T2->getTypeClass() == Type::Enum)) {
// In C23, if not being strict about token equivalence, we need to handle
// the case where one type is an enumeration and the other type is an
// integral type.
//
// C23 6.7.3.3p16: The enumerated type is compatible with the underlying
// type of the enumeration.
//
// Treat the enumeration as its underlying type and use the builtin type
// class comparison.
if (T1->getTypeClass() == Type::Enum) {
T1 = T1->getAs<EnumType>()->getDecl()->getIntegerType();
if (!T2->isBuiltinType() || T1.isNull()) // Sanity check
return false;
} else if (T2->getTypeClass() == Type::Enum) {
T2 = T2->getAs<EnumType>()->getDecl()->getIntegerType();
if (!T1->isBuiltinType() || T2.isNull()) // Sanity check
return false;
}
TC = Type::Builtin;
} else
return false;
}
@ -2067,6 +2091,48 @@ static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
!CheckStructurallyEquivalentAttributes(Context, D1, D2))
return false;
// In C23, if one enumeration has a fixed underlying type, the other shall
// have a compatible fixed underlying type (6.2.7).
if (Context.LangOpts.C23) {
if (D1->isFixed() != D2->isFixed()) {
if (Context.Complain) {
Context.Diag2(D2->getLocation(),
Context.getApplicableDiagnostic(
diag::err_odr_tag_type_inconsistent))
<< Context.ToCtx.getTypeDeclType(D2)
<< (&Context.FromCtx != &Context.ToCtx);
Context.Diag1(D1->getLocation(),
D1->isFixed()
? diag::note_odr_fixed_underlying_type
: diag::note_odr_missing_fixed_underlying_type)
<< D1;
Context.Diag2(D2->getLocation(),
D2->isFixed()
? diag::note_odr_fixed_underlying_type
: diag::note_odr_missing_fixed_underlying_type)
<< D2;
}
return false;
}
if (D1->isFixed()) {
assert(D2->isFixed() && "enums expected to have fixed underlying types");
if (!IsStructurallyEquivalent(Context, D1->getIntegerType(),
D2->getIntegerType())) {
if (Context.Complain) {
Context.Diag2(D2->getLocation(),
Context.getApplicableDiagnostic(
diag::err_odr_tag_type_inconsistent))
<< Context.ToCtx.getTypeDeclType(D2)
<< (&Context.FromCtx != &Context.ToCtx);
Context.Diag2(D2->getLocation(),
diag::note_odr_incompatible_fixed_underlying_type)
<< D2 << D2->getIntegerType() << D1->getIntegerType();
}
return false;
}
}
}
llvm::SmallVector<const EnumConstantDecl *, 8> D1Enums, D2Enums;
auto CopyEnumerators =
[](auto &&Range, llvm::SmallVectorImpl<const EnumConstantDecl *> &Cont) {

View File

@ -4441,7 +4441,8 @@ static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
}
} else if (!IsAccess) {
return CompleteObject(LVal.getLValueBase(), nullptr, BaseType);
} else if (IsConstant && Info.checkingPotentialConstantExpression() &&
} else if ((IsConstant || BaseType->isReferenceType()) &&
Info.checkingPotentialConstantExpression() &&
BaseType->isLiteralType(Info.Ctx) && !VD->hasDefinition()) {
// This variable might end up being constexpr. Don't diagnose it yet.
} else if (IsConstant) {
@ -4478,9 +4479,11 @@ static CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E,
// a null BaseVal. Any constexpr-unknown variable seen here is an error:
// we can't access a constexpr-unknown object.
if (!BaseVal) {
Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
<< AK << VD;
Info.Note(VD->getLocation(), diag::note_declared_at);
if (!Info.checkingPotentialConstantExpression()) {
Info.FFDiag(E, diag::note_constexpr_access_unknown_variable, 1)
<< AK << VD;
Info.Note(VD->getLocation(), diag::note_declared_at);
}
return CompleteObject();
}
} else if (DynamicAllocLValue DA = LVal.Base.dyn_cast<DynamicAllocLValue>()) {
@ -14478,12 +14481,6 @@ EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
if (!EvaluatePointer(E->getRHS(), RHSValue, Info) || !LHSOK)
return false;
// If we have Unknown pointers we should fail if they are not global values.
if (!(IsGlobalLValue(LHSValue.getLValueBase()) &&
IsGlobalLValue(RHSValue.getLValueBase())) &&
(LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown))
return false;
// Reject differing bases from the normal codepath; we special-case
// comparisons to null.
if (!HasSameBase(LHSValue, RHSValue)) {
@ -14545,6 +14542,10 @@ EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
(LHSValue.Base && isZeroSized(RHSValue)))
return DiagComparison(
diag::note_constexpr_pointer_comparison_zero_sized);
if (LHSValue.AllowConstexprUnknown || RHSValue.AllowConstexprUnknown)
return DiagComparison(
diag::note_constexpr_pointer_comparison_unspecified);
// FIXME: Verify both variables are live.
return Success(CmpResult::Unequal, E);
}
@ -14565,7 +14566,9 @@ EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
if (!LHSDesignator.Invalid && !RHSDesignator.Invalid && IsRelational) {
bool WasArrayIndex;
unsigned Mismatch = FindDesignatorMismatch(
getType(LHSValue.Base), LHSDesignator, RHSDesignator, WasArrayIndex);
LHSValue.Base.isNull() ? QualType()
: getType(LHSValue.Base).getNonReferenceType(),
LHSDesignator, RHSDesignator, WasArrayIndex);
// At the point where the designators diverge, the comparison has a
// specified value if:
// - we are comparing array indices
@ -14609,7 +14612,7 @@ EvaluateComparisonBinaryOperator(EvalInfo &Info, const BinaryOperator *E,
// compare pointers within the object in question; otherwise, the result
// depends on where the object is located in memory.
if (!LHSValue.Base.isNull() && IsRelational) {
QualType BaseTy = getType(LHSValue.Base);
QualType BaseTy = getType(LHSValue.Base).getNonReferenceType();
if (BaseTy->isIncompleteType())
return Error(E);
CharUnits Size = Info.Ctx.getTypeSizeInChars(BaseTy);

View File

@ -1331,7 +1331,7 @@ void ThreadSafetyAnalyzer::addLock(FactSet &FSet,
FSet.removeLock(FactMan, NegC);
}
else {
if (inCurrentScope(*Entry) && !Entry->asserted())
if (inCurrentScope(*Entry) && !Entry->asserted() && !Entry->reentrant())
Handler.handleNegativeNotHeld(Entry->getKind(), Entry->toString(),
NegC.toString(), Entry->loc());
}

View File

@ -769,6 +769,9 @@ std::unique_ptr<TargetInfo> AllocateTarget(const llvm::Triple &Triple,
case llvm::Triple::FreeBSD:
return std::make_unique<FreeBSDTargetInfo<LoongArch64TargetInfo>>(Triple,
Opts);
case llvm::Triple::OpenBSD:
return std::make_unique<OpenBSDTargetInfo<LoongArch64TargetInfo>>(Triple,
Opts);
default:
return std::make_unique<LoongArch64TargetInfo>(Triple, Opts);
}

View File

@ -461,6 +461,8 @@ LoongArchTargetInfo::parseTargetAttr(StringRef Features) const {
case AttrFeatureKind::Feature:
Ret.Features.push_back("+" + Value.str());
if (Value == "lasx")
Ret.Features.push_back("+lsx");
break;
}
}

View File

@ -129,7 +129,7 @@ public:
LongWidth = LongAlign = 32;
MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 32;
PointerWidth = PointerAlign = 32;
PtrDiffType = SignedInt;
PtrDiffType = IntPtrType = SignedInt;
SizeType = UnsignedInt;
SuitableAlign = 64;
}
@ -155,7 +155,7 @@ public:
IntMaxType = Int64Type;
LongWidth = LongAlign = 64;
PointerWidth = PointerAlign = 64;
PtrDiffType = SignedLong;
PtrDiffType = IntPtrType = SignedLong;
SizeType = UnsignedLong;
}
@ -165,7 +165,7 @@ public:
IntMaxType = Int64Type;
LongWidth = LongAlign = 32;
PointerWidth = PointerAlign = 32;
PtrDiffType = SignedInt;
PtrDiffType = IntPtrType = SignedInt;
SizeType = UnsignedInt;
}

View File

@ -496,6 +496,7 @@ public:
case llvm::Triple::sparcv9:
this->MCountName = "_mcount";
break;
case llvm::Triple::loongarch64:
case llvm::Triple::riscv64:
break;
}

View File

@ -176,6 +176,11 @@ public:
static Address invalid() { return Address(nullptr); }
bool isValid() const { return Pointer.getPointer() != nullptr; }
llvm::Value *getPointerIfNotSigned() const {
assert(isValid() && "pointer isn't valid");
return !isSigned() ? Pointer.getPointer() : nullptr;
}
/// This function is used in situations where the caller is doing some sort of
/// opaque "laundering" of the pointer.
void replaceBasePointer(llvm::Value *P) {

View File

@ -188,13 +188,14 @@ static llvm::Constant *buildBlockDescriptor(CodeGenModule &CGM,
// Optional copy/dispose helpers.
bool hasInternalHelper = false;
if (blockInfo.NeedsCopyDispose) {
auto &Schema = CGM.getCodeGenOpts().PointerAuth.BlockHelperFunctionPointers;
// copy_func_helper_decl
llvm::Constant *copyHelper = buildCopyHelper(CGM, blockInfo);
elements.add(copyHelper);
elements.addSignedPointer(copyHelper, Schema, GlobalDecl(), QualType());
// destroy_func_decl
llvm::Constant *disposeHelper = buildDisposeHelper(CGM, blockInfo);
elements.add(disposeHelper);
elements.addSignedPointer(disposeHelper, Schema, GlobalDecl(), QualType());
if (cast<llvm::Function>(copyHelper->stripPointerCasts())
->hasInternalLinkage() ||
@ -567,9 +568,8 @@ static void computeBlockInfo(CodeGenModule &CGM, CodeGenFunction *CGF,
llvm::StructType::get(CGM.getLLVMContext(), elementTypes, true);
info.CanBeGlobal = true;
return;
}
else if (C.getLangOpts().ObjC &&
CGM.getLangOpts().getGC() == LangOptions::NonGC)
} else if (C.getLangOpts().ObjC &&
CGM.getLangOpts().getGC() == LangOptions::NonGC)
info.HasCapturedVariableLayout = true;
if (block->doesNotEscape())
@ -783,7 +783,7 @@ llvm::Value *CodeGenFunction::EmitBlockLiteral(const BlockExpr *blockExpr) {
llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
bool IsOpenCL = CGM.getContext().getLangOpts().OpenCL;
auto GenVoidPtrTy =
llvm::PointerType *GenVoidPtrTy =
IsOpenCL ? CGM.getOpenCLRuntime().getGenericVoidPointerType() : VoidPtrTy;
LangAS GenVoidPtrAddr = IsOpenCL ? LangAS::opencl_generic : LangAS::Default;
auto GenVoidPtrSize = CharUnits::fromQuantity(
@ -817,9 +817,6 @@ llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
: CGM.getNSConcreteStackBlock();
isa = blockISA;
// Build the block descriptor.
descriptor = buildBlockDescriptor(CGM, blockInfo);
// Compute the initial on-stack block flags.
if (!CGM.getCodeGenOpts().DisableBlockSignatureString)
flags = BLOCK_HAS_SIGNATURE;
@ -833,6 +830,9 @@ llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
flags |= BLOCK_USE_STRET;
if (blockInfo.NoEscape)
flags |= BLOCK_IS_NOESCAPE | BLOCK_IS_GLOBAL;
// Build the block descriptor.
descriptor = buildBlockDescriptor(CGM, blockInfo);
}
auto projectField = [&](unsigned index, const Twine &name) -> Address {
@ -883,11 +883,25 @@ llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
llvm::ConstantInt::get(IntTy, blockInfo.BlockAlign.getQuantity()),
getIntSize(), "block.align");
}
addHeaderField(blockFn, GenVoidPtrSize, "block.invoke");
if (!IsOpenCL)
addHeaderField(descriptor, getPointerSize(), "block.descriptor");
else if (auto *Helper =
CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
if (!IsOpenCL) {
llvm::Value *blockFnPtr =
llvm::ConstantExpr::getBitCast(InvokeFn, VoidPtrTy);
QualType type = blockInfo.getBlockExpr()
->getType()
->castAs<BlockPointerType>()
->getPointeeType();
addSignedHeaderField(
blockFnPtr,
CGM.getCodeGenOpts().PointerAuth.BlockInvocationFunctionPointers,
GlobalDecl(), type, getPointerSize(), "block.invoke");
addSignedHeaderField(
descriptor, CGM.getCodeGenOpts().PointerAuth.BlockDescriptorPointers,
GlobalDecl(), type, getPointerSize(), "block.descriptor");
} else if (auto *Helper =
CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
addHeaderField(blockFn, GenVoidPtrSize, "block.invoke");
for (auto I : Helper->getCustomFieldValues(*this, blockInfo)) {
addHeaderField(
I.first,
@ -895,7 +909,8 @@ llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
CGM.getDataLayout().getTypeAllocSize(I.first->getType())),
I.second);
}
}
} else
addHeaderField(blockFn, GenVoidPtrSize, "block.invoke");
}
// Finally, capture all the values into the block.
@ -1166,6 +1181,8 @@ RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
ASTContext &Ctx = getContext();
CallArgList Args;
llvm::Value *FuncPtr = nullptr;
if (getLangOpts().OpenCL) {
// For OpenCL, BlockPtr is already casted to generic block literal.
@ -1185,7 +1202,7 @@ RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
if (!isa<ParmVarDecl>(E->getCalleeDecl()))
Func = CGM.getOpenCLRuntime().getInvokeFunction(E->getCallee());
else {
llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 2);
FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 2);
Func = Builder.CreateAlignedLoad(GenericVoidPtrTy, FuncPtr,
getPointerAlign());
}
@ -1194,7 +1211,7 @@ RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
BlockPtr =
Builder.CreatePointerCast(BlockPtr, UnqualPtrTy, "block.literal");
// Get pointer to the block invoke function
llvm::Value *FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 3);
FuncPtr = Builder.CreateStructGEP(GenBlockTy, BlockPtr, 3);
// First argument is a block literal casted to a void pointer
BlockPtr = Builder.CreatePointerCast(BlockPtr, VoidPtrTy);
@ -1211,7 +1228,15 @@ RValue CodeGenFunction::EmitBlockCallExpr(const CallExpr *E,
CGM.getTypes().arrangeBlockFunctionCall(Args, FuncTy);
// Prepare the callee.
CGCallee Callee(CGCalleeInfo(), Func);
CGPointerAuthInfo PointerAuth;
if (auto &AuthSchema =
CGM.getCodeGenOpts().PointerAuth.BlockInvocationFunctionPointers) {
assert(FuncPtr != nullptr && "Missing function pointer for AuthInfo");
PointerAuth =
EmitPointerAuthInfo(AuthSchema, FuncPtr, GlobalDecl(), FnType);
}
CGCallee Callee(CGCalleeInfo(), Func, PointerAuth);
// And call the block.
return EmitCall(FnInfo, Callee, ReturnValue, Args, CallOrInvoke);
@ -1295,14 +1320,15 @@ static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
bool IsOpenCL = CGM.getLangOpts().OpenCL;
bool IsWindows = CGM.getTarget().getTriple().isOSWindows();
auto &CGOPointerAuth = CGM.getCodeGenOpts().PointerAuth;
if (!IsOpenCL) {
// isa
if (IsWindows)
fields.addNullPointer(CGM.Int8PtrPtrTy);
else
fields.addSignedPointer(CGM.getNSConcreteGlobalBlock(),
CGM.getCodeGenOpts().PointerAuth.ObjCIsaPointers,
GlobalDecl(), QualType());
CGOPointerAuth.ObjCIsaPointers, GlobalDecl(),
QualType());
// __flags
BlockFlags flags = BLOCK_IS_GLOBAL;
@ -1321,11 +1347,20 @@ static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
}
// Function
fields.add(blockFn);
if (auto &Schema = CGOPointerAuth.BlockInvocationFunctionPointers) {
QualType FnType = blockInfo.getBlockExpr()
->getType()
->castAs<BlockPointerType>()
->getPointeeType();
fields.addSignedPointer(blockFn, Schema, GlobalDecl(), FnType);
} else
fields.add(blockFn);
if (!IsOpenCL) {
// Descriptor
fields.add(buildBlockDescriptor(CGM, blockInfo));
llvm::Constant *Descriptor = buildBlockDescriptor(CGM, blockInfo);
fields.addSignedPointer(Descriptor, CGOPointerAuth.BlockDescriptorPointers,
GlobalDecl(), QualType());
} else if (auto *Helper =
CGM.getTargetCodeGenInfo().getTargetOpenCLBlockHelper()) {
for (auto *I : Helper->getCustomFieldValues(CGM, blockInfo)) {
@ -1995,8 +2030,8 @@ CodeGenFunction::GenerateCopyHelperFunction(const CGBlockInfo &blockInfo) {
// it. It's not quite worth the annoyance to avoid creating it in the
// first place.
if (!needsEHCleanup(captureType.isDestructedType()))
if (auto *I =
cast_or_null<llvm::Instruction>(dstField.getBasePointer()))
if (auto *I = cast_or_null<llvm::Instruction>(
dstField.getPointerIfNotSigned()))
I->eraseFromParent();
}
break;
@ -2730,8 +2765,16 @@ void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
unsigned nextHeaderIndex = 0;
CharUnits nextHeaderOffset;
auto storeHeaderField = [&](llvm::Value *value, CharUnits fieldSize,
const Twine &name) {
const Twine &name, bool isFunction = false) {
auto fieldAddr = Builder.CreateStructGEP(addr, nextHeaderIndex, name);
if (isFunction) {
if (auto &Schema = CGM.getCodeGenOpts()
.PointerAuth.BlockByrefHelperFunctionPointers) {
auto PointerAuth = EmitPointerAuthInfo(
Schema, fieldAddr.emitRawPointer(*this), GlobalDecl(), QualType());
value = EmitPointerAuthSign(PointerAuth, value);
}
}
Builder.CreateStore(value, fieldAddr);
nextHeaderIndex++;
@ -2814,10 +2857,10 @@ void CodeGenFunction::emitByrefStructureInit(const AutoVarEmission &emission) {
storeHeaderField(V, getIntSize(), "byref.size");
if (helpers) {
storeHeaderField(helpers->CopyHelper, getPointerSize(),
"byref.copyHelper");
storeHeaderField(helpers->CopyHelper, getPointerSize(), "byref.copyHelper",
/*isFunction=*/true);
storeHeaderField(helpers->DisposeHelper, getPointerSize(),
"byref.disposeHelper");
"byref.disposeHelper", /*isFunction=*/true);
}
if (ByRefHasLifetime && HasByrefExtendedLayout) {

View File

@ -707,11 +707,15 @@ struct GetReturnObjectManager {
Builder.CreateStore(Builder.getFalse(), GroActiveFlag);
GroEmission = CGF.EmitAutoVarAlloca(*GroVarDecl);
auto *GroAlloca = dyn_cast_or_null<llvm::AllocaInst>(
GroEmission.getOriginalAllocatedAddress().getPointer());
assert(GroAlloca && "expected alloca to be emitted");
GroAlloca->setMetadata(llvm::LLVMContext::MD_coro_outside_frame,
llvm::MDNode::get(CGF.CGM.getLLVMContext(), {}));
if (!GroVarDecl->isNRVOVariable()) {
// NRVO variables don't have allocas and won't have the same issue.
auto *GroAlloca = dyn_cast_or_null<llvm::AllocaInst>(
GroEmission.getOriginalAllocatedAddress().getPointer());
assert(GroAlloca && "expected alloca to be emitted");
GroAlloca->setMetadata(llvm::LLVMContext::MD_coro_outside_frame,
llvm::MDNode::get(CGF.CGM.getLLVMContext(), {}));
}
// Remember the top of EHStack before emitting the cleanup.
auto old_top = CGF.EHStack.stable_begin();

View File

@ -170,6 +170,10 @@ void CGDebugInfo::addInstToSpecificSourceAtom(llvm::Instruction *KeyInstruction,
if (!Group || !CGM.getCodeGenOpts().DebugKeyInstructions)
return;
llvm::DISubprogram *SP = KeyInstruction->getFunction()->getSubprogram();
if (!SP || !SP->getKeyInstructionsEnabled())
return;
addInstSourceAtomMetadata(KeyInstruction, Group, /*Rank=*/1);
llvm::Instruction *BackupI =
@ -2641,7 +2645,8 @@ StringRef CGDebugInfo::getVTableName(const CXXRecordDecl *RD) {
// existing information in the DWARF. The type is assumed to be 'void *'.
void CGDebugInfo::emitVTableSymbol(llvm::GlobalVariable *VTable,
const CXXRecordDecl *RD) {
if (!CGM.getTarget().getCXXABI().isItaniumFamily())
if (!CGM.getTarget().getCXXABI().isItaniumFamily() ||
CGM.getTarget().getTriple().isOSBinFormatCOFF())
return;
ASTContext &Context = CGM.getContext();

View File

@ -2313,7 +2313,8 @@ llvm::Value *CodeGenFunction::EmitDynamicCast(Address ThisAddr,
bool IsExact = !IsDynamicCastToVoid &&
CGM.getCodeGenOpts().OptimizationLevel > 0 &&
DestRecordTy->getAsCXXRecordDecl()->isEffectivelyFinal() &&
CGM.getCXXABI().shouldEmitExactDynamicCast(DestRecordTy);
CGM.getCXXABI().shouldEmitExactDynamicCast(DestRecordTy) &&
!getLangOpts().PointerAuthCalls;
// C++ [expr.dynamic.cast]p4:
// If the value of v is a null pointer value in the pointer case, the result

View File

@ -846,11 +846,13 @@ void CodeGenFunction::EmitGotoStmt(const GotoStmt &S) {
if (HaveInsertPoint())
EmitStopPoint(&S);
ApplyAtomGroup Grp(getDebugInfo());
EmitBranchThroughCleanup(getJumpDestForLabel(S.getLabel()));
}
void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
ApplyAtomGroup Grp(getDebugInfo());
if (const LabelDecl *Target = S.getConstantTarget()) {
EmitBranchThroughCleanup(getJumpDestForLabel(Target));
return;
@ -869,6 +871,8 @@ void CodeGenFunction::EmitIndirectGotoStmt(const IndirectGotoStmt &S) {
cast<llvm::PHINode>(IndGotoBB->begin())->addIncoming(V, CurBB);
EmitBranch(IndGotoBB);
if (CurBB && CurBB->getTerminator())
addInstToCurrentSourceAtom(CurBB->getTerminator(), nullptr);
}
void CodeGenFunction::EmitIfStmt(const IfStmt &S) {
@ -2672,6 +2676,9 @@ static void UpdateAsmCallInst(llvm::CallBase &Result, bool HasSideEffect,
llvm::ConstantAsMetadata::get(Loc)));
}
// Make inline-asm calls Key for the debug info feature Key Instructions.
CGF.addInstToNewSourceAtom(&Result, nullptr);
if (!NoConvergent && CGF.getLangOpts().assumeFunctionsAreConvergent())
// Conservatively, mark all inline asm blocks in CUDA or OpenCL as
// convergent (meaning, they may call an intrinsically convergent op, such
@ -2750,6 +2757,7 @@ EmitAsmStores(CodeGenFunction &CGF, const AsmStmt &S,
}
}
ApplyAtomGroup Grp(CGF.getDebugInfo());
LValue Dest = ResultRegDests[i];
// ResultTypeRequiresCast elements correspond to the first
// ResultTypeRequiresCast.size() elements of RegResults.
@ -2757,7 +2765,8 @@ EmitAsmStores(CodeGenFunction &CGF, const AsmStmt &S,
unsigned Size = CGF.getContext().getTypeSize(ResultRegQualTys[i]);
Address A = Dest.getAddress().withElementType(ResultRegTypes[i]);
if (CGF.getTargetHooks().isScalarizableAsmOperand(CGF, TruncTy)) {
Builder.CreateStore(Tmp, A);
llvm::StoreInst *S = Builder.CreateStore(Tmp, A);
CGF.addInstToCurrentSourceAtom(S, S->getValueOperand());
continue;
}

View File

@ -837,17 +837,30 @@ void ToolChain::addFortranRuntimeLibs(const ArgList &Args,
void ToolChain::addFortranRuntimeLibraryPath(const llvm::opt::ArgList &Args,
ArgStringList &CmdArgs) const {
// Default to the <driver-path>/../lib directory. This works fine on the
// platforms that we have tested so far. We will probably have to re-fine
// this in the future. In particular, on some platforms, we may need to use
// lib64 instead of lib.
auto AddLibSearchPathIfExists = [&](const Twine &Path) {
// Linker may emit warnings about non-existing directories
if (!llvm::sys::fs::is_directory(Path))
return;
if (getTriple().isKnownWindowsMSVCEnvironment())
CmdArgs.push_back(Args.MakeArgString("-libpath:" + Path));
else
CmdArgs.push_back(Args.MakeArgString("-L" + Path));
};
// Search for flang_rt.* at the same location as clang_rt.* with
// LLVM_ENABLE_PER_TARGET_RUNTIME_DIR=0. On most platforms, flang_rt is
// located at the path returned by getRuntimePath() which is already added to
// the library search path. This exception is for Apple-Darwin.
AddLibSearchPathIfExists(getCompilerRTPath());
// Fall back to the non-resource directory <driver-path>/../lib. We will
// probably have to refine this in the future. In particular, on some
// platforms, we may need to use lib64 instead of lib.
SmallString<256> DefaultLibPath =
llvm::sys::path::parent_path(getDriver().Dir);
llvm::sys::path::append(DefaultLibPath, "lib");
if (getTriple().isKnownWindowsMSVCEnvironment())
CmdArgs.push_back(Args.MakeArgString("-libpath:" + DefaultLibPath));
else
CmdArgs.push_back(Args.MakeArgString("-L" + DefaultLibPath));
AddLibSearchPathIfExists(DefaultLibPath);
}
void ToolChain::addFlangRTLibPath(const ArgList &Args,

View File

@ -467,3 +467,18 @@ void aarch64::setPAuthABIInTriple(const Driver &D, const ArgList &Args,
break;
}
}
/// Is the triple {aarch64.aarch64_be}-none-elf?
bool aarch64::isAArch64BareMetal(const llvm::Triple &Triple) {
if (Triple.getArch() != llvm::Triple::aarch64 &&
Triple.getArch() != llvm::Triple::aarch64_be)
return false;
if (Triple.getVendor() != llvm::Triple::UnknownVendor)
return false;
if (Triple.getOS() != llvm::Triple::UnknownOS)
return false;
return Triple.getEnvironmentName() == "elf";
}

View File

@ -30,6 +30,7 @@ std::string getAArch64TargetCPU(const llvm::opt::ArgList &Args,
void setPAuthABIInTriple(const Driver &D, const llvm::opt::ArgList &Args,
llvm::Triple &triple);
bool isAArch64BareMetal(const llvm::Triple &Triple);
} // end namespace aarch64
} // end namespace target

View File

@ -23,7 +23,9 @@ const char *sparc::getSparcAsmModeForCPU(StringRef Name,
if (Triple.getArch() == llvm::Triple::sparcv9) {
const char *DefV9CPU;
if (Triple.isOSLinux() || Triple.isOSFreeBSD() || Triple.isOSOpenBSD())
if (Triple.isOSSolaris())
DefV9CPU = "-Av9b";
else if (Triple.isOSLinux() || Triple.isOSFreeBSD() || Triple.isOSOpenBSD())
DefV9CPU = "-Av9a";
else
DefV9CPU = "-Av9";
@ -35,6 +37,13 @@ const char *sparc::getSparcAsmModeForCPU(StringRef Name,
.Case("niagara4", "-Av9d")
.Default(DefV9CPU);
} else {
const char *DefV8CPU;
if (Triple.isOSSolaris())
DefV8CPU = "-Av8plus";
else
DefV8CPU = "-Av8";
return llvm::StringSwitch<const char *>(Name)
.Case("v8", "-Av8")
.Case("supersparc", "-Av8")
@ -70,7 +79,7 @@ const char *sparc::getSparcAsmModeForCPU(StringRef Name,
.Case("gr712rc", "-Aleon")
.Case("leon4", "-Aleon")
.Case("gr740", "-Aleon")
.Default("-Av8");
.Default(DefV8CPU);
}
}
@ -130,7 +139,8 @@ std::string sparc::getSparcTargetCPU(const Driver &D, const ArgList &Args,
return "";
}
void sparc::getSparcTargetFeatures(const Driver &D, const ArgList &Args,
void sparc::getSparcTargetFeatures(const Driver &D, const llvm::Triple &Triple,
const ArgList &Args,
std::vector<StringRef> &Features) {
sparc::FloatABI FloatABI = sparc::getSparcFloatABI(D, Args);
if (FloatABI == sparc::FloatABI::Soft)
@ -150,11 +160,22 @@ void sparc::getSparcTargetFeatures(const Driver &D, const ArgList &Args,
Features.push_back("-popc");
}
// Those OSes default to enabling VIS on 64-bit SPARC.
// See also the corresponding code for external assemblers in
// sparc::getSparcAsmModeForCPU().
bool IsSparcV9ATarget =
(Triple.getArch() == llvm::Triple::sparcv9) &&
(Triple.isOSLinux() || Triple.isOSFreeBSD() || Triple.isOSOpenBSD());
bool IsSparcV9BTarget = Triple.isOSSolaris();
bool IsSparcV8PlusTarget =
Triple.getArch() == llvm::Triple::sparc && Triple.isOSSolaris();
if (Arg *A = Args.getLastArg(options::OPT_mvis, options::OPT_mno_vis)) {
if (A->getOption().matches(options::OPT_mvis))
Features.push_back("+vis");
else
Features.push_back("-vis");
} else if (IsSparcV9ATarget) {
Features.push_back("+vis");
}
if (Arg *A = Args.getLastArg(options::OPT_mvis2, options::OPT_mno_vis2)) {
@ -162,6 +183,8 @@ void sparc::getSparcTargetFeatures(const Driver &D, const ArgList &Args,
Features.push_back("+vis2");
else
Features.push_back("-vis2");
} else if (IsSparcV9BTarget) {
Features.push_back("+vis2");
}
if (Arg *A = Args.getLastArg(options::OPT_mvis3, options::OPT_mno_vis3)) {
@ -182,6 +205,8 @@ void sparc::getSparcTargetFeatures(const Driver &D, const ArgList &Args,
if (Arg *A = Args.getLastArg(options::OPT_mv8plus, options::OPT_mno_v8plus)) {
if (A->getOption().matches(options::OPT_mv8plus))
Features.push_back("+v8plus");
} else if (IsSparcV8PlusTarget) {
Features.push_back("+v8plus");
}
if (Args.hasArg(options::OPT_ffixed_g1))

View File

@ -31,7 +31,8 @@ FloatABI getSparcFloatABI(const Driver &D, const llvm::opt::ArgList &Args);
std::string getSparcTargetCPU(const Driver &D, const llvm::opt::ArgList &Args,
const llvm::Triple &Triple);
void getSparcTargetFeatures(const Driver &D, const llvm::opt::ArgList &Args,
void getSparcTargetFeatures(const Driver &D, const llvm::Triple &Triple,
const llvm::opt::ArgList &Args,
std::vector<llvm::StringRef> &Features);
const char *getSparcAsmModeForCPU(llvm::StringRef Name,
const llvm::Triple &Triple);

View File

@ -12,6 +12,7 @@
#include "clang/Driver/CommonArgs.h"
#include "clang/Driver/InputInfo.h"
#include "Arch/AArch64.h"
#include "Arch/ARM.h"
#include "Arch/RISCV.h"
#include "clang/Driver/Compilation.h"
@ -31,21 +32,6 @@ using namespace clang::driver;
using namespace clang::driver::tools;
using namespace clang::driver::toolchains;
/// Is the triple {aarch64.aarch64_be}-none-elf?
static bool isAArch64BareMetal(const llvm::Triple &Triple) {
if (Triple.getArch() != llvm::Triple::aarch64 &&
Triple.getArch() != llvm::Triple::aarch64_be)
return false;
if (Triple.getVendor() != llvm::Triple::UnknownVendor)
return false;
if (Triple.getOS() != llvm::Triple::UnknownOS)
return false;
return Triple.getEnvironmentName() == "elf";
}
static bool isRISCVBareMetal(const llvm::Triple &Triple) {
if (!Triple.isRISCV())
return false;
@ -363,8 +349,9 @@ void BareMetal::findMultilibs(const Driver &D, const llvm::Triple &Triple,
}
bool BareMetal::handlesTarget(const llvm::Triple &Triple) {
return arm::isARMEABIBareMetal(Triple) || isAArch64BareMetal(Triple) ||
isRISCVBareMetal(Triple) || isPPCBareMetal(Triple);
return arm::isARMEABIBareMetal(Triple) ||
aarch64::isAArch64BareMetal(Triple) || isRISCVBareMetal(Triple) ||
isPPCBareMetal(Triple);
}
Tool *BareMetal::buildLinker() const {
@ -694,9 +681,6 @@ void baremetal::Linker::ConstructJob(Compilation &C, const JobAction &JA,
NeedCRTs)
CmdArgs.push_back(Args.MakeArgString(TC.GetFilePath(CRTEnd)));
if (TC.getTriple().isRISCV())
CmdArgs.push_back("-X");
// The R_ARM_TARGET2 relocation must be treated as R_ARM_REL32 on arm*-*-elf
// and arm*-*-eabi (the default is R_ARM_GOT_PREL, used on arm*-*-linux and
// arm*-*-*bsd).

View File

@ -1752,7 +1752,6 @@ void Clang::AddAArch64TargetArgs(const ArgList &Args,
options::OPT_fno_ptrauth_objc_interface_sel);
Args.addOptInFlag(CmdArgs, options::OPT_fptrauth_objc_class_ro,
options::OPT_fno_ptrauth_objc_class_ro);
if (Triple.getEnvironment() == llvm::Triple::PAuthTest)
handlePAuthABI(Args, CmdArgs);
@ -2731,16 +2730,6 @@ static void CollectArgsForIntegratedAssembler(Compilation &C,
CmdArgs.push_back(MipsTargetFeature);
}
// Those OSes default to enabling VIS on 64-bit SPARC.
// See also the corresponding code for external assemblers in
// sparc::getSparcAsmModeForCPU().
bool IsSparcV9ATarget =
(C.getDefaultToolChain().getArch() == llvm::Triple::sparcv9) &&
(Triple.isOSLinux() || Triple.isOSFreeBSD() || Triple.isOSOpenBSD());
if (IsSparcV9ATarget && SparcTargetFeatures.empty()) {
CmdArgs.push_back("-target-feature");
CmdArgs.push_back("+vis");
}
for (const char *Feature : SparcTargetFeatures) {
CmdArgs.push_back("-target-feature");
CmdArgs.push_back(Feature);

View File

@ -547,15 +547,22 @@ const char *tools::getLDMOption(const llvm::Triple &T, const ArgList &Args) {
case llvm::Triple::aarch64:
if (T.isOSManagarm())
return "aarch64managarm";
else if (aarch64::isAArch64BareMetal(T))
return "aarch64elf";
return "aarch64linux";
case llvm::Triple::aarch64_be:
if (aarch64::isAArch64BareMetal(T))
return "aarch64elfb";
return "aarch64linuxb";
case llvm::Triple::arm:
case llvm::Triple::thumb:
case llvm::Triple::armeb:
case llvm::Triple::thumbeb:
return tools::arm::isARMBigEndian(T, Args) ? "armelfb_linux_eabi"
: "armelf_linux_eabi";
case llvm::Triple::thumbeb: {
bool IsBigEndian = tools::arm::isARMBigEndian(T, Args);
if (arm::isARMEABIBareMetal(T))
return IsBigEndian ? "armelfb" : "armelf";
return IsBigEndian ? "armelfb_linux_eabi" : "armelf_linux_eabi";
}
case llvm::Triple::m68k:
return "m68kelf";
case llvm::Triple::ppc:
@ -856,7 +863,7 @@ void tools::getTargetFeatures(const Driver &D, const llvm::Triple &Triple,
case llvm::Triple::sparc:
case llvm::Triple::sparcel:
case llvm::Triple::sparcv9:
sparc::getSparcTargetFeatures(D, Args, Features);
sparc::getSparcTargetFeatures(D, Triple, Args, Features);
break;
case llvm::Triple::r600:
case llvm::Triple::amdgcn:
@ -1320,6 +1327,17 @@ void tools::addLTOOptions(const ToolChain &ToolChain, const ArgList &Args,
if (Args.hasArg(options::OPT_ftime_report))
CmdArgs.push_back(
Args.MakeArgString(Twine(PluginOptPrefix) + "-time-passes"));
if (Arg *A = Args.getLastArg(options::OPT_fthinlto_distributor_EQ)) {
CmdArgs.push_back(
Args.MakeArgString("--thinlto-distributor=" + Twine(A->getValue())));
CmdArgs.push_back(
Args.MakeArgString("--thinlto-remote-compiler=" +
Twine(ToolChain.getDriver().getClangProgramPath())));
for (auto A : Args.getAllArgValues(options::OPT_Xthinlto_distributor_EQ))
CmdArgs.push_back(Args.MakeArgString("--thinlto-distributor-arg=" + A));
}
}
void tools::addOpenMPRuntimeLibraryPath(const ToolChain &TC,

View File

@ -3187,28 +3187,46 @@ void MachO::addClangTargetOptions(const llvm::opt::ArgList &DriverArgs,
ToolChain::addClangTargetOptions(DriverArgs, CC1Args, DeviceOffloadKind);
// On arm64e, enable pointer authentication (for the return address and
// indirect calls), as well as usage of the intrinsics.
if (getArchName() == "arm64e") {
if (!DriverArgs.hasArg(options::OPT_fptrauth_returns,
options::OPT_fno_ptrauth_returns))
CC1Args.push_back("-fptrauth-returns");
if (!DriverArgs.hasArg(options::OPT_fptrauth_intrinsics,
options::OPT_fno_ptrauth_intrinsics))
CC1Args.push_back("-fptrauth-intrinsics");
// On arm64e, we enable all the features required for the Darwin userspace
// ABI
if (getTriple().isArm64e()) {
// Core platform ABI
if (!DriverArgs.hasArg(options::OPT_fptrauth_calls,
options::OPT_fno_ptrauth_calls))
CC1Args.push_back("-fptrauth-calls");
if (!DriverArgs.hasArg(options::OPT_fptrauth_returns,
options::OPT_fno_ptrauth_returns))
CC1Args.push_back("-fptrauth-returns");
if (!DriverArgs.hasArg(options::OPT_fptrauth_intrinsics,
options::OPT_fno_ptrauth_intrinsics))
CC1Args.push_back("-fptrauth-intrinsics");
if (!DriverArgs.hasArg(options::OPT_fptrauth_indirect_gotos,
options::OPT_fno_ptrauth_indirect_gotos))
CC1Args.push_back("-fptrauth-indirect-gotos");
if (!DriverArgs.hasArg(options::OPT_fptrauth_auth_traps,
options::OPT_fno_ptrauth_auth_traps))
CC1Args.push_back("-fptrauth-auth-traps");
// C++ v-table ABI
if (!DriverArgs.hasArg(
options::OPT_fptrauth_vtable_pointer_address_discrimination,
options::OPT_fno_ptrauth_vtable_pointer_address_discrimination))
CC1Args.push_back("-fptrauth-vtable-pointer-address-discrimination");
if (!DriverArgs.hasArg(
options::OPT_fptrauth_vtable_pointer_type_discrimination,
options::OPT_fno_ptrauth_vtable_pointer_type_discrimination))
CC1Args.push_back("-fptrauth-vtable-pointer-type-discrimination");
// Objective-C ABI
if (!DriverArgs.hasArg(options::OPT_fptrauth_objc_isa,
options::OPT_fno_ptrauth_objc_isa))
CC1Args.push_back("-fptrauth-objc-isa");
if (!DriverArgs.hasArg(options::OPT_fptrauth_objc_class_ro,
options::OPT_fno_ptrauth_objc_class_ro))
CC1Args.push_back("-fptrauth-objc-class-ro");
if (!DriverArgs.hasArg(options::OPT_fptrauth_objc_interface_sel,
options::OPT_fno_ptrauth_objc_interface_sel))
CC1Args.push_back("-fptrauth-objc-interface-sel");
}
}

View File

@ -447,6 +447,7 @@ void Flang::addTargetOptions(const ArgList &Args,
// Add the target features.
switch (TC.getArch()) {
default:
getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);
break;
case llvm::Triple::aarch64:
getTargetFeatures(D, Triple, Args, CmdArgs, /*ForAs*/ false);

View File

@ -85,11 +85,18 @@ void tools::MinGW::Linker::AddLibGCC(const ArgList &Args,
CmdArgs.push_back("-lmoldname");
CmdArgs.push_back("-lmingwex");
for (auto Lib : Args.getAllArgValues(options::OPT_l))
for (auto Lib : Args.getAllArgValues(options::OPT_l)) {
if (StringRef(Lib).starts_with("msvcr") ||
StringRef(Lib).starts_with("ucrt") ||
StringRef(Lib).starts_with("crtdll"))
StringRef(Lib).starts_with("crtdll")) {
std::string CRTLib = (llvm::Twine("-l") + Lib).str();
// Respect the user's chosen crt variant, but still provide it
// again as the last linker argument, because some of the libraries
// we added above may depend on it.
CmdArgs.push_back(Args.MakeArgStringRef(CRTLib));
return;
}
}
CmdArgs.push_back("-lmsvcrt");
}

View File

@ -161,7 +161,7 @@ void openbsd::Linker::ConstructJob(Compilation &C, const JobAction &JA,
if (Nopie || Profiling)
CmdArgs.push_back("-nopie");
if (Triple.isRISCV64()) {
if (Triple.isLoongArch64() || Triple.isRISCV64()) {
CmdArgs.push_back("-X");
if (Args.hasArg(options::OPT_mno_relax))
CmdArgs.push_back("--no-relax");

View File

@ -628,9 +628,16 @@ bool ContinuationIndenter::mustBreak(const LineState &State) {
// name.
!Style.isJavaScript() && Previous.isNot(tok::kw_template) &&
CurrentState.BreakBeforeParameter) {
for (const auto *Tok = &Previous; Tok; Tok = Tok->Previous)
if (Tok->FirstAfterPPLine || Tok->is(TT_LineComment))
for (const auto *Tok = &Previous; Tok; Tok = Tok->Previous) {
if (Tok->is(TT_LineComment))
return false;
if (Tok->is(TT_TemplateCloser)) {
Tok = Tok->MatchingParen;
assert(Tok);
}
if (Tok->FirstAfterPPLine)
return false;
}
return true;
}

View File

@ -727,6 +727,7 @@ template <> struct MappingTraits<FormatStyle::SpaceBeforeParensCustom> {
IO.mapOptional("AfterFunctionDeclarationName",
Spacing.AfterFunctionDeclarationName);
IO.mapOptional("AfterIfMacros", Spacing.AfterIfMacros);
IO.mapOptional("AfterNot", Spacing.AfterNot);
IO.mapOptional("AfterOverloadedOperator", Spacing.AfterOverloadedOperator);
IO.mapOptional("AfterPlacementOperator", Spacing.AfterPlacementOperator);
IO.mapOptional("AfterRequiresInClause", Spacing.AfterRequiresInClause);
@ -1748,7 +1749,6 @@ FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
GoogleStyle.AttributeMacros.push_back("absl_nullable");
GoogleStyle.AttributeMacros.push_back("absl_nullability_unknown");
GoogleStyle.BreakTemplateDeclarations = FormatStyle::BTDS_Yes;
GoogleStyle.DerivePointerAlignment = true;
GoogleStyle.IncludeStyle.IncludeBlocks = tooling::IncludeStyle::IBS_Regroup;
GoogleStyle.IncludeStyle.IncludeCategories = {{"^<ext/.*\\.h>", 2, 0, false},
{"^<.*\\.h>", 1, 0, false},
@ -1857,6 +1857,7 @@ FormatStyle getGoogleStyle(FormatStyle::LanguageKind Language) {
} else if (Language == FormatStyle::LK_ObjC) {
GoogleStyle.AlwaysBreakBeforeMultilineStrings = false;
GoogleStyle.ColumnLimit = 100;
GoogleStyle.DerivePointerAlignment = true;
// "Regroup" doesn't work well for ObjC yet (main header heuristic,
// relationship between ObjC standard library headers and other heades,
// #imports, etc.)

View File

@ -45,15 +45,18 @@ std::pair<tooling::Replacements, unsigned>
IntegerLiteralSeparatorFixer::process(const Environment &Env,
const FormatStyle &Style) {
switch (Style.Language) {
case FormatStyle::LK_Cpp:
case FormatStyle::LK_ObjC:
Separator = '\'';
break;
case FormatStyle::LK_CSharp:
case FormatStyle::LK_Java:
case FormatStyle::LK_JavaScript:
Separator = '_';
break;
case FormatStyle::LK_Cpp:
case FormatStyle::LK_ObjC:
if (Style.Standard >= FormatStyle::LS_Cpp14) {
Separator = '\'';
break;
}
[[fallthrough]];
default:
return {};
}

View File

@ -2590,6 +2590,9 @@ private:
if (!Tok.Previous || Tok.isNot(tok::identifier) || Tok.is(TT_ClassHeadName))
return false;
if (Tok.endsSequence(Keywords.kw_final, TT_ClassHeadName))
return false;
if ((Style.isJavaScript() || Style.isJava()) && Tok.is(Keywords.kw_extends))
return false;
@ -2996,14 +2999,18 @@ private:
const FormatToken *PrevToken = Tok.getPreviousNonComment();
if (!PrevToken)
return TT_UnaryOperator;
if (PrevToken->is(TT_TypeName))
if (PrevToken->isTypeName(LangOpts))
return TT_PointerOrReference;
if (PrevToken->isPlacementOperator() && Tok.is(tok::ampamp))
return TT_BinaryOperator;
const FormatToken *NextToken = Tok.getNextNonComment();
auto *NextToken = Tok.getNextNonComment();
if (!NextToken)
return TT_PointerOrReference;
if (NextToken->is(tok::greater)) {
NextToken->setFinalizedType(TT_TemplateCloser);
return TT_PointerOrReference;
}
if (InTemplateArgument && NextToken->is(tok::kw_noexcept))
return TT_BinaryOperator;
@ -3112,7 +3119,7 @@ private:
// It's more likely that & represents operator& than an uninitialized
// reference.
if (Tok.is(tok::amp) && PrevToken && PrevToken->Tok.isAnyIdentifier() &&
if (Tok.is(tok::amp) && PrevToken->Tok.isAnyIdentifier() &&
IsChainedOperatorAmpOrMember(PrevToken->getPreviousNonComment()) &&
NextToken && NextToken->Tok.isAnyIdentifier()) {
if (auto NextNext = NextToken->getNextNonComment();
@ -5474,7 +5481,8 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
if (Left.TokenText == "!")
return Style.SpaceAfterLogicalNot;
assert(Left.TokenText == "not");
return Right.isOneOf(tok::coloncolon, TT_UnaryOperator);
return Right.isOneOf(tok::coloncolon, TT_UnaryOperator) ||
(Right.is(tok::l_paren) && Style.SpaceBeforeParensOptions.AfterNot);
}
// If the next token is a binary operator or a selector name, we have
@ -6266,7 +6274,8 @@ bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
}
if (Right.is(tok::colon) &&
!Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon)) {
!Right.isOneOf(TT_CtorInitializerColon, TT_InlineASMColon,
TT_BitFieldColon)) {
return false;
}
if (Left.is(tok::colon) && Left.isOneOf(TT_DictLiteral, TT_ObjCMethodExpr)) {

View File

@ -1542,6 +1542,17 @@ void CompilerInvocation::setDefaultPointerAuthOptions(
Discrimination::Constant, InitFiniPointerConstantDiscriminator);
}
Opts.BlockInvocationFunctionPointers =
PointerAuthSchema(Key::ASIA, true, Discrimination::None);
Opts.BlockHelperFunctionPointers =
PointerAuthSchema(Key::ASIA, true, Discrimination::None);
Opts.BlockByrefHelperFunctionPointers =
PointerAuthSchema(Key::ASIA, true, Discrimination::None);
if (LangOpts.PointerAuthBlockDescriptorPointers)
Opts.BlockDescriptorPointers =
PointerAuthSchema(Key::ASDA, true, Discrimination::Constant,
BlockDescriptorConstantDiscriminator);
Opts.ObjCMethodListFunctionPointers =
PointerAuthSchema(Key::ASIA, true, Discrimination::None);
Opts.ObjCMethodListPointer =
@ -3598,6 +3609,8 @@ static void GeneratePointerAuthArgs(const LangOptions &Opts,
GenerateArg(Consumer, OPT_fptrauth_objc_interface_sel);
if (Opts.PointerAuthObjcClassROPointers)
GenerateArg(Consumer, OPT_fptrauth_objc_class_ro);
if (Opts.PointerAuthBlockDescriptorPointers)
GenerateArg(Consumer, OPT_fptrauth_block_descriptor_pointers);
}
static void ParsePointerAuthArgs(LangOptions &Opts, ArgList &Args,
@ -3621,7 +3634,8 @@ static void ParsePointerAuthArgs(LangOptions &Opts, ArgList &Args,
Opts.PointerAuthELFGOT = Args.hasArg(OPT_fptrauth_elf_got);
Opts.AArch64JumpTableHardening =
Args.hasArg(OPT_faarch64_jump_table_hardening);
Opts.PointerAuthBlockDescriptorPointers =
Args.hasArg(OPT_fptrauth_block_descriptor_pointers);
Opts.PointerAuthObjcIsa = Args.hasArg(OPT_fptrauth_objc_isa);
Opts.PointerAuthObjcClassROPointers = Args.hasArg(OPT_fptrauth_objc_class_ro);
Opts.PointerAuthObjcInterfaceSel =

Some files were not shown because too many files have changed in this diff Show More