aarch64: Tweak handling of general SVE permutes [PR121027]
This PR is partly about a code quality regression that was triggered
by g:caa7a99a052929d5970677c5b639e1fa5166e334. That patch taught the
gimple optimisers to fold two VEC_PERM_EXPRs into one, conditional
upon either (a) the original permutations not being "native" operations
or (b) the combined permutation being a "native" operation.
Whether something is a "native" operation is tested by calling
can_vec_perm_const_p with allow_variable_p set to false. This requires
the permutation to be supported directly by TARGET_VECTORIZE_VEC_PERM_CONST,
rather than falling back to the general vec_perm optab.
This exposed a problem with the way that we handled general 2-input
permutations for SVE. Unlike Advanced SIMD, base SVE does not have
an instruction to do general 2-input permutations. We do still implement
the vec_perm optab for SVE, but only when the vector length is known at
compile time. The general expansion is pretty expensive: an AND, a SUB,
two TBLs, and an ORR. It certainly couldn't be considered a "native"
operation.
However, if a VEC_PERM_EXPR has a constant selector, the indices can
be wider than the elements being permuted. This is not true for the
vec_perm optab, where the indices and permuted elements must have the
same precision.
This leads to one case where we cannot leave a general 2-input permutation
to be handled by the vec_perm optab: when permuting bytes on a target
with 2048-bit vectors. In that case, the indices of the elements in
the second vector are in the range [256, 511], which cannot be stored
in a byte index.
TARGET_VECTORIZE_VEC_PERM_CONST therefore has to handle 2-input SVE
permutations for one specific case. Rather than check for that
specific case, the code went ahead and used the vec_perm expansion
whenever it worked. But that undermines the !allow_variable_p
handling in can_vec_perm_const_p; it becomes impossible for
target-independent code to distinguish "native" operations from
the worst-case fallback.
This patch instead limits TARGET_VECTORIZE_VEC_PERM_CONST to the
cases that it has to handle. It fixes the PR for all vector lengths
except 2048 bits.
A better fix would be to introduce some sort of costing mechanism,
which would allow us to reject the new VEC_PERM_EXPR even for
2048-bit targets. But that would be a significant amount of work
and would not be backportable.
gcc/
PR target/121027
* config/aarch64/aarch64.cc (aarch64_evpc_sve_tbl): Punt on 2-input
operations that can be handled by vec_perm.
gcc/testsuite/
PR target/121027
* gcc.target/aarch64/sve/acle/general/perm_1.c: New test.
aarch64: Fix LD1Q and ST1Q failures for big-endian
LD1Q gathers and ST1Q scatters are unusual in that they operate
on 128-bit blocks (effectively VNx1TI). However, we don't have
modes or ACLE types for 128-bit integers, and 128-bit integers
are not the intended use case. Instead, the instructions are
intended to be used in "hybrid VLA" operations, where each 128-bit
block is an Advanced SIMD vector.
The normal SVE modes therefore capture the intended use case better
than VNx1TI would. For example, VNx2DI is effectively N copies
of V2DI, VNx4SI N copies of V4SI, etc.
Since there is only one LD1Q instruction and one ST1Q instruction,
the ACLE support used a single pattern for each, with the loaded or
stored data having mode VNx2DI. The ST1Q pattern was generated by:
where the force_lowpart_subreg bitcast the stored data to VNx2DI.
But such subregs require an element reverse on big-endian targets
(see the comment at the head of aarch64-sve.md), which wasn't the
intention. The code should have used aarch64_sve_reinterpret instead.
which always returns a VNx2DI value, leaving the caller to bitcast
that to the correct mode. That bitcast again uses subregs and has
the same problem as above.
However, for the reasons explained in the comment, using
aarch64_sve_reinterpret does not work well for LD1Q. The patch
instead parameterises the LD1Q based on the required data mode.
gcc/
* config/aarch64/aarch64-sve2.md (aarch64_gather_ld1q): Replace with...
(@aarch64_gather_ld1q<mode>): ...this, parameterizing based on mode.
* config/aarch64/aarch64-sve-builtins-sve2.cc
(svld1q_gather_impl::expand): Update accordingly.
(svst1q_scatter_impl::expand): Use aarch64_sve_reinterpret
instead of force_lowpart_subreg.
testsuite: Add -funwind-tables to sve*/pfalse* tests
The SVE svpfalse folding tests use CFI directives to delimit the
function bodies. That requires -funwind-tables to be enabled,
which is true by default for *-linux-gnu targets, but not for *-elf.
TARGET_VECTORIZE_VEC_PERM_CONST has code to match the SVE2.1
"hybrid VLA" DUPQ, EXTQ, UZPQ{1,2}, and ZIPQ{1,2} instructions.
This matching was conditional on !BYTES_BIG_ENDIAN.
The ACLE code also lowered the associated SVE2.1 intrinsics into
suitable VEC_PERM_EXPRs. This lowering was not conditional on
!BYTES_BIG_ENDIAN.
The mismatch led to lots of ICEs in the ACLE tests on big-endian
targets: we lowered to VEC_PERM_EXPRs that are not supported.
I think the !BYTES_BIG_ENDIAN restriction was unnecessary.
SVE maps the first memory element to the least significant end of
the register for both endiannesses, so no endian correction or lane
number adjustment is necessary.
This is in some ways a bit counterintuitive. ZIPQ1 is conceptually
"apply Advanced SIMD ZIP1 to each 128-bit block" and endianness does
matter when choosing between Advanced SIMD ZIP1 and ZIP2. For example,
the V4SI permute selector { 0, 4, 1, 5 } corresponds to ZIP1 for little-
endian and ZIP2 for big-endian. But the difference between the hybrid
VLA and Advanced SIMD permute selectors is a consequence of the
difference between the SVE and Advanced SIMD element orders.
The same thing applies to ACLE intrinsics. The current lowering of
svzipq1 etc. is correct for both endiannesses. If ACLE code does:
2x svld1_s32 + svzipq1_s32 + svst1_s32
then the byte-for-byte result is the same for both endiannesses.
On big-endian targets, this is different from using the Advanced SIMD
sequence below for each 128-bit block:
depends on endianness, since the quadword gathers and scatters use
Advanced SIMD byte ordering for each 128-bit block. This gather/scatter
sequence behaves in the same way as the Advanced SIMD LDR+ZIP1+STR
sequence for both endiannesses.
Programmers writing ACLE code have to be aware of this difference
if they want to support both endiannesses.
The patch includes some new execution tests to verify the expansion
of the VEC_PERM_EXPRs.
aarch64: Fix endianness of DFmode vector constants
aarch64_simd_valid_imm tries to decompose a constant into a repeating
series of 64 bits, since most Advanced SIMD and SVE immediate forms
require that. (The exceptions are handled first.) It does this by
building up a byte-level register image, lsb first. If the image does
turn out to repeat every 64 bits, it loads the first 64 bits into an
integer.
At this point, endianness has mostly been dealt with. Endianness
applies to transfers between registers and memory, whereas at this
point we're dealing purely with register values.
However, one of things we try is to bitcast the value to a float
and use FMOV. This involves splitting the value into 32-bit chunks
(stored as longs) and passing them to real_from_target. The problem
being fixed by this patch is that, when a value spans multiple 32-bit
chunks, real_from_target expects them to be in memory rather than
register order. Thus index 0 is the most significant chunk if
FLOAT_WORDS_BIG_ENDIAN and the least significant chunk otherwise.
This fixes aarch64/sve/cond_fadd_1.c and various other tests
for aarch64_be-elf.
gcc/
* config/aarch64/aarch64.cc (aarch64_simd_valid_imm): Account
for FLOAT_WORDS_BIG_ENDIAN when building a floating-point value.
When using SVE INDEX to load an Advanced SIMD vector, we need to
take account of the different element ordering for big-endian
targets. For example, when big-endian targets store the V4SI
constant { 0, 1, 2, 3 } in registers, 0 becomes the most
significant element, whereas INDEX always operates from the
least significant element. A big-endian target would therefore
load V4SI { 0, 1, 2, 3 } using:
INDEX Z0.S, #3, #-1
rather than little-endian's:
INDEX Z0.S, #0, #1
While there, I noticed that we would only check the first vector
in a multi-vector SVE constant, which would trigger an ICE if the
other vectors turned out to be invalid. This is pretty difficult to
trigger at the moment, since we only allow single-register modes to be
used as frontend & middle-end vector modes, but it can be seen using
the RTL frontend.
gcc/
* config/aarch64/aarch64.cc (aarch64_sve_index_series_p): New
function, split out from...
(aarch64_simd_valid_imm): ...here. Account for the different
SVE and Advanced SIMD element orders on big-endian targets.
Check each vector in a structure mode.
gcc/testsuite/
* gcc.dg/rtl/aarch64/vec-series-1.c: New test.
* gcc.dg/rtl/aarch64/vec-series-2.c: Likewise.
* gcc.target/aarch64/sve/acle/general/dupq_2.c: Fix expected
output for this big-endian test.
* gcc.target/aarch64/sve/acle/general/dupq_4.c: Likewise.
* gcc.target/aarch64/sve/vec_init_3.c: Restrict to little-endian
targets and add more tests.
* gcc.target/aarch64/sve/vec_init_4.c: New big-endian version
of vec_init_3.c.
While working on a new testcase that uses the RTL frontend,
I hit a bug where a (reg ...) that spans multiple hard registers
had REG_NREGS set to 1. This caused various things to misbehave.
For example, if the (reg ...) in question was used as crtl->return_rtx,
only the first register in the group would be marked as live on exit.
gcc/
* read-rtl-function.cc (function_reader::read_rtx_operand_r): Use
hard_regno_nregs to work out REG_NREGS for hard registers.
aarch64: Fix ZIP1 order in aarch64_expand_vector_init [PR118891]
aarch64_expand_vector_init contains some divide-and-conquer code
that tries to load the odd and even elements into 64-bit registers
and then ZIP them together. On big-endian targets, the even elements
are more significant than the odd elements and so should come second
in the ZIP.
This fixes many execution failures on aarch64_be-elf, including
gcc.c-torture/execute/pr28982a.c.
gcc/
PR target/118891
* config/aarch64/aarch64.cc (aarch64_expand_vector_init): Fix the
ZIP1 operand order for big-endian targets.
aarch64: Fix neon-sve-bridge.c failures for big-endian
Lowpart subregs are generally disallowed on big-endian SVE vector
registers, since the first memory element is stored at the least
significant end of the register, rather than the most significant end.
(See the comment at the head of aarch64-sve.md for details,
and aarch64_modes_compatible_p for the implementation.)
This means that arm_sve_neon_bridge.h needs to use custom define_insns
for big-endian targets, in lieu of using lowpart subregs. However,
one of those define_insns relied on the prohibited lowparts internally,
to convert an Advanced SIMD register to an SVE register. Since the
lowpart is not allowed, the lowpart_subreg would return null, leading
to a later ICE.
The simplest fix seems to be to use %Z instead, to force the Advanced
SIMD register to be written as an SVE register.
gcc/
* config/aarch64/aarch64-sve.md (@aarch64_sve_set_neonq_<mode>):
Use %Z instead of lowpart_subreg. Tweak formatting.
if (SUBREG_P (dst) && SUBREG_BYTE (dst).is_constant ())
{
bit = subreg_lsb (dst).to_constant ();
if (bit >= HOST_BITS_PER_WIDE_INT)
bit = HOST_BITS_PER_WIDE_INT - 1;
dst = SUBREG_REG (dst);
But a constant SUBREG_BYTE doesn't guarantee a constant subreg_lsb.
If the SUBREG_REG is a pair of N-bit registers on a big-endian target,
the most significant end has a SUBREG_BYTE of 0 but a subreg_lsb of N.
This N would then be non-constant for variable-length registers.
The patch fixes gcc.dg/torture/pr120276.c and other failures on
aarch64_be-elf.
gcc/
* ext-dce.cc (ext_dce_process_uses): Apply is_constant directly
to the subreg_lsb.
vect: Fix VEC_WIDEN_PLUS_HI/LO choice for big-endian [PR118891]
In the tree codes and optabs, the "hi" in a vector hi/lo pair means
"most significant" and the "lo" means "least significant", with
sigificance following GCC's normal endian expectations. Thus on
big-endian targets, the hi part handles the first half of the elements
in memory order and the lo part handles the second half.
For tree codes, supportable_widening_operation first chooses hi/lo
pairs based on little-endian order and then uses:
if (BYTES_BIG_ENDIAN && c1 != VEC_WIDEN_MULT_EVEN_EXPR)
std::swap (c1, c2);
to adjust. However, the handling for internal functions was missing
an equivalent fixup. This led to several execution failures in vect.exp
on aarch64_be-elf.
If the hi/lo code fails, the internal function handling goes on to try
even/odd. But I couldn't see anything obvious that would put the even/
odd results back into the right order later, so there might be a latent
bug there too.
gcc/
PR tree-optimization/118891
* tree-vect-stmts.cc (supportable_widening_operation): Swap the
hi and lo internal functions on big-endian targets.
Martin Jambor [Mon, 23 Jun 2025 21:52:20 +0000 (23:52 +0200)]
rust: Silence a clang warning in borrow-checker-diagnostics
When compiling
gcc/rust/checks/errors/borrowck/rust-borrow-checker-diagnostics.cc
with clang, it emits the following warning:
gcc/rust/checks/errors/borrowck/rust-borrow-checker-diagnostics.cc:145:46: warning: non-constant-expression cannot be narrowed from type 'Polonius::Loan' (aka 'unsigned long') to 'uint32_t' (aka 'unsigned int') in initializer list [-Wc++11-narrowing]
I'd hope that for indexing that is never really a problem,
nevertheless if narrowing is taking place, I guess it can be argued it
should be made explicit.
gcc/rust/ChangeLog:
2025-06-23 Martin Jambor <mjambor@suse.cz>
* checks/errors/borrowck/rust-borrow-checker-diagnostics.cc
(BorrowCheckerDiagnostics::get_loan): Type cast loan to uint32_t.
* checks/errors/borrowck/rust-bir-place.h
(IndexVec::size_type): Add.
(IndexVec::MAX_INDEX): Add.
(IndexVec::size): Change the return type to the type of the
internal value used by the index type.
(PlaceDB::lookup_or_add_variable): Use the return value from the
PlaceDB::add_place call.
* checks/errors/borrowck/rust-bir.h
(struct BasicBlockId): Move this definition before the
definition of the struct Function.
Thomas Schwinge [Sat, 19 Apr 2025 13:49:34 +0000 (15:49 +0200)]
Disable parallel testing for 'rust/compile/nr2/compile.exp' [PR119508]
..., using the standard idiom. This '*.exp' file doesn't adhere to the
parallel testing protocol as defined in 'gcc/testsuite/lib/gcc-defs.exp'.
This also restores proper behavior for '*.exp' files executing after (!) this
one, which erroneously caused hundreds or even thousands of individual test
cases get duplicated vs. skipped, randomly, depending on the '-jN' level.
Besides this commit working as a release-branch fix for the
PR, code inspection shows slightly better code for TImode
libgcc functions, and a modified
gcc.c-torture/execute/arith-rand-ll.c (basically s/long
long/__int128 and cutting out the non-128-bit cases) shows a
1.4% improvement. (Coremark code is identical, as
expected.)
Richard Biener [Fri, 18 Jul 2025 07:02:09 +0000 (09:02 +0200)]
tree-optimization/120924 - up --param uninit-max-chain-len
The PR shows that the uninit analysis limits are set too low in
cases we lower switches to ifs as happens on s390x for a linux
kernel TU. This causes false positive uninit diagnostics as we
abort the attempt to prove that a value is initialized on all
paths. The new testcase only would require upping to 9.
PR tree-optimization/120924
* params.opt (uninit-max-chain-len): Up from 8 to 12.
Richard Biener [Mon, 14 Jul 2025 12:09:28 +0000 (14:09 +0200)]
tree-optimization/121059 - fixup loop mask query
When we opportunistically mask an operand of a AND with an already
available loop mask we need to query that set with the correct number
of masks we expect.
PR tree-optimization/121059
* tree-vect-stmts.cc (vectorizable_operation): Query
scalar_cond_masked_set with the correct number of masks.
Richard Biener [Wed, 16 Jul 2025 13:07:58 +0000 (15:07 +0200)]
tree-optimization/121049 - avoid loop masking with even/odd reduction
The following disables loop masking when we are using an even/odd
widening operation in a reduction because the loop mask then aligns
to the wrong elements.
PR tree-optimization/121049
* internal-fn.h (widening_evenodd_fn_p): Declare.
* internal-fn.cc (widening_evenodd_fn_p): New function.
* tree-vect-stmts.cc (vectorizable_conversion): When using
an even/odd widening function disable loop masking.
Richard Biener [Wed, 16 Jul 2025 18:19:44 +0000 (20:19 +0200)]
tree-optimization/121035 - handle stray VN values without expression
When VN iterates we can end up with unreachable inserted expressions
in the expression tables which in turn will not be added to their
value by PREs compute_avail. This will later ICE when we pick
them up and want to generate them. Deal with this by giving up.
PR tree-optimization/121035
* tree-ssa-pre.cc (find_or_generate_expression): Handle
values without expression.
Gaius Mulley [Fri, 18 Jul 2025 07:48:22 +0000 (08:48 +0100)]
[PATCH] [PR modula2/117203] Followup add Delete procedure function
This patch provides GetFileName procedure function for
FIO.File, FileSystem.File and IOChan.ChanId. The
return result from these procedures can be passed into
StringFileSysOp.Unlink to complete the required delete.
gcc/m2/ChangeLog:
PR modula2/117203
* gm2-libs-log/FileSystem.def (GetFileName): New
procedure function.
(WriteString): New procedure.
* gm2-libs-log/FileSystem.mod (GetFileName): New
procedure function.
(WriteString): New procedure.
* gm2-libs/SFIO.def (GetFileName): New procedure function.
* gm2-libs/SFIO.mod (GetFileName): New procedure function.
* gm2-libs-iso/IOChanUtils.def: New file.
* gm2-libs-iso/IOChanUtils.mod: New file.
PR modula2/117203
* gm2/isolib/run/pass/testdelete2.mod: New test.
* gm2/pimlib/logitech/run/pass/testdelete2.mod: New test.
* gm2/pimlib/run/pass/testdelete.mod: New test.
Jakub Jelinek [Fri, 18 Jul 2025 07:20:30 +0000 (09:20 +0200)]
gimple-fold: Fix up big endian _BitInt adjustment [PR121131]
The following testcase ICEs because SCALAR_INT_TYPE_MODE of course
doesn't work for large BITINT_TYPE types which have BLKmode.
native_encode* as well as e.g. r14-8276 use in cases like these
GET_MODE_SIZE (SCALAR_INT_TYPE_MODE ()) and TREE_INT_CST_LOW (TYPE_SIZE_UNIT
()) for the BLKmode ones.
In this case, it wants bits rather than bytes, so I've used
GET_MODE_BITSIZE like before and TYPE_SIZE otherwise.
Furthermore, the patch only computes encoding_size for big endian
targets, for little endian we don't really adjust anything, so there
is no point computing it.
2025-07-18 Jakub Jelinek <jakub@redhat.com>
PR tree-optimization/121131
* gimple-fold.cc (fold_nonarray_ctor_reference): Use
TREE_INT_CST_LOW (TYPE_SIZE ()) instead of
GET_MODE_BITSIZE (SCALAR_INT_TYPE_MODE ()) for BLKmode BITINT_TYPEs.
Don't compute encoding_size at all for little endian targets.
Gaius Mulley [Fri, 18 Jul 2025 07:02:52 +0000 (08:02 +0100)]
[PATCH] [PR modula2/120731] error in Strings.Pos causing sigsegv
This patch corrects the m2log library procedure function
Strings.Pos which incorrectly sliced the wrong component
of the source string. The incorrect slice could cause
a sigsegv if negative slice indices were generated.
Gaius Mulley [Fri, 18 Jul 2025 00:47:40 +0000 (01:47 +0100)]
[PATCH] PR modula2/120673: Mutually dependent types crash the compiler
This patch fixes an ICE which will occur if cyclic dependent types
are used when declaring a variable. This patch detects the
cyclic dependency and issues an error message for each outstanding
component.
gcc/m2/ChangeLog:
PR modula2/120673
* gm2-compiler/M2GCCDeclare.mod (ErrorDepList): New
global variable set containing every errant dependency symbol.
(mystop): Remove.
(EmitCircularDependancyError): Replace with ...
(EmitCircularDependencyError): ... this.
(AssertAllTypesDeclared): Rewrite.
(DoVariableDeclaration): Ditto.
(TypeDependentsDeclared): New procedure function.
(PrepareGCCVarDeclaration): Ditto.
(DeclareVariable): Remove assert.
(DeclareLocalVariable): Ditto.
(Constructor): Initialize ErrorDepList.
* gm2-compiler/M2MetaError.mod (doErrorScopeProc): Rewrite
and ensure that a symbol with a module scope does not lookup
from a definition module.
* gm2-compiler/P2SymBuild.mod (BuildType): Rewrite so that
a synonym type is created using the token refering to the name
on the lhs.
gcc/testsuite/ChangeLog:
PR modula2/120673
* gm2/pim/fail/badmodvar.mod: New test.
* gm2/pim/fail/cyclictypes.mod: New test.
* gm2/pim/fail/cyclictypes2.mod: New test.
* gm2/pim/fail/cyclictypes4.mod: New test.
Gaius Mulley [Thu, 17 Jul 2025 19:41:10 +0000 (20:41 +0100)]
[PATCH] PR modula2/120606: FOR loop ICE if the last expression uses an array
This patch fixes the ICE which occurs if the last expression is an array.
It ensures that the start and end values of the for loop expressions are
dereferenced.
gcc/m2/ChangeLog:
PR modula2/120606
* gm2-compiler/M2Quads.mod (ForLoopLastIterator): Dereference
start and end expressions e1 and e2 respectively.
gcc/testsuite/ChangeLog:
PR modula2/120606
* gm2/pim/pass/forarray.mod: New test.
Gaius Mulley [Thu, 17 Jul 2025 16:51:03 +0000 (17:51 +0100)]
[PATCH] [PR modula2/119650, PR modula2/117203]: WriteString and Delete are missing from base libraries
This patch introduces a Write procedure for an array of char,
the string and char datatype. It uses the m2r10 style of
naming the module on the datatype. This uncovered a bug
in the import handling inside Quadident. It also includes
an Unlink procedure from a new module FileSysOp and a String
interface to this module.
gcc/m2/ChangeLog:
PR modula2/119650
PR modula2/117203
* gm2-compiler/P2Build.bnf (CheckModuleQualident): New
procedure.
(Qualident): Rewrite.
* gm2-compiler/P3Build.bnf (PushTFQualident): New procedure.
(CheckModuleQualident): Ditto.
(Qualident): Rewrite.
* gm2-compiler/PCBuild.bnf (PushTFQualident): New procedure.
(CheckModuleQualident): Ditto.
(Qualident): Rewrite.
* gm2-compiler/PHBuild.bnf (PushTFQualident): New procedure.
(CheckModuleQualident): Ditto.
(Qualident): Rewrite.
* gm2-libs/ARRAYOFCHAR.def: New file.
* gm2-libs/ARRAYOFCHAR.mod: New file.
* gm2-libs/CFileSysOp.def: New file.
* gm2-libs/CHAR.def: New file.
* gm2-libs/CHAR.mod: New file.
* gm2-libs/FileSysOp.def: New file.
* gm2-libs/FileSysOp.mod: New file.
* gm2-libs/String.def: New file.
* gm2-libs/String.mod: New file.
* gm2-libs/StringFileSysOp.def: New file.
* gm2-libs/StringFileSysOp.mod: New file.
libgm2/ChangeLog:
PR modula2/119650
PR modula2/117203
* libm2pim/Makefile.am (M2MODS): Add ARRAYOFCHAR,
CHAR.mod, StringFileSysOp.mod and String.mod.
(M2DEFS): Add ARRAYOFCHAR, CHAR.mod,
StringFileSysOp.mod and String.mod.
(libm2pim_la_SOURCES): Add CFileSysOp.c.
* libm2pim/Makefile.in: Regenerate.
* libm2pim/CFileSysOp.cc: New file.
gcc/testsuite/ChangeLog:
PR modula2/119650
* gm2/iso/fail/CHAR.mod: New test.
* gm2/iso/run/pass/CHAR.mod: New test.
* gm2/iso/run/pass/importself.mod: New test.
* gm2/pimlib/run/pass/testwrite.mod: New test.
* gm2/pimlib/run/pass/testwritechar.mod: New test.
Gaius Mulley [Thu, 17 Jul 2025 12:57:52 +0000 (13:57 +0100)]
[PATCH] PR modula2/120542: Return statement in the main procedure crashes the compiler
The patch checks whether a return statement is allowed. It also checks
to see that a return expression is allowed.
gcc/m2/ChangeLog:
PR modula2/120542
* gm2-compiler/M2Quads.mod (BuildReturnLower): New procedure.
(BuildReturn): Allow return without an expression from
module initialization blocks. Generate an error if an
expression is provided. Call BuildReturnLower if no error
was seen.
gcc/testsuite/ChangeLog:
PR modula2/120542
* gm2/iso/fail/badreturn.mod: New test.
* gm2/iso/fail/badreturn2.mod: New test.
* gm2/iso/pass/modulereturn.mod: New test.
* gm2/iso/pass/modulereturn2.mod: New test.
Gaius Mulley [Wed, 16 Jul 2025 20:17:51 +0000 (21:17 +0100)]
[PATCH] PR modula2/120497: error is generated for good code when returning a pointer var variable
The return type checking needs to skip over the Lvalue part of the VAR
parameter or variable.
gcc/m2/ChangeLog:
PR modula2/120497
* gm2-compiler/M2Range.mod (IsAssignmentCompatible): Remove from
import list.
(FoldTypeReturnFunc): Rewrite to skip the Lvalue of a var
variable.
(CodeTypeReturnFunc): Ditto.
(CodeTypeIndrX): Call AssignmentTypeCompatible rather than
IsAssignmentCompatible.
(FoldTypeIndrX): Ditto.
gcc/testsuite/ChangeLog:
PR modula2/120497
* gm2/pim/pass/ReturnType.mod: New test.
* gm2/pim/pass/ReturnType2.mod: New test.
Gaius Mulley [Wed, 16 Jul 2025 18:33:37 +0000 (19:33 +0100)]
[PATCH] PR modula2/120389 Assigning wrong type to an array causes an ICE
Although cherry picked as described. The cherry pick does not include
the command option (-fm2-strict-type-reason) introduced in:
gcc/m2/gm2-lang.cc, gcc/m2/lang.opt and gcc/doc/gm2.texi from the
original patch.
This patch provides follow on fixes for undetected type violations
which can occur then Lvalues are generated during assignment.
For example array accesses and with statements. The type checker
M2Check.mod has been overhauled and cleaned up.
gcc/m2/ChangeLog:
PR modula2/120389
* gm2-compiler/M2Check.def (AssignmentTypeCompatible): Add new
parameter enableReason.
* gm2-compiler/M2Check.mod (EquivalenceProcedure): New type.
(falseReason2): New procedure function.
(falseReason1): Ditto.
(falseReason0): Ditto.
(checkTypeEquivalence): Rewrite.
(checkUnboundedArray): Ditto.
(checkUnbounded): Ditto.
(checkArrayTypeEquivalence): Ditto.
(checkCharStringTypeEquivalence): Ditto.
(buildError4): Add false reason.
(buildError2): Ditto.
(IsTyped): Use GetDType.
(IsTypeEquivalence): New procedure function.
(checkVarTypeEquivalence): Ditto.
(checkVarEquivalence ): Rewrite.
(checkConstMeta): Ditto.
(checkEnumField): New procedure function.
(checkEnumFieldEquivalence): Ditto.
(checkSubrangeTypeEquivalence): Rewrite.
(checkSystemEquivalence): Ditto.
(checkTypeKindViolation): Ditto.
(doCheckPair): Ditto.
(InitEquivalenceArray): New procedure.
(addEquivalence): Ditto.
(checkProcType): Rewrite.
(deconstruct): Deallocate reason string.
(AssignmentTypeCompatible): Initialize reason and reasonEnable
fields.
(ParameterTypeCompatible): Ditto.
(doExpressionTypeCompatible): Ditto.
* gm2-compiler/M2GenGCC.mod (CodeIndrX) Rewrite.
(CheckBinaryExpressionTypes): Rewrite and simplify now that the
type checker is more robust.
(CheckElementSetTypes): Ditto.
(CodeXIndr): Add new range assignment type check.
* gm2-compiler/M2MetaError.def: Correct comments.
* gm2-compiler/M2Options.def (SetStrictTypeAssignment): New procedure.
(SetStrictTypeReason): Ditto.
* gm2-compiler/M2Options.mod: (SetStrictTypeAssignment): New procedure.
(SetStrictTypeReason): Ditto.
(StrictTypeReason): Initialize.
(StrictTypeAssignment): Ditto.
* gm2-compiler/M2Quads.mod (CheckBreak): Delete.
(BreakQuad): New global variable.
(BreakAtQuad): Delete.
(gdbhook): New procedure.
(BreakWhenQuadCreated): Ditto.
(CheckBreak): Ditto.
(Init): Call BreakWhenQuadCreated and gdbhook.
(doBuildAssignment): Add type assignment range check.
(CheckProcTypeAndProcedure): Only check if the procedure
types differ.
(doIndrX): Add type IndrX range check.
(CheckReturnType): Add range return type check.
* gm2-compiler/M2Range.def (InitTypesIndrXCheck): New procedure
function.
(InitTypesReturnTypeCheck): Ditto.
* gm2-compiler/M2Range.mod (InitTypesIndrXCheck): New procedure
function.
(InitTypesReturnTypeCheck): Ditto.
(HandlerExists): Add new clauses.
(FoldAssignment): Pass extra FALSE parameter to
AssignmentTypeCompatible.
(FoldTypeReturnFunc): New procedure.
(FoldTypeAssign): Ditto.
(FoldTypeIndrX): Ditto.
(CodeTypeAssign): Rewrite.
(CodeTypeIndrX): New procedure.
(CodeTypeReturnFunc): Ditto.
(FoldTypeCheck): Add new case clauses.
(CodeTypeCheck): Ditto.
(FoldRangeCheckLower): Ditto.
(IssueWarning): Ditto.
* gm2-gcc/m2options.h (M2Options_SetStrictTypeAssignment): New
function prototype.
(M2Options_SetStrictTypeReason): Ditto.
gcc/testsuite/ChangeLog:
PR modula2/120389
* gm2/pim/fail/testcharint.mod: New test.
* gm2/pim/fail/testindrx.mod: New test.
* gm2/pim/pass/testxindr.mod: New test.
* gm2/pim/pass/testxindr2.mod: New test.
* gm2/pim/pass/testxindr3.mod: New test.
i386: Decouple AMX-AVX512 from AVX10.2 and imply AVX512F
In ISE058, the AVX10.2 imply is removed from AMX-AVX512. This
leads to re-consideration on the imply for AMX-AVX512.
Since it is using zmm register and using zmm register only, we
need to at least imply AVX512F. AVX512VL is not needed.
On the other hand, if we imply AVX10.1 for AMX-AVX512, it will
cause -mno-avx10.1 disabling AMX-AVX512. This would be a surprise
for users.
Based on the two reasons above, the patch is decoupling AMX-AVX512
from AVX10.2 and imply AVX512F.
gcc/ChangeLog:
* common/config/i386/i386-common.cc
(OPTION_MASK_ISA2_AMX_AVX512_SET): Do not set AVX10.2.
(OPTION_MASK_ISA2_AVX10_2_UNSET): Remove AMX-AVX512 unset.
(OPTION_MASK_ISA2_AVX512F_UNSET): Unset AMX-AVX512.
(ix86_handle_option): Imply AVX512F for AMX-AVX512.
gcc/testsuite/ChangeLog:
* gcc.target/i386/amxavx512-cvtrowd2ps-2.c: Add -mavx512fp16 to
use FP16 related intrins for convert.
* gcc.target/i386/amxavx512-cvtrowps2bf16-2.c: Ditto.
* gcc.target/i386/amxavx512-cvtrowps2ph-2.c: Ditto.
* gcc.target/i386/amxavx512-movrow-2.c: Ditto.
Gaius Mulley [Tue, 15 Jul 2025 18:38:04 +0000 (19:38 +0100)]
[PATCH] PR modula2/120389 ICE if assigning a constant char to an integer array
This patch fixes an ICE which occurs if a constant char is assigned
into an integer array. The fix it to introduce type checking in
M2GenGCC.mod:CodeXIndr.
gcc/m2/ChangeLog:
PR modula2/120389
* gm2-compiler/M2GenGCC.mod (CodeXIndr): Check to see that
the type of left is assignment compatible with the type of
right.
gcc/testsuite/ChangeLog:
PR modula2/120389
* gm2/iso/fail/badarray3.mod: New test.
openmp, fortran: Fix ICE when the procedure name cannot be found in declare variant directives [PR104428]
The result of searching for the procedure name symbol should be checked in
case the symbol cannot be found to avoid a null dereference.
gcc/fortran/
PR fortran/104428
* trans-openmp.cc (gfc_trans_omp_declare_variant): Check that proc_st
is non-NULL before dereferencing. Add line number to error message.
Fortran: Ensure finalizers are created correctly [PR120637]
Finalize_component freeed an expression that it used to remember which
components in which context it had finalized already. While it makes
sense to free the copy of the expression, if it is unused, it causes
issues, when comparing to a non existent expression. This is now
detected by returning true, when the expression has been used.
PR fortran/120637
gcc/fortran/ChangeLog:
* class.cc (finalize_component): Return true, when a finalizable
component was detect and do not free it.
Andrew Pinski [Sun, 6 Jul 2025 17:20:26 +0000 (10:20 -0700)]
crc: Error out on non-constant poly arguments for the crc builtins [PR120709]
These builtins requires a constant integer for the third argument but currently
there is assert rather than error. This fixes that and updates the documentation too.
Uses the same terms as was being used for the __builtin_prefetch arguments.
Bootstrapped and tested on x86_64-linux-gnu.
PR middle-end/120709
gcc/ChangeLog:
* builtins.cc (expand_builtin_crc_table_based): Error out
instead of asserting the 3rd argument is an integer constant.
* internal-fn.cc (expand_crc_optab_fn): Likewise.
* doc/extend.texi (crc): Document requirement of the poly argument
being a constant.
aarch64: PR target/120999: Adjust operands for movprfx alternative of NBSL implementation of NOR
While the SVE2 NBSL instruction accepts MOVPRFX to add more flexibility
due to its tied operands, the destination of the movprfx cannot be also
a source operand. But the offending pattern in aarch64-sve2.md tries
to do exactly that for the "=?&w,w,w" alternative and gas warns for the
attached testcase.
This patch adjusts that alternative to avoid taking operand 0 as an input
in the NBSL again.
So for the testcase in the patch we now generate:
nor_z:
movprfx z0, z1
nbsl z0.d, z0.d, z2.d, z1.d
ret
instead of the previous:
nor_z:
movprfx z0, z1
nbsl z0.d, z0.d, z2.d, z0.d
ret
which generated a gas warning.
Bootstrapped and tested on aarch64-none-linux-gnu.
Richard Earnshaw [Mon, 14 Apr 2025 15:41:16 +0000 (16:41 +0100)]
aarch64: Fix up commutative and early-clobber markers on compact insns
For constraints there are operand modifiers and constraint qualifiers.
Operand modifiers apply to all alternatives and must appear, in
traditional syntax before the first alternative. Constraint
qualifiers, on the other hand must appear in each alternative to which
they apply.
There's no easy way to validate the distinction in the traditional md
format, but when using the new compact format we can enforce some
semantic checking of these characters to avoid some potentially
surprising code generation.
Fortunately, all of these errors are benign, but the two misplaced
early-clobber markers were quite suspicious at first sight - it's only
by luck that the second alternative does not need an early-clobber.
The syntax checking will be added in the following patch, but first of
all, fix up the errors in aarch64.md.
Jeff Law [Mon, 30 Jun 2025 20:38:33 +0000 (14:38 -0600)]
[committed] [PR rtl-optimization/120242] Fix SUBREG_PROMOTED_VAR_P after ext-dce's actions
I've gone back and forth of these problems multiple times. We have two passes,
ext-dce and combine which eliminate extensions using totally different
mechanisms.
ext-dce looks for cases where the state of upper bits in an object aren't
observable and if they aren't observable, then eliminates extensions which set
those bits.
combine looks for cases where we know the state of the upper bits and can prove
an extension is just setting those bits to their prior value. Combine also
looks for cases where the precise extension isn't really important, just the
knowledge that the upper bits are zero or sign extended from a narrower mode
is needed.
Combine relies heavily on the SUBREG_PROMOTED_VAR state to do its job. If the
actions of ext-dce (or any other pass for that matter) make
SUBREG_PROMOTED_VAR's state inconsistent with combine's expectations, then
combine can end up generating incorrect code.
--
When ext-dce eliminates an extension and turns it into a subreg copy (without
any known SUBREG_PROMOTED_VAR state). Since we can no longer guarantee the
destination object has any known extension state, we scurry around and wipe
SUBREG_PROMOTED_VAR state for the destination object.
That's fine and dandy, but ultimately insufficient. Consider if the
destination of the optimized extension was used as a source in a simple copy
insn. Furthermore assume that the destination of that copy is used within a
SUBREG expression with SUBREG_PROMOTED_VAR set. ext-dce's actions have
clobbered the SUBREG_PROMOTED_VAR state on the destination of that copy, albeit
indirectly.
This patch addresses this problem by taking the set of pseudos directly
impacted by ext-dce's actions and expands that set by building a transitive
closure for pseudos connected via copies. We then scurry around finding
SUBREG_PROMOTED_VAR state to wipe for everything in that expanded set of
pseudos. Voila, everything just works.
--
The other approach here would be to further expand the liveness sets inside
ext-dce. That's a simpler path forward, but ultimately regresses the quality
of codes we do care about.
One good piece of news is that with the transitive closure bits in place, we
can eliminate a bit of the live set expansion we had in place for
SUBREG_PROMOTED_VAR objects.
--
So let's take one case of the 5 that have been reported.
Combine will do its thing on insns 30/31. Essentially the sign extension is
not necessary in this context, assuming the promoted subreg status in insn 30
-- the equality test doesn't really care about the kind of extension, just
knowing the value is extended is enough to safely elide the extension.
And now we've come to the crux the problem. That promotion state needs to be
adjusted. The new ext-dce code will see that copy at insn 26 and add (reg 144)
to the set of registers that need promotion state wiped. And everything is
happy after that.
The other cases are similar in nature.
--
This has been bootstrapped and regression tested on x86_64 and aarch64.
Variants have bootstrapped & regression tested on several other platforms and
it's survived testing on the crosses as well.
* ext-dce.cc (ext_dce_process_uses): Remove some cases where we
unnecessarily expanded live sets for promoted subregs.
(expand_changed_pseudos): New function.
(reset_subreg_promoted_p): Use it.
RISC-V: prefetch: fix LRA failing to allocate reg [PR118241]
prefetch was recently fixed/tightened (with Q reg constraint) to only
support right address patterns (REG or REG+D with lower 5 bits clear).
However in some cases that's too restrictive for LRA and it fails to
allocate a reg resulting in following ICE...
Jeff Law [Sat, 21 Jun 2025 14:24:58 +0000 (08:24 -0600)]
[RISC-V][PR target/118241] Fix data prefetch predicate/constraint for RISC-V
The RISC-V prefetch support is broken in a few ways. This addresses the data
side prefetch problems. I'd mistakenly thought this BZ was a prefetch.i
related (which has deeper problems).
The basic problem is we were accepting any valid address when in fact there are
restrictions. This patch more precisely defines the predicate such that we
allow
REG
REG+D
Where D must have the low 5 bits clear. Note that absolute addresses fall into
the REG+D form using the x0 for the register operand since it always has the
value zero. The test verifies REG, REG+D, ABS addressing modes that are valid
as well as REG+D and ABS which must be reloaded into a REG because the
displacement has low bits set.
An earlier version of this patch has gone through testing in my tester on rv32
and rv64. Obviously I'll wait for pre-commit CI to do its thing before moving
forward.
This is a good backport candidate after simmering on the trunk for a bit.
PR target/118241
gcc/
* config/riscv/predicates.md (prefetch_operand): New predicate.
* config/riscv/constraints.md (Q): New constraint.
* config/riscv/riscv.md (prefetch): Use new predicate and constraint.
(riscv_prefetchi_<mode>): Similarly.
gcc/testsuite/
* gcc.target/riscv/pr118241.c: New test.
Eric Botcazou [Mon, 14 Jul 2025 10:11:44 +0000 (12:11 +0200)]
Ada: Add missing guard before accessing the Underlying_Record_View field
It is necessary when GNAT extensions are enabled (-gnatX switch).
gcc/ada/
PR ada/121056
* sem_ch4.adb (Try_Object_Operation.Try_Primitive_Operation): Add
test on Is_Record_Type before accessing Underlying_Record_View.
gcc/testsuite/
* gnat.dg/deref4.adb: New test.
* gnat.dg/deref4_pkg.ads: New helper.
H.J. Lu [Thu, 3 Jul 2025 02:54:39 +0000 (10:54 +0800)]
x86-64: Add RDI clobber to 64-bit dynamic TLS patterns
*tls_global_dynamic_64_largepic, *tls_local_dynamic_64_<mode> and
*tls_local_dynamic_base_64_largepic use RDI as the __tls_get_addr
argument. Add RDI clobber to these patterns to show it.
gcc/
PR target/120908
* config/i386/i386.cc (legitimize_tls_address): Pass RDI to
gen_tls_local_dynamic_64.
* config/i386/i386.md (*tls_global_dynamic_64_largepic): Add
RDI clobber and use it to generate LEA.
(*tls_local_dynamic_64_<mode>): Likewise.
(*tls_local_dynamic_base_64_largepic): Likewise.
(@tls_local_dynamic_64_<mode>): Add a clobber.
gcc/testsuite/
PR target/120908
* gcc.target/i386/pr120908.c: New test.
H.J. Lu [Tue, 1 Jul 2025 09:17:06 +0000 (17:17 +0800)]
x86-64: Add RDI clobber to tls_global_dynamic_64 patterns
*tls_global_dynamic_64_<mode> uses RDI as the __tls_get_addr argument.
Add RDI clobber to tls_global_dynamic_64 patterns to show it.
PR target/120908
* config/i386/i386.cc (legitimize_tls_address): Pass RDI to
gen_tls_global_dynamic_64.
* config/i386/i386.md (*tls_global_dynamic_64_<mode>): Add RDI
clobber and use it to generate LEA.
(@tls_global_dynamic_64_<mode>): Add a clobber.
i386: Remove KEYLOCKER related feature since Panther Lake and Clearwater Forest
According to July 2025 SDM, Key locker will no longer be supported on
hardware 2025 onwards. This means for Panther Lake and Clearwater Forest,
the feature will not be enabled. Remove them from those two platforms.
[PATCH] [RISC-V] Fix shift type for RVV interleaved stepped patterns [PR120356]
It corrects the shift type of interleaved stepped patterns for const vector
expanding in LRA. The shift instruction was initially LSHIFTRT, and it seems
still should be the same type for both LRA and other cases.
PR target/120356
gcc/ChangeLog:
* config/riscv/riscv-v.cc
(expand_const_vector_interleaved_stepped_npatterns):
Fix ASHIFT to LSHIFTRT insn.
gcc/testsuite/ChangeLog:
* gcc.target/riscv/rvv/autovec/pr120356.c: New test.
Jakub Jelinek [Fri, 11 Jul 2025 11:43:58 +0000 (13:43 +0200)]
testsuite: Add testcase for already fixed PR [PR120954]
This was a regression introduced by r16-1893 (and its backports) for C++,
though for C it had false positive warning for years. Fixed by r16-2000
(and its backports).
2025-07-11 Jakub Jelinek <jakub@redhat.com>
PR c++/120954
* c-c++-common/Warray-bounds-11.c: New test.
Jakub Jelinek [Fri, 11 Jul 2025 10:09:44 +0000 (12:09 +0200)]
ipa: Disallow signature changes in fun->has_musttail functions [PR121023]
As the following testcase shows e.g. on ia32, letting IPA opts change
signature of functions which have [[{gnu,clang}::musttail]] calls
can turn programs that would be compiled normally into something
that is rejected because the caller has fewer argument stack slots
than the function being tail called.
The following patch prevents signature changes for such functions.
It is perhaps too big hammer in some cases, but it might be hard
to try to figure out what signature changes are still acceptable and which
are not at IPA time.
2025-07-11 Jakub Jelinek <jakub@redhat.com>
Martin Jambor <mjambor@suse.cz>
Jakub Jelinek [Thu, 10 Jul 2025 21:47:42 +0000 (23:47 +0200)]
c++: Fix up final handling in C++98 [PR120628]
The following patch is on top of the
https://gcc.gnu.org/pipermail/gcc-patches/2025-June/686210.html
patch which stopped treating override as conditional keyword in
class properties.
This PR mentions another problem; we emit a bogus warning on code like
struct C {}; struct C final = {};
in C++98. In this case we parse final as conditional keyword in C++
(including pedwarn) but the caller then immediately aborts the tentative
parse because it isn't followed by { nor (in some cases) : .
I think we certainly shouldn't pedwarn on it, but I think we even shouldn't
warn for it say for -Wc++11-compat, because we don't actually treat the
identifier as conditional keyword even in C++11 and later.
The patch only does this if final is the only class property conditional
keyword, if one uses
struct S __final final __final = {};
one gets the warning and duplicate diagnostics and later parsing errors.
2025-07-10 Jakub Jelinek <jakub@redhat.com>
PR c++/120628
* parser.cc (cp_parser_elaborated_type_specifier): Use
cp_parser_nth_token_starts_class_definition_p with extra argument 1
instead of cp_parser_next_token_starts_class_definition_p.
(cp_parser_class_property_specifier_seq_opt): For final conditional
keyword in C++98 check if the token after it isn't
cp_parser_nth_token_starts_class_definition_p nor CPP_NAME and in
that case break without consuming it nor warning.
(cp_parser_class_head): Use
cp_parser_nth_token_starts_class_definition_p with extra argument 1
instead of cp_parser_next_token_starts_class_definition_p.
(cp_parser_next_token_starts_class_definition_p): Renamed to ...
(cp_parser_nth_token_starts_class_definition_p): ... this. Add N
argument. Use cp_lexer_peek_nth_token instead of cp_lexer_peek_token.
* g++.dg/cpp0x/final1.C: New test.
* g++.dg/cpp0x/final2.C: New test.
* g++.dg/cpp0x/override6.C: New test.
Jakub Jelinek [Thu, 10 Jul 2025 21:41:56 +0000 (23:41 +0200)]
c++: Don't incorrectly reject override after class head name [PR120569]
While the
https://www.open-std.org/jtc1/sc22/wg21/docs/papers/2025/p2786r13.html#c03-compatibility-changes-for-annex-c-diff.cpp03.dcl.dcl
hunk dropped because
struct C {}; struct C final {};
is actually not valid C++98 (which didn't have list initialization), we
actually also reject
struct D {}; struct D override {};
and that IMHO is valid all the way from C++11 onwards.
Especially in the light of P2786R13 adding new contextual keywords, I think
it is better to use a separate routine for parsing the
class-virt-specifier-seq (in C++11, there was export next to final),
class-virt-specifier (in C++14 to C++23) and
class-property-specifier-seq (in C++26) instead of using the same function
for virt-specifier-seq and class-property-specifier-seq.
2025-07-10 Jakub Jelinek <jakub@redhat.com>
PR c++/120569
* parser.cc (cp_parser_class_property_specifier_seq_opt): New
function.
(cp_parser_class_head): Use it instead of
cp_parser_property_specifier_seq_opt. Don't diagnose
VIRT_SPEC_OVERRIDE here. Formatting fix.
* g++.dg/cpp0x/override2.C: Expect different diagnostics with
override.
* g++.dg/cpp0x/override5.C: New test.
Jakub Jelinek [Fri, 4 Jul 2025 05:50:12 +0000 (07:50 +0200)]
c-family: Tweak ptr +- (expr +- cst) FE optimization [PR120837]
The following testcase is miscompiled with -fsanitize=undefined but we
introduce UB into the IL even without that flag.
The optimization ptr +- (expr +- cst) when expr/cst have undefined
overflow into (ptr +- cst) +- expr is sometimes simply not valid,
without careful analysis on what ptr points to we don't know if it
is valid to do (ptr +- cst) pointer arithmetics.
E.g. on the testcase, ptr points to start of an array (actually
conditionally one or another) and cst is -1, so ptr - 1 is invalid
pointer arithmetics, while ptr + (expr - 1) can be valid if expr
is at runtime always > 1 and smaller than size of the array ptr points
to + 1.
Unfortunately, removing this 1992-ish optimization altogether causes
FAIL: c-c++-common/restrict-2.c -Wc++-compat scan-tree-dump-times lim2 "Moving statement" 11
FAIL: gcc.dg/tree-ssa/copy-headers-5.c scan-tree-dump ch2 "is now do-while loop"
FAIL: gcc.dg/tree-ssa/copy-headers-5.c scan-tree-dump-times ch2 " if " 3
FAIL: gcc.dg/vect/pr57558-2.c scan-tree-dump vect "vectorized 1 loops"
FAIL: gcc.dg/vect/pr57558-2.c -flto -ffat-lto-objects scan-tree-dump vect "vectorized 1 loops"
regressions (restrict-2.c also for C++ in all std modes). I've been thinking
about some match.pd optimization for signed integer addition/subtraction of
constant followed by widening integral conversion followed by multiplication
or left shift, but that wouldn't help 32-bit arches.
So, instead at least for now, the following patch keeps doing the
optimization, just doesn't perform it in pointer arithmetics.
pointer_int_sum itself actually adds the multiplication by size_exp,
so ptr + expr is turned into ptr p+ expr * size_exp,
so this patch will try to optimize
ptr + (expr +- cst)
into
ptr p+ ((sizetype)expr * size_exp +- (sizetype)cst * size_exp)
and
ptr - (expr +- cst)
into
ptr p+ -((sizetype)expr * size_exp +- (sizetype)cst * size_exp)
2025-07-04 Jakub Jelinek <jakub@redhat.com>
PR c/120837
* c-common.cc (pointer_int_sum): Rewrite the intop PLUS_EXPR or
MINUS_EXPR optimization into extension of both intop operands,
their separate multiplication and then addition/subtraction followed
by rest of pointer_int_sum handling after the multiplication.
Jonathan Wakely [Tue, 8 Jul 2025 09:48:21 +0000 (10:48 +0100)]
libstdc++: Fix __uninitialized_default for constexpr case [PR119754]
We should not use the std::fill optimization for trivial types during
constant evaluation, because we need to begin the lifetime of all
objects, even trivially default constructible ones.
This fixes a bug that Clang diagnosed:
include/c++/16.0.0/bits/stl_algobase.h:925:11: note: assignment to object outside its lifetime is not allowed in a constant expression
925 | *__first = __val;
| ~~~~~~~~~^~~~~~~
I initially just added the #ifdef __cpp_lib_is_constant_evaluated check,
but that gave warnings with GCC because the function isn't constexpr
until C++26. So then I tried checking __glibcxx_raw_memory_algorithms
for the value indicating constexpr uninitialized_value_construct, but
that macro depends on __cpp_constexpr >= 202406 and Clang 19 doesn't
support constexpr placement new, so doesn't define it.
So I decided to just change __uninitialized_default to use
_GLIBCXX20_CONSTEXPR which is consistent with __uninitialized_default_n
(which needs to be constexpr because it's used by std::vector). We don't
currently need to use __uninitialized_default in constexpr contexts for
C++20 code, but we might find uses for it, so now it would be possible.
libstdc++-v3/ChangeLog:
PR libstdc++/119754
* include/bits/stl_uninitialized.h (__uninitialized_default):
Do not use optimized implementation for constexpr case. Use
_GLIBCXX20_CONSTEXPR instead of _GLIBCXX26_CONSTEXPR.
Jonathan Wakely [Tue, 8 Jul 2025 13:56:39 +0000 (14:56 +0100)]
libstdc++: Do not use list-initialization in std::span members [PR120997]
As the bug report shows, for span<const bool> the return statements of
the form `return {data(), count};` will use the new C++26 constructor,
span(initializer_list<element_type>).
Although the conversions from data() to bool and count to bool are
narrowing and should be ill-formed, in system headers the narrowing
diagnostics are suppressed. In any case, even if the compiler diagnosed
them as ill-formed, we still don't want the initializer_list constructor
to be used. We want to use the span(element_type*, size_t) constructor
instead.
Replace the braced-init-list uses with S(data(), count) where S is the
correct return type. We need to make similar changes in the C++26
working draft, which will be taken care of via an LWG issue.
libstdc++-v3/ChangeLog:
PR libstdc++/120997
* include/std/span (span::first, span::last, span::subspan): Do
not use braced-init-list for return statements.
* testsuite/23_containers/span/120997.cc: New test.
Jonathan Wakely [Fri, 4 Jul 2025 15:44:13 +0000 (16:44 +0100)]
libstdc++: Ensure pool resources meet alignment requirements [PR118681]
For allocations with size > alignment and size % alignment != 0 we were
sometimes returning pointers that did not meet the requested aligment.
For example, allocate(24, 16) would select the pool for 24-byte objects
and the second allocation from that pool (at offset 24 bytes into the
pool) is only 8-byte aligned not 16-byte aligned.
The pool resources need to round up the requested allocation size to a
multiple of the alignment, so that the selected pool will always return
allocations that meet the alignment requirement.
This backport includes the fixes for the bootstrap error and the tests.
libstdc++-v3/ChangeLog:
PR libstdc++/118681
* src/c++17/memory_resource.cc (choose_block_size): New
function.
(synchronized_pool_resource::do_allocate): Use choose_block_size
to determine appropriate block size.
(synchronized_pool_resource::do_deallocate): Likewise
(unsynchronized_pool_resource::do_allocate): Likewise.
(unsynchronized_pool_resource::do_deallocate): Likewise
* testsuite/20_util/synchronized_pool_resource/118681.cc: New
test.
* testsuite/20_util/unsynchronized_pool_resource/118681.cc: New
test.
Thomas Schwinge [Wed, 9 Jul 2025 08:06:39 +0000 (10:06 +0200)]
Fix 'main' function in 'gcc.dg/builtin-dynamic-object-size-pr120780.c'
Fix-up for commit 72e85d46472716e670cbe6e967109473b8d12d38
"tree-optimization/120780: Support object size for containing objects".
'size_t sz' is unused here, and GCC/nvptx doesn't accept this:
spawn -ignore SIGHUP [...]/nvptx-none-run ./builtin-dynamic-object-size-pr120780.exe
error : Prototype doesn't match for 'main' in 'input file 1 at offset 1924', first defined in 'input file 1 at offset 1924'
nvptx-run: cuLinkAddData failed: unknown error (CUDA_ERROR_UNKNOWN, 999)
FAIL: gcc.dg/builtin-dynamic-object-size-pr120780.c execution test
tree-optimization/120780: Support object size for containing objects
MEM_REF cast of a subobject to its containing object has negative
offsets, which objsz sees as an invalid access. Support this use case
by peeking into the structure to validate that the containing object
indeed contains a type of the subobject at that offset and if present,
adjust the wholesize for the object to allow the negative offset.
Kyrylo Tkachov [Mon, 2 Jun 2025 14:08:12 +0000 (07:08 -0700)]
aarch64: Add support for NVIDIA GB10
This adds support for -mcpu=gb10. This is a big.LITTLE configuration
involving Cortex-X925 and Cortex-A725 cores. The appropriate MIDR numbers
are added to detect them in -mcpu=native. We did not add an
-mcpu=cortex-x925.cortex-a725 option because GB10 does include the crypto
instructions which we want on by default, and the current convention is to not
enable such extensions for Arm Cortex cores in -mcpu where they are optional
in the IP.
Bootstrapped and tested on aarch64-none-linux-gnu.
Remove the checks on coranks conformability in expressions,
because there is nothing in the standard about it. When a coarray
has no coindexes it it treated like a non-coarray, when it has
a full-corank coindex its result is a regular array. So nothing
to check for corank conformability.
PR fortran/120843
gcc/fortran/ChangeLog:
* resolve.cc (resolve_operator): Remove conformability check,
because it is not in the standard.
gcc/testsuite/ChangeLog:
* gfortran.dg/coarray/coindexed_6.f90: Enhance test to have
coarray components covered.
Richard Biener [Mon, 7 Jul 2025 13:13:38 +0000 (15:13 +0200)]
tree-optimization/120358 - bogus PTA with structure access
When we compute the constraint for something like
MEM[(const struct QStringView &)&tok2 + 32] we go and compute
what (const struct QStringView &)&tok2 + 32 points to and then
add subvariables to its dereference that possibly fall in the
range of the access according to the original refs size. In
doing that we disregarded that the subvariable the starting
address points to might not be aligned to it and thus the
access might start at any point within that variable. The following
conservatively adjusts the pruning of adjacent sub-variables to
honor this.
PR tree-optimization/120358
* tree-ssa-structalias.cc (get_constraint_for_1): Adjust
pruning of sub-variables according to the imprecise
known start offset.
The vectorizer tracks alignment of datarefs with dr_aligned
and dr_unaligned_supported but that's aligned with respect to
the target alignment which can be less aligned than the mode
used for the access. The following fixes this discrepancy
for vectorizing loads and stores. The issue is visible for
aarch64 SVE and risc-v where VLA vector modes have larger than
element alignment but the target handles element alignment
just fine.
Richard Biener [Mon, 7 Jul 2025 07:56:50 +0000 (09:56 +0200)]
tree-optimization/120817 - bogus DSE of .MASK_STORE
DSE used ao_ref_init_from_ptr_and_size for .MASK_STORE but
alias-analysis will use the specified size to disambiguate
against smaller objects. For .MASK_STORE we instead have to
make the access size unspecified but we can still constrain
the access extent based on the maximum size possible.
PR tree-optimization/120817
* tree-ssa-dse.cc (initialize_ao_ref_for_dse): Use
ao_ref_init_from_ptr_and_range with unknown size for
.MASK_STORE and .MASK_LEN_STORE.
Richard Biener [Thu, 3 Jul 2025 12:39:22 +0000 (14:39 +0200)]
tree-optimization/120927 - 510.parest_r segfault with masked epilog
The following fixes bad alignment computaton for epilog vectorization
when as in this case for 510.parest_r and masked epilog vectorization
with AVX512 we end up choosing AVX to vectorize the main loop and
masked AVX512 (sic!) to vectorize the epilog. In that case alignment
analysis for the epilog tries to force alignment of the base to 64,
but that cannot possibly help the epilog when the main loop had used
a vector mode with smaller alignment requirement.
There's another issue, that the check whether the step preserves
alignment needs to consider possibly previously involved VFs
(here, the main loops smaller VF) as well.
These might not be the only case with problems for such a mode mix
but at least there it seems wise to never use DR alignment forcing
when analyzing an epilog.
We get to chose this mode setup because the iteration over epilog
modes doesn't prevent this, the maybe_ge (cached_vf_per_mode[0],
first_vinfo_vf) skip is conditional on !supports_partial_vectors
and it is also conditional on having a cached VF. Further nothing
in vect_analyze_loop_1 rejects this setup - it might be conceivable
that a target can do masking only for larger modes. There is a
second reason we end up with this mode setup, which is that
vect_need_peeling_or_partial_vectors_p says we do not need
peeling or partial vectors when analyzing the main loop with
AVX512 (if it would say so we'd have chosen a masked AVX512
epilog-only vectorization). It does that because it looks at
LOOP_VINFO_COST_MODEL_THRESHOLD (which is not yet computed, so
always zero at this point), and compares max_niter (5) against
the VF (8), but not with equality as the comment says but with
greater. This also needs looking at, PR120939.
PR tree-optimization/120927
* tree-vect-data-refs.cc (vect_compute_data_ref_alignment):
Do not force a DRs base alignment when analyzing an
epilog loop. Check whether the step preserves alignment
for all VFs possibly involved sofar.
* gcc.dg/vect/vect-pr120927.c: New testcase.
* gcc.dg/vect/vect-pr120927-2.c: Likewise.
Fortran: Ensure arguments in coarray call get unique components in add_data [PR120847]
PR fortran/120847
gcc/fortran/ChangeLog:
* coarray.cc (check_add_new_comp_handle_array): Make the count
of components static to be able to create more than one. Create
an array component only for array expressions.
Fortran: Fix non-conformable corank on this_image ref [PR120843]
PR fortran/120843
gcc/fortran/ChangeLog:
* resolve.cc (resolve_operator): Report inconsistent coranks
only when not referencing this_image.
(gfc_op_rank_conformable): Treat coranks as inconformable only
when a coindex other then implicit this_image is used.