41793 Commits

Author SHA1 Message Date
Florian Hahn
bcbbe2c2bc
[VPlan] Pass backedge value directly to FOR and reduction phis (NFC).
Pass backedge values directly to VPFirstOrderRecurrencePHIRecipe and
VPReductionPHIRecipe directly, as they must be provided and availbale.

Split off from https://github.com/llvm/llvm-project/pull/168291.
2025-12-14 20:59:22 +00:00
Florian Hahn
53cf22f3a1
[VPlan] Simplify live-ins early using SCEV. (#155304)
Use SCEV to simplify all live-ins during VPlan0 construction. This
enables us to remove special SCEV queries when constructing
VPWidenRecipes and improves results in some cases.

This leads to simplifications in a number of cases in real-world
applications (~250 files changed across LLVM, SPEC, ffmpeg)

PR: https://github.com/llvm/llvm-project/pull/155304
2025-12-14 20:15:05 +00:00
int-zjt
fd95803a35
[LoopRotate] Simplify PHINode::removeIncomingValue usage (NFC) (#171958) 2025-12-14 09:43:52 +08:00
Luke Lau
4ea8157773 Revert "[VPlan] Remove legacy costing inside VPBlendRecipe::computeCost (#171846)"
This reverts commit fd5f53aa9b21060063484fc6c346316a34a6464c.

It's triggering legacy cost model assertions reported in
https://github.com/llvm/llvm-project/pull/171846#issuecomment-3647640019
2025-12-13 20:05:34 +08:00
Nicolai Hähnle
54ae1222ef
VectorCombine: Fold chains of shuffles fed by length-changing shuffles (#168819)
Such chains can arise from folding insert/extract chains.
2025-12-12 13:53:03 -08:00
Florian Hahn
e6e3f94b5c
[VPlan] Re-add clarifying comment regarding part to extract. (NFC)
Re-add and emphasize comment regarding extracting from the last part, as
suggested post-commit in https://github.com/llvm/llvm-project/pull/171145.
2025-12-12 21:51:33 +00:00
Florian Hahn
333ee931df
[LV] Update stale comment after 4e05d702f02a. (NFC)
Address post-commit suggestion, update stale comment after 4e05d702f.
2025-12-12 21:36:56 +00:00
Florian Hahn
0171e881b5
[VPlan] Strip stray whitespace when printing VPWidenIntOrFpInduction.
printFlags takes care of inserting the needed spaces, remove unneeded
extra stray whitespace
2025-12-12 21:28:50 +00:00
Alireza Torabian
9bc38df587
[LoopFusion] Simplifying the legality checks (#171889)
Considering that the current loop fusion only supports adjacent loops,
we are able to simplify the checks in this pass. By removing
`isControlFlowEquivalent` check, this patch fixes multiple issues
including #166560, #166535, #165031, #80301 and #168263.

Now only the sequential/adjacent candidates are collected in the same
list. This patch is the implementation of approach 2 discussed in post
#171207.
2025-12-12 15:09:34 -05:00
Seraphimt
112a6126ef
Fixes non-functional changes found static analyzer (#171197)
As per @arsenm 's instructions, I've separated the non-functional
changes from https://github.com/llvm/llvm-project/pull/169958.
Afterwards I'll tackle the functional ones one by one. I hope I did
everything right this time.

Full descriptions in the article:
https://pvs-studio.com/en/blog/posts/cpp/1318/
3. Array overrun is possible.
The PVS-Studio warning: V557 Array overrun is possible. The value of
'regIdx' index could reach 31. VEAsmParser.cpp 696
10. Excessive check.
The PVS-Studio warning: V547 Expression 'IsLeaf' is always false.
PPCInstrInfo.cpp 419
11. Doubling the same check.
The PVS-Studio warning: V581 The conditional expressions of the 'if'
statements situated alongside each other are identical. Check lines:
5820, 5823. PPCInstrInfo.cpp 5823
15. Excessive check.
The PVS-Studio warning: V547 Expression 'i != e' is always true.
MachineFunction.cpp 1444
17. Excessive assignment.
The PVS-Studio warning: V1048 The 'FirstOp' variable was assigned the
same value. MachineInstr.cpp 1995
18. Excessive check.
The PVS-Studio warning: V547 Expression 'AllSame' is always true.
SimplifyCFG.cpp 1914
19. Excessive check.
The PVS-Studio warning: V547 Expression 'AbbrevDecl' is always true.
LVDWARFReader.cpp 398
2025-12-12 20:03:02 +01:00
Craig Topper
ef21740781
[LoopPeel] Check for onlyAccessesInaccessibleMemory instead of llvm.assume in peelToTurnInvariantLoadsDereferenceable. (#171910)
onlyAccessesInaccessibleMemory can't alias with a load. This allows us
to ignore more intrinsics than llvm.assume.

Follow up from #171547
2025-12-12 10:45:41 -08:00
Mircea Trofin
ff3dcd06a9
[GlobalOpt][profcheck] Mark as unknown the branch weights of global shrunk to boolean (#171530) 2025-12-12 08:34:11 -08:00
Matt Arsenault
6e47d4ef45
Reapply "InstCombine: Fold ldexp with constant exponent to fmul" (#171895) (#171977) 2025-12-12 12:55:55 +01:00
Nikita Popov
89c37fee25 [WPD] Use getSigned() for offset
This offset is a signed int64_t which can take negative values.
2025-12-12 11:15:44 +01:00
Peter Collingbourne
b0d3405578
SROA: Recognize llvm.protected.field.ptr intrinsics.
When an alloc slice's users include llvm.protected.field.ptr intrinsics
and their discriminators are consistent, drop the intrinsics in order
to avoid unnecessary pointer sign and auth operations.

Reviewers: nikic

Reviewed By: nikic

Pull Request: https://github.com/llvm/llvm-project/pull/151650
2025-12-11 18:22:05 -08:00
Florian Hahn
65deac0872
[VPlan] Remove vector type checking in inferScalartType (NFC).
inferScalarTypeForRecipe always infers a scalar type, so BaseTy must be
a scalar type. Remove unneeded cast.
2025-12-11 22:10:31 +00:00
Florian Hahn
4e05d702f0
[LV] Always include middle block cost in isOutsideLoopWorkProfitable. (#171102)
Always include the cost of the middle block in
isOutsideLoopWorkProfitable. This addresses the TODO from
https://github.com/llvm/llvm-project/pull/168949 and removes the
temporary restriction.

isOutsideLoopWorkProfitable already scales the cost outside loops
according the expected trip counts.

In practice this increases the minimum iteration threshold in a few
cases. On a large IR corpus based on C/C++ workloads, ~50 out of 179450
vector loops have their thresholds increased slightly.


PR: https://github.com/llvm/llvm-project/pull/171102
2025-12-11 21:41:47 +00:00
Matt Arsenault
757c5b3bc7
Revert "InstCombine: Fold ldexp with constant exponent to fmul" (#171895)
Reverts llvm/llvm-project#171731

Fails on a libc test
2025-12-11 21:12:59 +00:00
Teresa Johnson
75cd29b6d6
[MemProf] Add option to emit full call context for matched allocations (#170516)
Add the -memprof-print-matched-alloc-stack option to enable emitting the
full allocation call context (of stack ids) for each matched allocation
reported by -memprof-print-match-info. Noop when the latter is not
enabled.
2025-12-11 10:43:53 -08:00
Matt Arsenault
5eb2ec2179
InstCombine: Fold ldexp with constant exponent to fmul (#171731)
If we can represent this with an fmul, prefer it as a canonical
form. More optimizations will understand fmul, and allows contract to
fma.
2025-12-11 19:20:45 +01:00
Alexis Engelke
6813f8f037
[IR] Don't store switch case values as operands
SwitchInst case values must be ConstantInt, which have no use list.
Therefore it is not necessary to store these as Use, instead store them
more efficiently as a simple array of pointers after the uses, similar
to how PHINode stores basic blocks.

After this change, the successors of all terminators are stored
consecutively in the operand list. This is preparatory work for
improving the performance of successor access.

Add new C API functions so that switch case values remain accessible
from bindings for other languages.

While this could also be achieved by merely changing the order of
operands (i.e., first all successors, then all constants), doing so
would increase the asymptotic runtime of addCase from O(1) to O(n)
(i.e., adding n cases would be O(n^2)), because it would need to shift
all constants by one slot. Having null/invalid operands is also a bad
idea and would cause much more breakage.

Pull Request: https://github.com/llvm/llvm-project/pull/170984
2025-12-11 18:38:39 +01:00
Nikita Popov
8a9d9e4853 [LV] Use getSigned() for stride
The stride may be negative.
2025-12-11 17:30:37 +01:00
Nikita Popov
bc19a0ad49 [InstCombine] Use getSigned() for negative numbers 2025-12-11 17:30:37 +01:00
Nikita Popov
a981d26bd5 [KCFI] Use getSigned() for negative value 2025-12-11 17:30:37 +01:00
Luke Lau
fd5f53aa9b
[VPlan] Remove legacy costing inside VPBlendRecipe::computeCost (#171846)
A VPBlendRecipe always emits selects, even when the VF is scalar.

However the legacy cost model always costs all scalar non-header phis as
a phi, and the VPlan cost model has to account for this.

This can cause the cost to be a little off, for example not including
the cost of the select in @smax_call_uniform leading to unprofitable
vectorization.

This removes this from the VPlan cost model and handles checks for the
case in planContainsAdditionalSimplifications instead.

I considered trying to make the legacy cost model more accurate but I'm
not sure if it's possible. We need information as to whether or not the
scalar VF we are costing is the original loop in which case it's
actually a phi, or if it's a VPBlendRecipe that emits a select,
potentially from a VF=1, UF>=1 VPlan.
2025-12-12 00:25:58 +08:00
Ramkumar Ramachandra
85fafd5db0
[SCEVExp] Get DL from SE, strip constructor arg (NFC) (#171823) 2025-12-11 14:26:47 +00:00
Luke Lau
2967815249
[VPlan] Don't emit VPBlendRecipes with only one incoming value. NFC (#171804)
We can just directly use the incoming value. These single value blends
would get optimized later on in simplifyBlends, but by doing it early it
removes the notion of an "immediately normalized" blend, and simplifies
an upcoming patch.
2025-12-11 12:55:56 +00:00
Tirthankar Mazumder
2ce17ba347
[InstCombine][CmpInstAnalysis] Use consistent spelling and function names. NFC. (#171645)
Both `decomposeBitTestICmp` and `decomposeBitTest` have a parameter
called `lookThroughTrunc`. This was spelled in full (i.e. `lookThroughTrunc`)
in the header. However, in the implementation, it's written as `lookThruTrunc`.

I opted to convert all instances of `lookThruTrunc` into
`lookThroughTrunc` to reduce surprise while reading the code and for
conformity.

---

The other change in this PR is the renaming of the wrapper around
`decomposeBitTest()`. Even though it was a wrapper around
`CmpInstAnalysis.h`'s `decomposeBitTest`, the function was called
`decomposeBitTestICmp`. This is quite confusing because such a function
_also_ exists in `CmpInstAnalysis.h`, but it is _not_ the one actually
being used in `InstCombineAndOrXor.cpp`.
2025-12-11 07:40:04 +00:00
Florian Hahn
5a1299b196
[VPlan] Strip stray whitespace when printing VPWidenSelectRecipe. (NFCI)
printFlags takes care of inserting the correct amount of spaces,
depending on whether there are flags to print or not.
2025-12-10 22:15:35 +00:00
Craig Topper
ccc3835ffa
[LoopPeel] Ignore assume intrinsics for the mayWriteToMemory check in peelToTurnInvariantLoadsDereferenceable. (#171547)
llvm.assume intrinsics have the mayWriteToMemory property, but
won't prevent the load from becoming dereferenceable.
2025-12-10 13:14:19 -08:00
Evgenii Podkorytov
617ba837ee
[GlobalOpt] Preserve Address Space when recreating GV (#171211)
Fix for GlobalOpt pass: preserve Address Space when recreating GV
This fix prevents dropping `addrspace(1)` in the following code snippet
(see modified LIT-test) for `@llvm.compiler.used`:

Before global-opt
```
@_ZM2C = internal addrspace(1) global %struct.FakeDeviceGlobal zeroinitializer, align 8
@_ZL1C = internal addrspace(1) global %struct.FakeDeviceGlobal zeroinitializer, align 8

@llvm.compiler.used = appending addrspace(1) global [2 x ptr addrspace(4)] [ptr addrspace(4) addrspacecast (ptr addrspace(1) @_ZM2C to ptr addrspace(4)), ptr addrspace(4) addrspacecast (ptr addrspace(1) @_ZL1C to ptr addrspace(4))]
```

After global-opt
```
@_ZM2C = internal addrspace(1) global %struct.FakeDeviceGlobal zeroinitializer, align 8
@_ZL1C = internal addrspace(1) global %struct.FakeDeviceGlobal zeroinitializer, align 8

@llvm.compiler.used = appending global [2 x ptr addrspace(4)] [ptr addrspace(4) addrspacecast (ptr addrspace(1) @_ZM2C to ptr addrspace(4)), ptr addrspace(4) addrspacecast (ptr addrspace(1) @_ZL1C to ptr addrspace(4))]
```

With proposed fix `@llvm.compiler.used` will be re-created with
preserving original `addrspace(1)` as:
```
@llvm.compiler.used = appending addrspace(1) global [2 x ptr addrspace(4)] [ptr addrspace(4) addrspacecast (ptr addrspace(1) @_ZM2C to ptr addrspace(4)), ptr addrspace(4) addrspacecast (ptr addrspace(1) @_ZL1C to ptr addrspace(4))]
```
2025-12-10 15:10:40 +01:00
Ramkumar Ramachandra
1c7126d8db
[VPlan] Combine LiveIns fields into MapVector (NFC) (#170220)
Combine Value2VPValue and VPLiveIns into a single MapVector LiveIns
field, simplifying users.
2025-12-10 07:09:21 +00:00
Ramkumar Ramachandra
3310c0be58
[VPlan] Strip TODO to consolidate (ActiveLaneMask|Widen)PHI (#171392)
They cannot be consolidated, as WidenPHI is not a header PHI, while
ActtiveLaneMaskPHI is.
2025-12-09 21:38:58 +00:00
Aiden Grossman
f29d06029f Revert "[LV] Mark checks as never succeeding for high cost cutoff."
This reverts commit 8a115b6934a90441d77ea54af73e7aaaa1394b38.

This broke premerge. https://lab.llvm.org/staging/#/builders/192/builds/13326

/home/gha/llvm-project/clang/test/Frontend/optimization-remark-options.c:10:11: remark: loop not vectorized: cannot prove it is safe to reorder floating-point operations; allow reordering by specifying '#pragma clang loop vectorize(enable)' before the loop or by providing the compiler option '-ffast-math'
2025-12-09 21:32:09 +00:00
Florian Hahn
8a115b6934
[LV] Mark checks as never succeeding for high cost cutoff.
When GeneratedRTChecks::create bails out due to exceeding the cost
threshold, no runtime checks are generated and we must not proceed
assuming checks have been generated.

Mark the checks as never succeeding, to make sure we don't try to
vectorize assuming the runtime checks hold. This fixes a case where we
previously incorrectly vectorized assuming runtime checks had been
generated when forcing vectorization via metadate.

Fixes the mis-compile mentioned in
https://github.com/llvm/llvm-project/pull/166247#issuecomment-3631471588
2025-12-09 20:37:21 +00:00
BaiXilin
4f79552d25
[x86][AVX-VNNI] Fix VPDPWXXD Argument Types (#169456)
Fixed the argument types of the following intrinsics to match with the
ISA:
 - vpdpwssd_128, vpdpwssd_256, vpdpwssd_512,
 - vpdpwssds_128, vpdpwssds_256, vpdpwssds_512
 - vpdpwsud_128, vpdpwsud_256, vpdowsud_512
 - vpdpwsuds_128, vpdpwsuds_256, vpdpwsuds_512
 - vpdpwusd_128, vpdpwusd_256, vpdpwusd_512
 - vpdpwusds_128, vpdpwusds_256, vpdpwusds_512
 - vpdpwuud_128, vpdpwuud_256, vpdpwuud_512
 - vpdpwuuds_128, vpdpwuuds_256, vpdpwuuds_512

Fixes #97271. Note that this is the last PR for the issue.
2025-12-09 17:10:20 +00:00
Florian Hahn
c61a481a23
[VPlan] Use SCEV to prove non-aliasing for stores at different offsets. (#170347)
Extend the logic add in https://github.com/llvm/llvm-project/pull/168771
to also allow sinking stores past stores in the same noalias set by
checking if we can prove no-alias via the distance between accesses,
checked via SCEV.

PR: https://github.com/llvm/llvm-project/pull/170347
2025-12-09 16:19:13 +00:00
valadaptive
7f2bbba60d
[AArch64][ARM] Optimize more tbl/tbx calls into shufflevector (#169748)
Resolves #169701.

This PR extends the existing InstCombine operation which folds `tbl1`
intrinsics to `shufflevector` if the mask operand is constant. Before
this change, it only handled 64-bit `tbl1` intrinsics with no
out-of-bounds indices. I've extended it to support both 64-bit and
128-bit vectors, and it now handles the full range of `tbl1`-`tbl4` and
`tbx1`-`tbx4`, as long as at most two of the input operands are actually
indexed into.

For the purposes of `tbl`, we need a dummy vector of zeroes if there are
any out-of-bounds indices, and for the purposes of `tbx`, we use the
"fallback" operand. Both of those take up an operand for the purposes of
`shufflevector`.

This works a lot like https://github.com/llvm/llvm-project/pull/169110,
with some added complexity because we need to handle multiple operands.
I raised a couple questions in that PR that still need to be answered:
- Is it correct to check `IsA<UndefValue>` for each mask index, and set
the output mask index to -1 if so? This is later folded to a poison
value, and I'm not sure about the subtle differences between poison and
undef and when you can substitute one for the other. As I mentioned in
#169110, the existing x86 pass (`simplifyX86vpermilvar`) already behaves
this way when it comes to undef.
- How can I write an Alive2 proof for this? It's very hard to find good
documentation or tutorials about Alive2.

As with #169110, most of the regression test cases were generated using
Claude. Everything else was written by me.
2025-12-09 16:11:26 +00:00
Nikita Popov
6960b633ee [LSR] Use getSigned() for negated immediate 2025-12-09 16:19:36 +01:00
Nikita Popov
cf9ba401e3 [BypassSlowDivision] Explicitly create bit mask
Explicitly create the high bit mask using getBitsSetFrom() instead
of inverting an integer. This avoids relying on implicit
truncation.
2025-12-09 16:13:59 +01:00
Fabrice de Gans
d478baa238
Add more missing LLVM_ABI annotations (#168765)
This patch updates various LLVM headers to properly add the `LLVM_ABI`
and `LLVM_ABI_FOR_TEST` annotations ot build LLVM as a DLL on Windows.

This effort is tracked in #109483.
2025-12-09 09:03:15 -05:00
Alexandros Lamprineas
1b82c16fa8
[FMV][AArch64] Allow user to override version priority. (#150267)
Implements https://github.com/ARM-software/acle/pull/404

This allows the user to specify "featA+featB;priority=[1-255]" where
priority=255 means highest priority. If the explicit priority string is
omitted then the priority of "featA+featB" is implied, which is lower
than priority=1.

Internally this gets expanded using special FMV features P0 ... P7 which
can encode up to 256-1 priority levels (excluding all zeros). Those do
not have corresponding detection bit at pos FEAT_#enum so I made this
field optional in FMVInfo. Also they don't affect the codegen or name
mangling of versioned functions.
2025-12-09 13:31:10 +00:00
Florian Hahn
0768068ff0
[VPlan] Remove ExtractLastLane for plans with scalar VFs. (#171145)
ExtractLastLane is a no-op for scalar VFs. Update simplifyRecipe to
remove them. This also requires adjusting the code in VPlanUnroll.cpp to
split off handling of ExtractLastLane/ExtractPenultimateElement for
scalar VFs, which now needs to match ExtractLastPart.

PR: https://github.com/llvm/llvm-project/pull/171145
2025-12-09 11:59:40 +00:00
Fabrice de Gans
ca9f43fe15
llvm: Export EliminateNewDuplicatePHINodes (#169564)
This is needed for tests, when building with `LLVM_BUILD_LLVM_DYLIB` so
LLVM can be built as a DLL on Windows.

This effort is tracked in #109483.
2025-12-09 06:37:36 -05:00
Nikita Popov
86755dd0bf [llvm] Use ConstantInt::getAllOnesValue()
Prefer getAllOnesValue() over get(-1). This is good practice to
avoid issues with sign extension for large types.
2025-12-09 12:02:39 +01:00
Pengcheng Wang
1ef0a56b55
[LV][NFC] Use foldTailWithEVL() (#171282) 2025-12-09 16:58:53 +08:00
Luke Lau
0fbb45e7d6 [LV] Return getPredBlockCostDivisor in uint64_t
When the probability of a block is extremely low, HeaderFreq / BBFreq
may be larger than 32 bits. Previously this got truncated to uint32_t
which could cause division by zero exceptions on x86. Widen the return
type to uint64_t which should fit the entire range of BlockFrequency
values.

It's also worth noting that a frequency can never be zero according to
BlockFrequency.h, so we shouldn't need to worry about divide by zero in
getPredBlockCostDivisor itself.
2025-12-09 15:43:13 +08:00
Nikita Popov
d46d99cb41
[InferAlign] Eliminate and ptr, -align pattern (#171147)
To complement the `and ptr, align-1 -> 0` pattern, also fold
`and ptr, -align` to `ptr`.

Proof: https://alive2.llvm.org/ce/z/TbeG6d
2025-12-09 08:04:30 +01:00
Mircea Trofin
93c7ad1880
[LTT] Bias branch weights as "expected" when lowering type tests with conditional (#170752)
We expect the type test to succeed.
2025-12-08 21:02:23 -08:00
Fei Peng
f803e463f9
Reland "Redesign Straight-Line Strength Reduction (SLSR) (#162930)" (#169614)
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.
- **Correctness enhencment**
- Fix a correctness issue that reusing instructions with the same SCEV
may introduce poison.

---------

Co-authored-by: Kazu Hirata <kazu@google.com>
2025-12-08 16:07:27 -06:00