13749 Commits

Author SHA1 Message Date
Kazu Hirata
19129ea343
[llvm] Use llvm::size (NFC) (#168675)
Note that llvm::size only works on types that allow std::distance in
O(1).
2025-11-19 07:29:57 -08:00
Sjoerd Meijer
a2ddb020d7
[LoopInterchange] Don't consider loops with BTC=0 (#167113)
Do not consider loops with a zero backedge taken count as candidates for
interchange. This seems like a sensible thing because it suggests the loop
doesn't execute and there is no point in interchanging. As a bonus, this
seems to avoid triggering an assert about phis and their uses from source
code, so this is a partial fix for #163954 but it needs more work to properly
fix that.
2025-11-19 13:13:35 +00:00
Kazu Hirata
977d6cfe3e
[Scalar] Remove a redaundant cast (NFC) (#168284)
ThisPartition is already of type int.

Identified with readability-redundant-casting.
2025-11-16 14:06:10 -08:00
Kazu Hirata
e1e696d2eb
[Scalar] Avoid repeated hash lookups (NFC) (#168217) 2025-11-16 08:09:21 -08:00
Mircea Trofin
17789e9fa8
[MemCpyOpt][profcheck] Set unknown branch weights for certain selects (#167597)
Issue #147390
2025-11-14 10:36:50 -08:00
Mircea Trofin
9ac84a6193
[MergeICmp][profcheck] Propagate profile info (#167594)
Propagate branch weights in `mergeComparisons`​ : the probability of reaching the common "exit" BB (`bb_phi`​ in the description in `processPhi`​)doesn't change, and is a disjunction over the probabilities of doing that from the blocks performing comparisons which are now being merged  
  
Issue #147390
2025-11-14 09:29:41 -08:00
Alexander Belyaev
7ee0e0f956 Revert "[LICM] Sink unused l-invariant loads in preheader. #157559"
This reverts commit 469702c5d5cc4fa18c3a962afb971950a084f373.

https://github.com/llvm/llvm-project/issues/168048
2025-11-14 14:51:33 +01:00
Kerang Mao
3890c97fc0
[InferAddressSpaces] Fix bad addrspacecast insertion for phinode (#163528)
The IR verifier will carsh if there is any instructions located before
phi-node. The `infer-address-spaces` pass would like to insert
`addrspacecast` before phi-node in some corner cases. Indeed, since the
operand pointer(phi-node's incoming value) has been determined to
`NewAS` by the pass, it is safe to `addrspacecast` it immediately after
the position where defined it.

Co-authored-by: Kerang Mao <krmao@birentech.com>
2025-11-14 18:55:05 +08:00
Kazu Hirata
4d42a0c3f1
[Scalar] Avoid deep copies of DenseMap (NFC) (#168012)
Passing BlockOrder by value results in deep copies of DenseMap.  This
patch replaces them with const l-value references.
2025-11-13 21:54:16 -08:00
Michael Kruse
7a0f7dbf2d
[Polly] Introduce PhaseManager and remove LPM support (#125442) (#167560)
Reapply of a22d1c2225543aa9ae7882f6b1a97ee7b2c95574. Using this PR for
pre-merge CI.

Instead of relying on any pass manager to schedule Polly's passes, add
Polly's own pipeline manager which is seen as a monolithic pass in
LLVM's pass manager. Polly's former passes are now phases of the new
PhaseManager component.

Relying on LLVM's pass manager (the legacy as well as the New Pass
Manager) to manage Polly's phases never was a good fit that the
PhaseManager resolves:

* Polly passes were modifying analysis results, in particular RegionInfo
and ScopInfo. This means that there was not just one unique and
"definite" analysis result, the actual result depended on which analyses
ran prior, and the pass manager was not allowed to throw away cached
analyses or prior SCoP optimizations would have been forgotten. The LLVM
pass manger's persistance of analysis results is not contractual but
designed for caching.

* Polly depends on a particular execution order of passes and regions
(e.g. regression tests, invalidation of consecutive SCoPs). LLVM's pass
manager does not guarantee any excecution order.

* Polly does not completely preserve DominatorTree, RegionInfo,
LoopInfo, or ScalarEvolution, but only as-needed for Polly's own uses.
Because the ScopDetection object stores references to those analyses, it
still had to lie to the pass manager that they would be preserved, or
the pass manager would have released and recomputed the invalidated
analysis objects that ScopDetection/ScopInfo was still referencing. To
ensure that no non-Polly pass would see these not-completely-preserved
analyses, all analyses still had to be thrown away after the
ScopPassManager, respectively with a BarrierNoopPass in case of the LPM.
 
* The NPM's PassInstrumentation wraps the IR unit into an `llvm::Any`
object, but implementations such as PrintIRInstrumentation call
llvm_unreachable on encountering an unknown IR unit, such as SCoPs, with
no extension points to add support. Hence LLVM crashes when dumping IR
between SCoP passes (such as `-print-before-changed` with Polly being
active).

The new PhaseManager uses some command line options that previously
belonged to Polly's legacy passes, such as `-polly-print-detect` (so the
option will continue to work). Hence the LPM support is incompatible
with the new approach and support for it is removed.
2025-11-14 00:45:54 +01:00
Mircea Trofin
3d41cbb13f
[PILC][profcheck] Bias branch weights when optimizing sqrt (#167742)
Biasing towards the native `sqrt`​ not returning NaN.  


Issue #147390
2025-11-13 12:46:22 -08:00
Kazu Hirata
0f45a33193 [Scalar] Fix warnings
This patch fixes:

  llvm/lib/Transforms/Scalar/StraightLineStrengthReduce.cpp:689:45:
  error: lambda capture 'DT' is not used
  [-Werror,-Wunused-lambda-capture]

  llvm/lib/Transforms/Scalar/StraightLineStrengthReduce.cpp:584:1:
  error: unused function 'operator<<' [-Werror,-Wunused-function]
2025-11-13 07:02:23 -08:00
Fei Peng
f67409c3ec
Redesign Straight-Line Strength Reduction (SLSR) (#162930)
This PR implements parts of
https://github.com/llvm/llvm-project/issues/162376

- **Broader equivalence than constant index deltas**:
- Add Base-delta and Stride-delta matching for Add and GEP forms using
ScalarEvolution deltas.
- Reuse enabled for both constant and variable deltas when an available
IR value dominates the user.
- **Dominance-aware dictionary instead of linear scans**:
  - Tuple-keyed candidate dictionary grouped by basic block.
- Walk the immediate-dominator chain to find the nearest dominating
basis quickly and deterministically.
- **Simple cost model and best-rewrite selection**:
- Score candidate expressions and rewrites; select the highest-profit
rewrite per instruction.
- Skip rewriting when expressions are already foldable or
high-efficiency.
- **Path compression for better ILP**:
- Compress chains of rewrites to a deeper dominating basis when a
constant delta exists along the path, reducing dependent bumps on
critical paths.
- **Dependency-aware rewrite ordering**:
- Build a dependency graph (basis, stride, variable delta producers) and
rewrite in topological order.
- This dependency graph will be needed by the next PR that adds partial
strength reduction.
2025-11-13 08:08:52 -06:00
Yingwei Zheng
edd8b29667
[Float2Int] Make sure the CFP can be represented in the integer type (#167699)
When `convertToInteger` fails, the integer result is undefined. In this
case, we cannot use it in the subsequent steps.
Close https://github.com/llvm/llvm-project/issues/167627.
2025-11-13 20:54:32 +08:00
serge-sans-paille
45a2320372
Remove unused <utility> inclusion
Per https://llvm.org/docs/CodingStandards.html#include-as-little-as-possible this improves compilation time, while not being too intrusive on the codebase.
2025-11-11 13:33:33 +01:00
Antonio Frighetto
eaf3a91722
[IndVarSimplify] Ensure fp values can be represented as exact integers
When transforming floating-point induction variables into integer ones,
make sure we stay within the bounds of fp values that can be represented
as integers without gaps, i.e., 2^24 and 2^53 for IEEE-754 single and
double precision respectively (both on negative and positive side).

Fixes: https://github.com/llvm/llvm-project/issues/166496.
2025-11-11 10:30:58 +01:00
Florian Hahn
80fa6e1bce
[DropAssumes] Drop dereferenceable assumptions after vectorization. (#166947)
This patch adds another run of DropUnnecessaryAssumes after
vectorization, to clean up assumes that are not longer needed after this
point.

The main example of such an assume is currently dereferenceable
assumptions. This complements
https://github.com/llvm/llvm-project/pull/166945, which avoids sinking
code if it would mean remove a dereferenceable assumption.

There are a few additional cases where some unneeded assumes are left
over after vectorization that also get cleaned up.

The main motivation is to work together with
https://github.com/llvm/llvm-project/pull/166945, but there may be a
better solution.

Adding another instance of this pass to the pipeline is not great, but
compile-time impact seems in the noise:
https://llvm-compile-time-tracker.com/compare.php?from=55e71fe08b6406ec7ce2c81ce042e48717acf204&to=85da4ee3a74126f557cdc74c7b40e048dacb3fc4&stat=instructions:u

PR: https://github.com/llvm/llvm-project/pull/166947
2025-11-10 10:50:15 +00:00
Kazu Hirata
1b3eaacb9d
[llvm] Remove unused local variables (NFC) (#167185)
Identified with bugprone-unused-local-non-trivial-variable.
2025-11-08 22:56:03 -08:00
Mircea Trofin
77e3975236
[LSCFG][profcheck] Add dummy branch weights for the dummy switch to dead exits (#164714)
As noted in the doc comment of `handleDeadExits`​, the dummy switch is just an artifact of the constraints placed by the fact that we operate in a loop pass. Adding weights here is unnecessary, but the complexity is low, and it helps keep things easy for profile propagation verification (in a sense, the overall complexity would be higher if we special-cased this somehow).

Issue #147390
2025-11-05 17:14:03 -08:00
Mircea Trofin
5e46103f1b
[LIR][profcheck] Reuse the loop's exit condition profile (#164523)
The idioms are described in https://reviews.llvm.org/D102116 and [https://reviews.llvm.org/D92754](https://reviews.llvm.org/D91038). In both cases, the way the loop is expressed changes, without changing its iteration count, which means we can reuse the original loop's branch probabilities.

Issue #147390
2025-11-05 13:39:22 -08:00
Mircea Trofin
ff108f7486
Fix failures introduced in #166032 (#166574) 2025-11-05 08:02:55 -08:00
Mircea Trofin
52cb6e9d49
[ProfCheck][NFC] Make Function argument from branch weight setter optional (#166032)
This picks up from #166028, making the `Function` argument optional:
most cases don't need to provide it, but in e.g. InstCombine's case,
where the instruction (select, branch) is not attached to a function
yet, the function needs to be passed explicitly.

Co-authored-by: Florian Hahn <flo@fhahn.com>
2025-11-05 07:40:37 -08:00
Mircea Trofin
1458d313a1
[SLU][profcheck] Propagate profile for branches on injected conditions. (#164476)
This patch addresses the profile of 2 branches:

- one that compares the 2 limits, for which we have no information (the C1, C2, see https://reviews.llvm.org/D136233)
- one that is conditioned on a condition for which we have a profile, so we reuse it



Issue #147390
2025-11-04 17:23:55 -08:00
Mircea Trofin
d547931137
[SLU][profcheck] create likely branch weights for guard->branch (#164271)
The `llvm.experimental.guard` intrinsic is a `call`, so its metadata - if present - would be one value (as per `Verifier::visitProfMetadata`). That wouldn't be a correct `branch_weights` metadata. Likely, `GI->getMetadata(LLVMContext::MD_prof)` was always `nullptr`.

We can bias away from deopt instead.

Issue #147390
2025-11-04 16:39:12 -08:00
Alireza Torabian
025e431e74
[LoopFusion] Forget loop and block dispositions after latch merge (#166233)
Merging the latches of loops may affect the dispositions, so they should
be forgotten after the merge. This patch fixed the crash in loop fusion
[#164082](https://github.com/llvm/llvm-project/issues/164082).
2025-11-04 16:48:39 -05:00
Ivan Kelarev
37825ad4f6
[LoopUnroll] Prevent LoopFullUnrollPass from performing partial unrolling when trip counts are unknown (#165013)
Currently, `LoopFullUnrollPass` incorrectly performs partial unrolling
when `#pragma unroll` is specified and both `TripCount` and
`MaxTripCount` are unknown. This patch adds a check to prevent partial
unrolling when `OnlyFullUnroll` parameter is true and both trip count
values are zero.
2025-11-04 09:20:01 -08:00
Florian Hahn
af9a4263a1
[LAA] Only use inbounds/nusw in isNoWrap if the GEP is dereferenced. (#161445)
Update isNoWrap to only use the inbounds/nusw flags from GEPs that are
guaranteed to be dereferenced on every iteration. This fixes a case
where we incorrectly determine no dependence.

I think the issue is isolated to code that evaluates the resulting
AddRec at BTC, just using it to compute the distance between accesses
should still be fine; if the access does not execute in a given
iteration, there's no dependence in that iteration. But isolating the
code is not straight-forward, so be conservative for now. The practical
impact should be very minor (only one loop changed across a corpus with
27k modules from large C/C++ workloads.

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

PR: https://github.com/llvm/llvm-project/pull/161445
2025-11-04 17:08:12 +00:00
Mircea Trofin
01221874e4
[SLU][profcheck] Use the original branch weigths in buildPartialInvariantUnswitchConditionalBranch (#164270)
A new branch is created on the same condition as a branch for which we have a profile. We can reuse that profile in this case.

Issue #147390
2025-11-03 14:37:41 -08:00
Robert Imschweiler
a8ea7f4580
Reapply: [AMDGPU][UnifyDivergentExitNodes][StructurizeCFG] Add support for callbr instruction with inline-asm (#152161) (#166195)
Reapply #152161 with fixed 'changed' flags.
2025-11-03 20:59:48 +01:00
Robert Imschweiler
af68efc9c4
Revert "[AMDGPU][UnifyDivergentExitNodes][StructurizeCFG] Add support for callbr instruction with inline-asm" (#166186)
Reverts llvm/llvm-project#152161

Need to revert to fix changed logic for the expensive checks.
2025-11-03 16:33:20 +00:00
Robert Imschweiler
332f9b5eee
[AMDGPU][UnifyDivergentExitNodes][StructurizeCFG] Add support for callbr instruction with inline-asm (#152161)
Finishes adding inline-asm callbr support for AMDGPU, started by
https://github.com/llvm/llvm-project/pull/149308.
2025-11-03 16:09:12 +01:00
Hassnaa Hamdi
8998df2097
[DropUnnecessaryAssumes] Don't drop public_type_test intrinsic (#166034)
Don't drop `assume` intrinsic when it's using `public_type_test `
intrinsic, as it could be used by devirtualization.
2025-11-03 10:34:44 +00:00
Kazu Hirata
707bab651f
[llvm] Remove redundant typename (NFC) (#166087)
Identified with readability-redundant-typename.
2025-11-02 13:15:16 -08:00
Kazu Hirata
c9ef3d8eb8
[Transforms] Use "= default" (NFC) (#166043)
Identified with modernize-use-equals-default.
2025-11-02 08:59:24 -08:00
Nathan Corbyn
138e0ff87c
[Matrix] (NFC) Refactor sharing of shape information (#164774) 2025-11-02 09:44:34 +00:00
Mircea Trofin
e63f0f50fa
[SLU][profcheck] Estimate branch weights in partial unswitch cases (#164035)
In the case of a partial unswitch, we take the invariant part of an expression consisting of either conjunctions or disjunctions, and hoist it out of the loop, conditioning a branch on it (==the invariant part). We can't correctly calculate the branch probability of this new branch, but can use the probability of the existing branch as a bound. That would preserve block frequencies better than allowing for the default, static (50-50) probability for that branch.

Issue #147390
2025-10-30 10:37:15 -07:00
Vigneshwar Jayakumar
469702c5d5
[LICM] Sink unused l-invariant loads in preheader. (#157559)
Unused loop invariant loads were not sunk from the preheader to the exit
block, increasing live range.

This commit moves the sinkUnusedInvariant logic from indvarsimplify to
LICM also adds functionality to sink unused load that's not
clobbered by the loop body.
2025-10-30 09:23:04 -05:00
John Brawn
53e7443e0c
[LSR] Don't count conditional loads/store as enabling pre/post-index (#159573)
When a load/store is conditionally executed in a loop it isn't a
candidate for pre/post-index addressing, as the increment of the address
would only happen on those loop iterations where the load/store is
executed.

Detect this and only discount the AddRec cost when the load/store is
unconditional.
2025-10-30 13:53:15 +00:00
Nikita Popov
8f624815bf
[MemCpyOpt] Allow stack move optimization if one address captured (#165527)
Allow the stack move optimization (which merges two allocas) when the
address of only one alloca is captured (and the provenance is not
captured). Both addresses need to be captured to observe that the
allocas were merged.

Fixes https://github.com/llvm/llvm-project/issues/165484.
2025-10-30 10:23:40 +01:00
Hongyu Chen
affed57d36
[DFAJumpThreading] Add MaxOuterUseBlocks threshold (#163428)
For every threadable path `B1 -> B2 -> ... -> Bn`, we need to insert phi
nodes into every unduplicated successor of `Bi` if there are outer uses
of duplicated definitions in `B_i`. To prevent the booming of phi nodes,
this patch adds a threshold for the maximum number of unduplicated
successors that may contain outer uses. This threshold makes sense
especially when multi-target branches like switch/indirectbr/callbr are
duplicated.

Note that the O3 statistics in llvm-test-suite are not influenced.
2025-10-30 00:34:48 +08:00
Rahul Joshi
213b8a9f18
[NFC][LLVM] Namespace cleanup in MergeICmps (#163761) 2025-10-23 09:15:24 -07:00
Florian Hahn
daf0182277
[ConstraintElim] Apply add with neg constant first during decomp. (#164791)
We have dedicated decomposition logic for (add %x, -C), but if we have
(add nsw %x, -C) we will first apply the generic logic for NSWAdd, which
gives worse results for negative constants in practice.

Update the code to first apply the pattern with negative constants.

Helps to remove a number of runtime checks in practice:
https://github.com/dtcxzyw/llvm-opt-benchmark/pull/2968

Alive2 proofs for the test changes: https://alive2.llvm.org/ce/z/JfR2Ma

PR: https://github.com/llvm/llvm-project/pull/164791
2025-10-23 12:50:12 +01:00
Nikita Popov
80b311a944 [SpeculativeExecution] Add support for ptrtoaddr 2025-10-20 16:56:11 +02:00
Nikita Popov
2ec549ad11 [GVNSink] Add support for ptrtoaddr 2025-10-20 16:46:08 +02:00
Sjoerd Meijer
b90a8d385e
[LoopInterchange] Add simplifyLCSSAPhis: remove phi from non-exit bb (#160889)
This deals with a corner case of LCSSA phi nodes in the outer loop latch
block: the loop was in LCSSA form, some transformations can come along
(e.g. unswitch) and create an empty block:

     BB4:
       br label %BB5
     BB5:
       %old.cond.lcssa = phi i16 [ %cond, %BB4 ]
       br outer.header

Interchange then brings it in LCSSA form again and we get:

     BB4:
       %new.cond.lcssa = phi i16 [ %cond, %BB3 ]
       br label %BB5
     BB5:
       %old.cond.lcssa = phi i16 [ %new.cond.lcssa, %BB4 ]

Which means that we have a chain of LCSSA phi nodes from %new.cond.lcssa
to %old.cond.lcssa. The problem is that interchange can reoder blocks
BB4 and BB5 placing the use before the def if we don't check this. The
solution is to simplify lcssa phis, and remove them from non-exit blocks
if they are 1-input phi nodes.

Fixes #160068
2025-10-20 10:23:36 +01:00
Nikita Popov
573ca36753
[IR] Replace alignment argument with attribute on masked intrinsics (#163802)
The `masked.load`, `masked.store`, `masked.gather` and `masked.scatter`
intrinsics currently accept a separate alignment immarg. Replace this
with an `align` attribute on the pointer / vector of pointers argument.

This is the standard representation for alignment information on
intrinsics, and is already used by all other memory intrinsics. This
means the signatures now match llvm.expandload, llvm.vp.load, etc.
(Things like llvm.memcpy used to have a separate alignment argument as
well, but were already migrated a long time ago.)

It's worth noting that the masked.gather and masked.scatter intrinsics
previously accepted a zero alignment to indicate the ABI type alignment
of the element type. This special case is gone now: If the align
attribute is omitted, the implied alignment is 1, as usual. If ABI
alignment is desired, it needs to be explicitly emitted (which the
IRBuilder API already requires anyway).
2025-10-20 08:50:09 +00:00
Luke Lau
df8956442f
[SimpleLoopUnswitch] Don't use BlockFrequencyInfo to skip cold loops (#159522)
In https://reviews.llvm.org/D129599, non-trivial switching was disabled
for cold loops in the interest of code size. This added a dependency on
BlockFrequencyInfo with PGO, but in loop passes this is only available
on a lossy basis: see https://reviews.llvm.org/D86156

LICM moved away from BFI so as of today SimpleLoopUnswitch is the only
remaining loop pass that uses BFI, for the sole reason to prevent code
size increases in PGO builds. It doesn't use BFI if there's no profile
summary available.

After some investigation on llvm-test-suite it turns out that the lossy
BFI causes very significant deviations in block frequency, since when
new loops are deleted/created during the loop pass manager it can return
frequencies for different loops altogether.
This results in unswitchable loops being mistakenly skipped because they
are thought to be cold.

This patch removes the use of BFI from SimpleLoopUnswitch and thus the
last remaining use of BFI in a loop pass.

To recover the original intent of not unswitching cold code,
PGOForceFunctionAttrs can be used to annotate functions which can be
optimized for code size, since SimpleLoopUnswitch will respect OptSize:
https://reviews.llvm.org/D94559

This isn't 100% the same behaviour since the previous behaviour checked
for coldness at the loop level and this is now at the function level. We
could expand PGOForceFunctionAttrs to be more granular at the loop
level, https://github.com/llvm/llvm-project/issues/159595 tracks this
idea.
2025-10-17 23:33:49 +00:00
Adam Nemet
783b050f88
[LMI] Support non-power-of-2 types for the matmul remainder (#163987)
In the inner loop of matmul, instead of continuously halving the HW
vector register width, I just use the remainder vector directly if it's
legal.

We don't have in-tree targets that have this so I opted for adding a
hidden flag to simulate this for testing purposes:
-matrix-split-matmul-remainder-over-threshold

The tests are the vectorization-friendly 3x3x1 matrix-vector and 1x3x3
vector-matrix multiplies for CM, RM respectively.
2025-10-17 18:42:30 +00:00
Orlando Cazalet-Hyams
7bbb03d516
[NFC][SROA][DebugInfo] Reuse existing dbg_assigns where possible (#163938)
Addresses issue #145937

Without this patch SROA generates new dbg_assign for new stores. We can
simply steal the existing dbg_assigns linked to the old store when the
store is not being split.
2025-10-17 17:19:43 +01:00
Rahul Joshi
7c02ca846c
[NFC][LLVM] Namespace cleanup in LowerMatrixIntrinsics (#163760) 2025-10-17 07:37:14 -07:00