664 Commits

Author SHA1 Message Date
Florian Hahn
2d9e452ab0
[LoopUnroll] Introduce parallel reduction phis when unrolling. (#149470)
When partially or runtime unrolling loops with reductions, currently the
reductions are performed in-order in the loop, negating most benefits
from unrolling such loops.

This patch extends unrolling code-gen to keep a parallel reduction phi
per unrolled iteration and combining the final result after the loop.
For out-of-order CPUs, this allows executing mutliple reduction chains
in parallel.

For now, the initial transformation is restricted to cases where we
unroll a small number of iterations (hard-coded to 4, but should maybe
be capped by TTI depending on the execution units), to avoid introducing
an excessive amount of parallel phis.

It also requires single block loops for now, where the unrolled
iterations are known to not exit the loop (either due to runtime
unrolling or partial unrolling). This ensures that the unrolled loop
will have a single basic block, with a single exit block where we can
place the final reduction value computation.

The initial implementation also only supports parallelizing loops with a
single reduction and only integer reductions. Those restrictions are
just to keep the initial implementation simpler, and can easily be
lifted as follow-ups.

With corresponding TTI to the AArch64 unrolling preferences which I will
also share soon, this triggers in ~300 loops across a wide range of
workloads, including LLVM itself, ffmgep, av1aom, sqlite, blender,
brotli, zstd and more.

PR: https://github.com/llvm/llvm-project/pull/149470
2025-09-04 20:54:09 +01:00
Ryotaro Kasuga
2330fd2f73
[LoopPeel] Add new option to peeling loops to convert PHI into IV (#121104)
LoopPeel currently considers PHI nodes that become loop invariants
through peeling. However, in some cases, peeling transforms PHI nodes
into induction variables (IVs), potentially enabling further
optimizations such as loop vectorization. For example:

```c
// TSVC s292
int im = N-1;
for (int i=0; i<N; i++) {
  a[i] = b[i] + b[im];
  im = i;
}
```

In this case, peeling one iteration converts `im` into an IV, allowing
it to be handled by the loop vectorizer.

This patch adds a new feature to peel loops when to convert PHIs into
IVs. At the moment this feature is disabled by default.

Enabling it allows to vectorize the above example. I have measured on
neoverse-v2 and observed a speedup of more than 60% (options: `-O3
-ffast-math -mcpu=neoverse-v2 -mllvm -enable-peeling-for-iv`).

This PR is taken over from #94900
Related #81851
2025-08-20 13:44:56 +00:00
Ahmad Yasin
1f2fb8e979
[AArch64] Tune unrolling prefs for more patterns on Apple CPUs (#149358)
Enhance the heuristics in `getAppleRuntimeUnrollPreferences` to let a
bit more loops to be unrolled.

Specifically, this patch adjusts two checks:
I. Tune the loop size budget from 8 to 10
II. Include immediate in-loop users of loaded values in the load/stores
dependencies predicate

---------

Co-authored-by: Florian Hahn <flo@fhahn.com>

PR: https://github.com/llvm/llvm-project/pull/149358
2025-08-13 11:16:54 +01:00
Florian Hahn
d10dc67fc3
[LoopUnroll] Add additional reduction unroll tests for #149470.
Add additional tests from https://github.com/llvm/llvm-project/pull/149470.
2025-08-01 15:06:22 +01:00
Ramkumar Ramachandra
fd175fafa6
[RISCV] Adjust unroll prefs for loops with vectors (#151525)
Adjust the unrolling preferences to unroll hand-vectorized code, as well
as the scalar remainder of a vectorized loop. Inspired by a similar
effort in AArch64: see #147420 and #151164.
2025-07-31 21:11:56 +01:00
Joel E. Denny
37e03b56b8
Revert "[PGO] Add llvm.loop.estimated_trip_count metadata" (#151585)
Reverts llvm/llvm-project#148758

[As
requested.](https://github.com/llvm/llvm-project/pull/148758#pullrequestreview-3076627201)
2025-07-31 15:56:31 -04:00
Joel E. Denny
f7b65011de
[PGO] Add llvm.loop.estimated_trip_count metadata (#148758)
This patch implements the `llvm.loop.estimated_trip_count` metadata
discussed in [[RFC] Fix Loop Transformations to Preserve Block
Frequencies](https://discourse.llvm.org/t/rfc-fix-loop-transformations-to-preserve-block-frequencies/85785).
As [suggested in the RFC
comments](https://discourse.llvm.org/t/rfc-fix-loop-transformations-to-preserve-block-frequencies/85785/4),
it adds the new metadata to all loops at the time of profile ingestion
and estimates each trip count from the loop's `branch_weights` metadata.
As [suggested in the PR #128785
review](https://github.com/llvm/llvm-project/pull/128785#discussion_r2151091036),
it does so via a new `PGOEstimateTripCountsPass` pass, which creates the
new metadata for each loop but omits the value if it cannot estimate a
trip count due to the loop's form.

An important observation not previously discussed is that
`PGOEstimateTripCountsPass` *often* cannot estimate a loop's trip count,
but later passes can sometimes transform the loop in a way that makes it
possible. Currently, such passes do not necessarily update the metadata,
but eventually that should be fixed. Until then, if the new metadata has
no value, `llvm::getLoopEstimatedTripCount` disregards it and tries
again to estimate the trip count from the loop's current
`branch_weights` metadata.
2025-07-31 12:28:25 -04:00
John Brawn
9a9b8b7d1c
[AArch64] Allow unrolling of scalar epilogue loops (#151164)
#147420 changed the unrolling preferences to permit unrolling of
non-auto vectorized loops by checking for the isvectorized attribute,
however when a loop is vectorized this attribute is put on both the
vector loop and the scalar epilogue, so this change prevented the scalar
epilogue from being unrolled.

Restore the previous behaviour of unrolling the scalar epilogue by
checking both for the isvectorized attribute and vector instructions in
the loop.
2025-07-31 11:03:41 +01:00
Florian Hahn
f9f68af4b8
[SCEV] Make sure LCSSA is preserved when re-using phi if needed.
If we insert a new add instruction, it may introduce a new use outside
the loop that contains the phi node we re-use. Use fixupLCSSAFormFor to
fix LCSSA form, if needed.

This fixes a crash reported in
https://github.com/llvm/llvm-project/pull/147824#issuecomment-3124670997.
2025-07-28 16:24:46 +01:00
Florian Hahn
90f733ce6e
[LoopUnroll] Add tests for unrolling loops with reductions.
Add tests for unrolling loops with reductions. In some cases, multiple
parallel reduction phis could be retained to improve performance.
2025-07-18 07:39:28 +01:00
Ahmad Yasin
671072e830
[AArch64] Unrolling of loops with vector instructions. (#147420)
This patch permits loops with vector instructions to be unrolled.

Today there is an early exit in `getUnrollingPreferences()` of AArch64
targets if a vector instruction is observed in any of the loop blocks.
This patch fixes that so common loops like this one get a chance to be
unrolled:

void saxpy (float * dst, const float * src, const float a, const int
len) {
        float32x4_t * vdst = (float32x4_t *)dst;
        float32x4_t * vsrc = (float32x4_t *)src;
        float32x4_t vk = vdupq_n_f32(a);
        for (int i = 0; i < (len >> 2); i++)
        {
            vdst[i] = vaddq_f32(vdst[i], vmulq_f32(vsrc[i], vk));
        }
    }

Auto-vectorized loops are still not unrolled, unless they were not
interleaved when vectorized.

The provided test case shows the enhancement on top of runtime/partial
unrolling, depending on the CPU.

PR: https://github.com/llvm/llvm-project/pull/147420
2025-07-14 20:53:09 +01:00
macurtis-amd
cff4a00d3f
AMDGPU: Fix runtime unrolling when cascaded GEPs present (#147700)
Cascaded GEP (i.e. GEP of GEP) are not handled when determining if it is
ok to runtime unroll loops.

This change simply uses `getUnderlyingObjects` to look through cascaded
GEPs.
2025-07-10 03:44:04 -05:00
Philip Reames
bb288de4e0
[LoopPeel] Support last iteration peeling of min/max intrinsics (#143598)
This isn't terribly useful at the moment because of the step=1
restriction but it should be functionally sound. This is mostly just
making sure the codepaths don't diverge as we make other changes.
2025-06-17 11:22:23 -07:00
Philip Reames
719e7bea8a [LoopPeel] Add tests for last iteration peeling of min/max intrinsics 2025-06-10 13:08:36 -07:00
Philip Reames
4e706adc5e [LoopPeel] Add test coverage for edge case for peel last
Add coverage for two cases:
1) Handling of the two transition edge case with equality conditions
   when last iteration is both first and second transition.
2) Need to handle inverted predicates
2025-06-10 11:46:06 -07:00
Florian Hahn
e5ff7055be
[LoopPeel] Use loop guards when checking if last iter can be peeled. (#142605)
Apply loop guards to BTC before checking if the last iteration should be
peeled off. This also adds an assert to make sure applying the guards
does not pessimize the results. I checked on a large test set and it did
not trigger there, but it adds an additional guard to catch potential
cases where loop-guards pessimize results.

Peels ~15% more loops.

PR: https://github.com/llvm/llvm-project/pull/142605
2025-06-10 08:29:42 +01:00
Yingwei Zheng
4eac8daa38
[LoopPeel] Handle non-local instructions/arguments when updating exiting values (#142993)
Similar to
7e14161f49,
the exiting value may be a non-local instruction or an argument.

Closes https://github.com/llvm/llvm-project/issues/142895.
2025-06-06 12:56:28 +08:00
Florian Hahn
3a8b48862a
[LoopPeel] Add tests for peeling last iteration with loop guards.
Add additional test coverage for peeling the last iteration where
information from loop guards is needed.
2025-06-03 14:29:44 +01:00
Florian Hahn
f98bdd94e6
Reapply "[LoopPeel] Remove known trip count restriction when peeling last. (#140792)"
This reverts commit 580454526b936f7a576ddbc9bb932cf9be376ec4.

The recommitted version contains an extra check to not peel if the
latch exit is controlled by a pointer induction.

Original message:
Remove the restriction that the loop must be known to execute at least 2
iterations when peeling the last iteration. If we cannot prove at least
2 iterations are executed, a check and branch to skip the peeled loop is
inserted.

PR: https://github.com/llvm/llvm-project/pull/140792
2025-05-28 13:02:03 +01:00
Florian Hahn
f0f666bc32
[LoopPeel] Add peeling tests with debug value and pointer inductions
Adds extra test coverage for https://github.com/llvm/llvm-project/pull/140792.
2025-05-28 10:07:02 +01:00
Florian Hahn
580454526b
Revert "[LoopPeel] Remove known trip count restriction when peeling last. (#140792)"
This reverts commit 24b97756decb7bf0e26dcf0e30a7a9aaf27f417c.
Also reverts ac9a466e39bf97ffeab127982aa7c405cb257551.

Building CMake triggers a crash with the patch, revert while I
investigate.
2025-05-27 21:25:32 +01:00
Florian Hahn
ac9a466e39
[LoopPeel] Insert new phis before first non-PHI when peeling last iter.
Make sure the new phis are inserted before any non-phi instructions.
This fixes a crash when dbg_value instructions are present in the
original exit block.
2025-05-27 10:46:28 +01:00
Florian Hahn
24b97756de
[LoopPeel] Remove known trip count restriction when peeling last. (#140792)
Remove the restriction that the loop must be known to execute at least 2
iterations when peeling the last iteration. If we cannot prove at least
2 iterations are executed, a check and branch to skip the peeled loop is
inserted.

PR: https://github.com/llvm/llvm-project/pull/140792
2025-05-26 20:08:02 +01:00
Florian Hahn
3c9812eeea
[LoopPeel] Add tests for peeling last iteration with multiple exits. 2025-05-23 15:46:34 +01:00
Florian Hahn
4f869e0f5c
[LoopPeel] Add test for peeling last iteration with non-trivial BTC.
Additional test to https://github.com/llvm/llvm-project/pull/140792 with
different SCEV expansion costs.
2025-05-21 22:28:26 +01:00
Florian Hahn
705e27c234
[LoopPeel] Add tests for peeling from end with variable trip counts.
Add more test coverage for peeling the last iteration with variable trip
counts. Separate test cases for constant and variable trip counts in
different files.
2025-05-20 21:07:21 +01:00
Florian Hahn
a0a2a1e095
[LoopPeel] Make sure exit condition has a single use when peeling last.
Update the check in canPeelLastIteration to make sure the exiting
condition has a single use. When peeling the last iteration, we adjust
the condition in the loop body to be true one iteration early, which
would be incorrect for other users.

Fixes https://github.com/llvm/llvm-project/issues/140444.
2025-05-18 11:47:12 +01:00
Florian Hahn
7e14161f49
[LoopPeel] Handle constants when updating exit values when peeling last.
Account for constant values when updating exit values after peeling an
iteration from the end. This can happen if the inner loop gets unrolled
and simplified.

Fixes https://github.com/llvm/llvm-project/issues/140442.
2025-05-18 10:17:21 +01:00
Florian Hahn
3fcfce4c5e
Reapply "[LoopPeel] Implement initial peeling off the last loop iteration. (#139551)"
This reverts the revert commit bf92b127d2637948f53d11a187e865aa10e2e74c.

This adds missing initialization of PeelLast in gatherPeelingPreferences.

Original message:
Generalize countToEliminateCompares to also consider peeling off the
last iteration if it eliminates a compare.

At the moment, codegen for peeling off the last iteration is quite
restrictive and callers have to make sure that the exit condition can be
adjusted when peeling and that the loop executes at least 2 iterations.

Both will be relaxed in follow-ups.

PR: https://github.com/llvm/llvm-project/pull/139551
2025-05-17 10:51:05 +01:00
Florian Hahn
bf92b127d2
Revert "[LoopPeel] Implement initial peeling off the last loop iteration. (#139551)"
This reverts commit bb10c3ba7f77d40a7fbfd4ac815015d3a4ae476a.

Also reverts 4f663cca15f2b53c2bc6a84d1b1f5bd81679356d:
  Revert "[LoopPeel] Make sure PeelLast is always initialized."

Revert for now to bring msan bots back to green

 https://lab.llvm.org/buildbot/#/builders/164/builds/9992
 https://lab.llvm.org/buildbot/#/builders/94/builds/7158
2025-05-16 08:33:12 +01:00
Florian Hahn
bb10c3ba7f
[LoopPeel] Implement initial peeling off the last loop iteration. (#139551)
Generalize countToEliminateCompares to also consider peeling off the
last iteration if it eliminates a compare.

At the moment, codegen for peeling off the last iteration is quite
restrictive and callers have to make sure that the exit condition can be
adjusted when peeling and that the loop executes at least 2 iterations.

Both will be relaxed in follow-ups.

PR: https://github.com/llvm/llvm-project/pull/139551
2025-05-15 19:15:48 +01:00
Florian Hahn
310ed2b070
[LoopUnroll] Add tests with multiple exiting/latches and small BTCs.
Extra test coverage for cases mentioned during review of
https://github.com/llvm/llvm-project/pull/139551.
2025-05-15 12:54:00 +01:00
Florian Hahn
d39ca81fdd
[LoopPeel] Add initial tests for peeling the last iteration.
Precommit tests for upcoming PR.
2025-05-12 14:56:21 +01:00
Matt Arsenault
9bdd9dc895
AMDGPU: Mark workitem ID intrinsics with range attribute (#136196)
This avoids the need to have special handling at every use site.
Unfortunately this means we unnecessarily emit AssertZext in the DAG
(where we already directly understand the range of the intrinsic), andt
we regress in undefined cases as we don't fold out asserts on undef.
2025-04-18 12:27:38 +02:00
Sirish Pande
7f107c3019
[IndVarsSimplify] sinkUnusedInvariants is skipping instructions while sinking. (#135205)
While sinking instructions (that are loop invariant) from preheader to
the exit block, we are skipping instructions due to decrementing
instruction iterator twice.
2025-04-17 19:21:18 -05:00
Yingwei Zheng
7e5317139d
[PowerPC] Pre-commit tests for PR130742. NFC. (#135606)
Needed by https://github.com/llvm/llvm-project/pull/130742.
2025-04-17 17:52:49 +08:00
Björn Pettersson
092b6e73e6
[InstCombine] Handle "add like" in ADD+GEP->GEP+GEP rewrites (#135156)
Considering that "or disjoint" is the canonical for certain add
operations, then I think we want to support such "add like" operations
when doing ADD+GEP->GEP+GEP rewrites to make things more consistent.

Problem was found when improving ValueTracking, which turned an ADD into
OR, and then suddenly optimizations got worse due to these rewrites no
longer triggering.
2025-04-14 17:11:13 +02:00
David Sherwood
712c21336f
[AArch64] Enable unrolling for small multi-exit loops (#131998)
It can be highly beneficial to unroll small, two-block search loops
that look for a value in an array. An example of this would be
something that uses std::find to find a value in libc++. Older
versions of std::find in the libstdc++ headers are manually unrolled
in the source code, but this might change in newer releases where
the compiler is expected to either vectorise or unroll itself.
2025-04-09 10:34:27 +01:00
Florian Hahn
a4573ee38d
[LoopUnroll] UnrollRuntimeMultiExit takes precedence over TTI. (#134259)
Update UnrollRuntimeLoopRemainder to always give priority to the
UnrollRuntimeMultiExit option, if provided.

After ad9da92cf6f7357 (https://github.com/llvm/llvm-project/pull/124462),
we would ignore the option if the backend indicates multi-exit is profitable.
This means it cannot be used to disable runtime unrolling.

To be consistent with canProfitablyRuntimeUnrollMultiExitLoop, always
respect the option.

This surfaced while discussing https://github.com/llvm/llvm-project/pull/131998.

PR: https://github.com/llvm/llvm-project/pull/134259
2025-04-04 10:16:50 +01:00
David Sherwood
aaf398c2e7
[AArch64] Regenerate apple-unrolling-multi-exit.ll test checks (#134257) 2025-04-04 09:03:49 +01:00
Yingwei Zheng
c5a491e9ea
[SCEV] Check whether the start is non-zero in ScalarEvolution::howFarToZero (#131522)
https://github.com/llvm/llvm-project/pull/94525 assumes that the loop
will be infinite when the stride is zero. However, it doesn't hold when
the start value of addrec is also zero.

Closes https://github.com/llvm/llvm-project/issues/131465.
2025-03-17 13:59:16 +08:00
Jeremy Morse
792a6f8119
[RemoveDIs] Remove "try-debuginfo-iterators..." test flags (#130298)
These date back to when the non-intrinsic format of variable locations
was still being tested and was behind a compile-time flag, so not all
builds / bots would correctly run them. The solution at the time, to get
at least some test coverage, was to have tests opt-in to non-intrinsic
debug-info if it was built into LLVM.

Nowadays, non-intrinsic format is the default and has been on for more
than a year, there's no need for this flag to exist.

(I've downgraded the flag from "try" to explicitly requesting
non-intrinsic format in some places, so that we can deal with tests that
are explicitly about non-intrinsic format in their own commit).
2025-03-14 15:50:49 +00:00
Florian Hahn
46a13a5b17
[AArch64] Runtime-unroll small multi-exit loops on Apple Silicon. (#124751)
Extend unrolling preferences to allow more aggressive unrolling of
search loops with 2 exits, building on the TTI hook added in

ad9da92cf6.

In combination with
eac23a5b97
this enables unrolling loops like
std::find, which can improve performance significantly (+15% end-to-end
on a workload that makes heavy use of std::find). It increase the total
number of unrolled loops by ~2.5% across a very large corpus of
workloads.

For SPEC2017, +1.6% more loops are unrolled and the following workloads
increase in size (`__text`):

      workload             base                patch  
    500.perlbench_r   1682884.00         1694104.00  0.7%
    523.xalancbmk_r   3001716.00          3003832.00  0.1%

PR: https://github.com/llvm/llvm-project/pull/124751
2025-02-27 14:42:45 +00:00
Nikita Popov
29441e4f5f
[IR] Convert from nocapture to captures(none) (#123181)
This PR removes the old `nocapture` attribute, replacing it with the new
`captures` attribute introduced in #116990. This change is
intended to be essentially NFC, replacing existing uses of `nocapture`
with `captures(none)` without adding any new analysis capabilities.
Making use of non-`none` values is left for a followup.

Some notes:
* `nocapture` will be upgraded to `captures(none)` by the bitcode
   reader.
* `nocapture` will also be upgraded by the textual IR reader. This is to
   make it easier to use old IR files and somewhat reduce the test churn in
   this PR.
* Helper APIs like `doesNotCapture()` will check for `captures(none)`.
* MLIR import will convert `captures(none)` into an `llvm.nocapture`
   attribute. The representation in the LLVM IR dialect should be updated
   separately.
2025-01-29 16:56:47 +01:00
Florian Hahn
3007f31e74 [LoopUnroll] Add AArch64 tests for multi-exit loop unrolling.
Test coverage to https://github.com/llvm/llvm-project/pull/124751.
2025-01-28 14:25:27 +00:00
Florian Hahn
d486b76823
[AArch64] Unroll some loops with early-continues on Apple Silicon. (#118499)
Try to runtime-unroll loops with early-continues depending on
loop-varying loads; this helps with branch-prediction for the
early-continues and can significantly improve performance
for such loops

Builds on top of https://github.com/llvm/llvm-project/pull/118317.

PR: https://github.com/llvm/llvm-project/pull/118499.
2024-12-22 13:10:54 +00:00
Vladi Krapp
f8d270474c
[ARM] Reduce loop unroll when low overhead branching is available (#120065)
For processors with low overhead branching (LOB), runtime unrolling the
innermost loop is often detrimental to performance. In these cases the
loop remainder gets unrolled into a series of compare-and-jump blocks,
which in deeply nested loops get executed multiple times, negating the
benefits of LOB.

This is particularly noticable when the loop trip count of the innermost
loop varies within the outer loop, such as in the case of triangular
matrix decompositions.

In these cases we will prefer to not unroll the innermost loop, with the
intention for it to be executed as a low overhead loop.
2024-12-18 10:10:51 +00:00
Florian Hahn
0bb7bd4b4e
[AArch64] Runtime-unroll small load/store loops for Apple Silicon CPUs. (#118317)
Add initial heuristics to selectively enable runtime unrolling for loops
where doing so is expected to be highly beneficial on Apple Silicon
CPUs.

To start with, we try to runtime-unroll small, single block loops, if
they have load/store dependencies, to expose more parallel memory
access streams [1] and to improve instruction delivery [2].

We also explicitly avoid runtime-unrolling for loop structures that may
limit the expected gains from runtime unrolling. Such loops include
loops with complex control flow (aren't innermost loops, have multiple
exits, have a large number of blocks), trip count expansion is
expensive and are expected to execute a small number of iterations.

Note that the heuristics here may be overly conservative and we err on
the side of avoiding runtime unrolling rather than unroll excessively. 
They are all subject to further refinement.

Across a large set of workloads, this increase the total number of
unrolled loops by 2.9%.

[1] 4.6.10 in Apple Silicon CPU Optimization Guide
[2] 4.4.4 in Apple Silicon CPU Optimization Guide

Depends on https://github.com/llvm/llvm-project/pull/118316 for TTI
changes.

PR: https://github.com/llvm/llvm-project/pull/118317
2024-12-09 14:28:31 +00:00
VladiKrapp-Arm
bb3eb0ca0c
[ARM] Test unroll behaviour on machines with low overhead branching (#118692)
Add test for existing loop unroll behaviour.

Current behaviour is the single loop with fmul gets runtime unrolled by
count of 4, with the loop remainder unrolled as the 3 for.body9.us.prol
sections. This is quite a lot of compare and branch, negating the
benefits of the low overhead loop mechanism.
2024-12-06 15:04:56 +00:00
Nikita Popov
f7685af4a5 [InstCombine] Move gep of phi fold into separate function
This makes sure that an early return during this fold doesn't end
up skipping later gep folds.
2024-12-05 15:20:56 +01:00