[llvm] [LoopVectorize][X86] Rewrite guaranteed-safe masked stores as load-blend-store] (PR #206654)
Arjun H Kumar via llvm-commits
llvm-commits at lists.llvm.org
Mon Jun 29 23:36:44 PDT 2026
https://github.com/arjun-harikumar-amd created https://github.com/llvm/llvm-project/pull/206654
None
>From 72d3b2677ac6be1632fa3ab5a3befd7d6249e332 Mon Sep 17 00:00:00 2001
From: Arjun H Kumar <Arjun.HKumar at amd.com>
Date: Tue, 30 Jun 2026 11:44:22 +0530
Subject: [PATCH 1/2] [LoopVectorize][X86] Rewrite guaranteed-safe masked
stores as load-blend-store]
---
.../include/llvm/Analysis/MemSafetyAnalysis.h | 121 +++++++++
.../llvm/Analysis/TargetTransformInfo.h | 8 +
.../llvm/Analysis/TargetTransformInfoImpl.h | 4 +
llvm/lib/Analysis/CMakeLists.txt | 1 +
llvm/lib/Analysis/MemSafetyAnalysis.cpp | 237 ++++++++++++++++++
llvm/lib/Analysis/TargetTransformInfo.cpp | 4 +
llvm/lib/Target/X86/X86.td | 13 +-
.../lib/Target/X86/X86TargetTransformInfo.cpp | 8 +
llvm/lib/Target/X86/X86TargetTransformInfo.h | 2 +
.../Transforms/Vectorize/LoopVectorize.cpp | 67 ++++-
llvm/lib/Transforms/Vectorize/VPlan.h | 26 +-
.../lib/Transforms/Vectorize/VPlanRecipes.cpp | 34 ++-
.../optimize-masked-memory/mode-a-flag-off.ll | 42 ++++
.../mode-a-guaranteed-safe.ll | 44 ++++
.../mode-a-non-guaranteed.ll | 40 +++
.../scatter-untouched.ll | 42 ++++
16 files changed, 684 insertions(+), 9 deletions(-)
create mode 100644 llvm/include/llvm/Analysis/MemSafetyAnalysis.h
create mode 100644 llvm/lib/Analysis/MemSafetyAnalysis.cpp
create mode 100644 llvm/test/Transforms/LoopVectorize/X86/optimize-masked-memory/mode-a-flag-off.ll
create mode 100644 llvm/test/Transforms/LoopVectorize/X86/optimize-masked-memory/mode-a-guaranteed-safe.ll
create mode 100644 llvm/test/Transforms/LoopVectorize/X86/optimize-masked-memory/mode-a-non-guaranteed.ll
create mode 100644 llvm/test/Transforms/LoopVectorize/X86/optimize-masked-memory/scatter-untouched.ll
diff --git a/llvm/include/llvm/Analysis/MemSafetyAnalysis.h b/llvm/include/llvm/Analysis/MemSafetyAnalysis.h
new file mode 100644
index 0000000000000..baa47f70a6d39
--- /dev/null
+++ b/llvm/include/llvm/Analysis/MemSafetyAnalysis.h
@@ -0,0 +1,121 @@
+//===- MemSafetyAnalysis.h - Memory access safety for a loop ----*- C++ -*-===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Originally developed by Advanced Micro Devices, Inc. (2015).
+//
+// MemSafetyAnalysis answers one question about a loop's memory accesses:
+//
+// "Is this memory access guaranteed to execute on every iteration of the
+// loop?" -- isGuaranteedMemoryAccess(const SCEV *)
+//
+// Used to legalise rewriting a masked store as load-blend-store: if the
+// same SCEV-keyed address is touched on every iteration anyway, the
+// sequence does not introduce any new fault.
+//
+// The analysis is built once per loop and consulted from the loop vectoriser
+// when -enable-masked-memory-optimization is in effect.
+//
+// Phase-2 (stack-alloca padding) is layered on top of this analysis in a
+// follow-up patch; the ctor here keeps the TLI/TTI parameters that Phase-2
+// will use, so the analysis-construction call site does not have to change.
+//
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_ANALYSIS_MEMSAFETYANALYSIS_H
+#define LLVM_ANALYSIS_MEMSAFETYANALYSIS_H
+
+#include "llvm/ADT/SmallPtrSet.h"
+#include "llvm/IR/Value.h"
+#include <map>
+
+namespace llvm {
+
+class BasicBlock;
+class DominatorTree;
+class Loop;
+class LoopInfo;
+class ScalarEvolution;
+class SCEV;
+class TargetLibraryInfo;
+class TargetTransformInfo;
+
+/// Classification of a per-block memory access. \c LocalSafe means the access
+/// has been observed but not yet proven to execute on every iteration of the
+/// enclosing loop; \c Safe means the access is proven to execute on every
+/// iteration; \c Unsafe is reserved for future use.
+enum class MemProperty { Unsafe, Safe, LocalSafe };
+
+/// Per-block summary of memory accesses, indexed by the SCEV of the pointer.
+class BlockMemInfo {
+public:
+ BasicBlock *BB;
+ bool GuaranteedToExecute;
+ std::map<const SCEV *, MemProperty> BlockMemAccess;
+
+ BlockMemInfo(BasicBlock *BB, bool GuaranteedToExecute)
+ : BB(BB), GuaranteedToExecute(GuaranteedToExecute) {}
+
+ void addMemoryAccess(const SCEV *S, MemProperty AccessTy);
+ bool isBlockGuaranteedToExecute() const { return GuaranteedToExecute; }
+ void copyBlockMemInfo(BlockMemInfo *BMI);
+};
+
+/// MemSafetyAnalysis -- per-loop analysis that builds a SCEV-keyed map of
+/// memory accesses guaranteed to execute on every iteration.
+///
+/// A memory access is guaranteed to execute when either:
+/// * it lives in a block that dominates the latch (top-level block), or
+/// * the same SCEV-keyed address is touched on every path of the
+/// subtree rooted at the current block (propagated bottom-up).
+///
+/// See `examples` block in MemSafetyAnalysis.cpp for canonical cases.
+class MemSafetyAnalysis {
+public:
+ MemSafetyAnalysis(Loop *L, LoopInfo *LI, ScalarEvolution *SE,
+ DominatorTree *DT, const TargetLibraryInfo *TLI,
+ const TargetTransformInfo *TTI);
+ ~MemSafetyAnalysis();
+
+ MemSafetyAnalysis(const MemSafetyAnalysis &) = delete;
+ MemSafetyAnalysis &operator=(const MemSafetyAnalysis &) = delete;
+
+ /// True if the analysis successfully ran on the loop. Clients must check
+ /// this before consulting the other queries.
+ bool isLegalAnalysis() const { return IsAnalysisValid; }
+
+ /// True if the access at SCEV \p S is guaranteed to execute on every
+ /// iteration of the loop body.
+ bool isGuaranteedMemoryAccess(const SCEV *S) const;
+
+ /// Debug: dump the analysis state to dbgs().
+ void printAnalysis() const;
+
+private:
+ Loop *L;
+ LoopInfo *LI;
+ ScalarEvolution *SE;
+ DominatorTree *DT;
+ const TargetLibraryInfo *TLI;
+ const TargetTransformInfo *TTI;
+ bool IsAnalysisValid = false;
+
+ std::map<BasicBlock *, BlockMemInfo *> BlockMemAccessMap;
+ std::map<const SCEV *, MemProperty> SafeMemoryAccesses;
+
+ BlockMemInfo *getBlockMemInfo(BasicBlock *BB);
+ bool blockGuaranteedToExecute(BasicBlock *BB);
+ void addGuaranteedMemoryAccess(const SCEV *S);
+ bool isLegalLoopStructure();
+ bool processBlock(BasicBlock *BB);
+ bool analyzeMemoryAccessesInLoop();
+ void clearLocalMemory();
+};
+
+} // namespace llvm
+
+#endif // LLVM_ANALYSIS_MEMSAFETYANALYSIS_H
diff --git a/llvm/include/llvm/Analysis/TargetTransformInfo.h b/llvm/include/llvm/Analysis/TargetTransformInfo.h
index 10c0509460b95..bacf4545966b5 100644
--- a/llvm/include/llvm/Analysis/TargetTransformInfo.h
+++ b/llvm/include/llvm/Analysis/TargetTransformInfo.h
@@ -1163,6 +1163,14 @@ class TargetTransformInfo {
/// vector loads/stores.
LLVM_ABI bool enableMaskedInterleavedAccessVectorization() const;
+ /// Return true if a masked store whose pointer is provably touched on every
+ /// loop iteration should be rewritten as an unconditional load + select +
+ /// unconditional store. Targets with a microcoded / slow masked-store path
+ /// (e.g. AMD znver1/2/3) should return true. Returning false leaves the
+ /// masked store untouched. Consulted by LoopVectorize when
+ /// -enable-masked-memory-optimization is on.
+ LLVM_ABI bool shouldRewriteMaskedStoreAsLoadBlendStore() const;
+
/// Indicate that it is potentially unsafe to automatically vectorize
/// floating-point operations because the semantics of vector and scalar
/// floating-point semantics may differ. For example, ARM NEON v7 SIMD math
diff --git a/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h b/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h
index 5645cc63a6944..a391f23569757 100644
--- a/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h
+++ b/llvm/include/llvm/Analysis/TargetTransformInfoImpl.h
@@ -553,6 +553,10 @@ class LLVM_ABI TargetTransformInfoImplBase {
return false;
}
+ virtual bool shouldRewriteMaskedStoreAsLoadBlendStore() const {
+ return false;
+ }
+
virtual bool isFPVectorizationPotentiallyUnsafe() const { return false; }
virtual bool allowsMisalignedMemoryAccesses(LLVMContext &Context,
diff --git a/llvm/lib/Analysis/CMakeLists.txt b/llvm/lib/Analysis/CMakeLists.txt
index f3586c66cb056..47f9a14180ad9 100644
--- a/llvm/lib/Analysis/CMakeLists.txt
+++ b/llvm/lib/Analysis/CMakeLists.txt
@@ -115,6 +115,7 @@ add_llvm_component_library(LLVMAnalysis
LoopPass.cpp
MLInlineAdvisor.cpp
MemDerefPrinter.cpp
+ MemSafetyAnalysis.cpp
MemoryBuiltins.cpp
MemoryDependenceAnalysis.cpp
MemoryLocation.cpp
diff --git a/llvm/lib/Analysis/MemSafetyAnalysis.cpp b/llvm/lib/Analysis/MemSafetyAnalysis.cpp
new file mode 100644
index 0000000000000..3b86203c81723
--- /dev/null
+++ b/llvm/lib/Analysis/MemSafetyAnalysis.cpp
@@ -0,0 +1,237 @@
+//===- MemSafetyAnalysis.cpp - Memory access safety for a loop ------------===//
+//
+// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
+// See https://llvm.org/LICENSE.txt for license information.
+// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
+//
+//===----------------------------------------------------------------------===//
+//
+// Originally developed by Advanced Micro Devices, Inc. (2015).
+//
+// MemSafetyAnalysis identifies memory accesses that are guaranteed to execute
+// on every dynamic iteration of the loop body.
+//
+// Guaranteed-access classification:
+// Case#1: P is accessed in a top-level block (one that dominates the latch)
+// loop {
+// if (C1) *P;
+// else { if (C2) *P; else ... }
+// *P; // <-- top-level
+// }
+//
+// Case#2: P is accessed on every successor path of a top-level subtree
+// loop {
+// if (C1) *P;
+// else { if (C2) *P; else *P; } // both branches touch *P
+// }
+//
+// Case#3: P is not accessed on some path -- not guaranteed
+// loop {
+// if (C1) *P;
+// else { if (C2) *P; else { if (C3) *P; else /* no access */ } }
+// }
+//
+// See MemSafetyAnalysis.h for the public API.
+//
+//===----------------------------------------------------------------------===//
+
+#include "llvm/Analysis/MemSafetyAnalysis.h"
+#include "llvm/Analysis/LoopInfo.h"
+#include "llvm/Analysis/LoopIterator.h"
+#include "llvm/Analysis/ScalarEvolution.h"
+#include "llvm/IR/BasicBlock.h"
+#include "llvm/IR/Dominators.h"
+#include "llvm/IR/InstIterator.h"
+#include "llvm/IR/Instructions.h"
+#include "llvm/Support/Debug.h"
+#include "llvm/Support/raw_ostream.h"
+#include <stack>
+
+using namespace llvm;
+
+#define DEBUG_TYPE "mem-access-safety"
+
+//===----------------------------------------------------------------------===//
+// BlockMemInfo
+//===----------------------------------------------------------------------===//
+
+void BlockMemInfo::addMemoryAccess(const SCEV *S, MemProperty AccessTy) {
+ BlockMemAccess[S] = AccessTy;
+}
+
+void BlockMemInfo::copyBlockMemInfo(BlockMemInfo *BMI) {
+ for (auto &Itr : BMI->BlockMemAccess)
+ BlockMemAccess[Itr.first] = Itr.second;
+}
+
+//===----------------------------------------------------------------------===//
+// MemSafetyAnalysis
+//===----------------------------------------------------------------------===//
+
+MemSafetyAnalysis::MemSafetyAnalysis(Loop *L, LoopInfo *LI, ScalarEvolution *SE,
+ DominatorTree *DT,
+ const TargetLibraryInfo *TLI,
+ const TargetTransformInfo *TTI)
+ : L(L), LI(LI), SE(SE), DT(DT), TLI(TLI), TTI(TTI) {
+ if (isLegalLoopStructure())
+ analyzeMemoryAccessesInLoop();
+}
+
+MemSafetyAnalysis::~MemSafetyAnalysis() {
+ // BlockMemAccessMap is cleared as part of analyzeMemoryAccessesInLoop's
+ // tail; no-op here if it already ran.
+ clearLocalMemory();
+}
+
+bool MemSafetyAnalysis::isLegalLoopStructure() {
+ if (!L->getLoopLatch())
+ return false;
+ if (!L->getSubLoops().empty())
+ return false;
+ if (L->getNumBackEdges() != 1)
+ return false;
+ if (!L->getExitingBlock())
+ return false;
+ if (L->getExitingBlock() != L->getLoopLatch())
+ return false;
+ return true;
+}
+
+void MemSafetyAnalysis::clearLocalMemory() {
+ for (auto &Itr : BlockMemAccessMap)
+ delete Itr.second;
+ BlockMemAccessMap.clear();
+}
+
+void MemSafetyAnalysis::addGuaranteedMemoryAccess(const SCEV *S) {
+ SafeMemoryAccesses[S] = MemProperty::Safe;
+}
+
+bool MemSafetyAnalysis::isGuaranteedMemoryAccess(const SCEV *S) const {
+ auto Itr = SafeMemoryAccesses.find(S);
+ if (Itr == SafeMemoryAccesses.end() || Itr->second != MemProperty::Safe)
+ return false;
+ return true;
+}
+
+bool MemSafetyAnalysis::blockGuaranteedToExecute(BasicBlock *BB) {
+ return DT->dominates(BB, L->getLoopLatch());
+}
+
+BlockMemInfo *MemSafetyAnalysis::getBlockMemInfo(BasicBlock *BB) {
+ auto Itr = BlockMemAccessMap.find(BB);
+ if (Itr != BlockMemAccessMap.end())
+ return Itr->second;
+ auto *BMI = new BlockMemInfo(BB, blockGuaranteedToExecute(BB));
+ BlockMemAccessMap[BB] = BMI;
+ return BMI;
+}
+
+bool MemSafetyAnalysis::processBlock(BasicBlock *BB) {
+ Instruction *Term = BB->getTerminator();
+ BlockMemInfo *BMI = getBlockMemInfo(BB);
+
+ if (auto *CB = dyn_cast<CondBrInst>(Term)) {
+ BlockMemInfo *Succ0BMI = getBlockMemInfo(CB->getSuccessor(0));
+ BlockMemInfo *Succ1BMI = getBlockMemInfo(CB->getSuccessor(1));
+ // Case#2: an access registered as LocalSafe on both successors gets
+ // promoted to Safe on the current block, and to a loop-level guaranteed
+ // access if the current block is itself guaranteed.
+ for (auto &Itr0 : Succ0BMI->BlockMemAccess) {
+ for (auto &Itr1 : Succ1BMI->BlockMemAccess) {
+ if (Itr0.first != Itr1.first)
+ continue;
+ if (Itr0.second != MemProperty::LocalSafe ||
+ Itr1.second != MemProperty::LocalSafe)
+ continue;
+ if (BMI->isBlockGuaranteedToExecute()) {
+ BMI->addMemoryAccess(Itr0.first, MemProperty::Safe);
+ addGuaranteedMemoryAccess(Itr0.first);
+ } else {
+ BMI->addMemoryAccess(Itr0.first, MemProperty::LocalSafe);
+ }
+ }
+ }
+ } else if (auto *UB = dyn_cast<UncondBrInst>(Term)) {
+ BlockMemInfo *Succ0BMI = getBlockMemInfo(UB->getSuccessor(0));
+ BMI->copyBlockMemInfo(Succ0BMI);
+ } else {
+ // Not a branch terminator (return, unreachable, switch, indirectbr,
+ // resume, ...) -- bail out and let the analysis stay invalid.
+ return false;
+ }
+
+ // Now register the block's own accesses.
+ for (auto &I : *BB) {
+ Value *Ptr = nullptr;
+ if (auto *Ld = dyn_cast<LoadInst>(&I)) {
+ if (!Ld->isSimple())
+ continue;
+ Ptr = Ld->getPointerOperand();
+ } else if (auto *St = dyn_cast<StoreInst>(&I)) {
+ if (!St->isSimple())
+ continue;
+ Ptr = St->getPointerOperand();
+ } else {
+ continue;
+ }
+
+ const SCEV *PtrSCEV = SE->getSCEV(Ptr);
+ if (isGuaranteedMemoryAccess(PtrSCEV)) {
+ BMI->addMemoryAccess(PtrSCEV, MemProperty::Safe);
+ continue;
+ }
+ if (BMI->isBlockGuaranteedToExecute()) {
+ addGuaranteedMemoryAccess(PtrSCEV);
+ BMI->addMemoryAccess(PtrSCEV, MemProperty::Safe);
+ continue;
+ }
+ BMI->addMemoryAccess(PtrSCEV, MemProperty::LocalSafe);
+ }
+ return true;
+}
+
+bool MemSafetyAnalysis::analyzeMemoryAccessesInLoop() {
+ LoopBlocksRPO RPOT(L);
+ RPOT.perform(LI);
+ // Bottom-up traversal: process a block after its successors so that
+ // Case#2 propagation has the successor info ready.
+ std::stack<BasicBlock *> WorkList;
+ for (BasicBlock *BB : RPOT)
+ WorkList.push(BB);
+ while (!WorkList.empty()) {
+ if (!processBlock(WorkList.top())) {
+ clearLocalMemory();
+ return false;
+ }
+ WorkList.pop();
+ }
+ IsAnalysisValid = true;
+ clearLocalMemory();
+ return true;
+}
+
+void MemSafetyAnalysis::printAnalysis() const {
+ LLVM_DEBUG(dbgs() << "MemSafetyAnalysis\n");
+ for (auto *Block : L->getBlocks()) {
+ for (auto &Inst : *Block) {
+ Value *Ptr = nullptr;
+ if (auto *Ld = dyn_cast<LoadInst>(&Inst)) {
+ if (!Ld->isSimple())
+ continue;
+ Ptr = Ld->getPointerOperand();
+ } else if (auto *St = dyn_cast<StoreInst>(&Inst)) {
+ if (!St->isSimple())
+ continue;
+ Ptr = St->getPointerOperand();
+ } else {
+ continue;
+ }
+ const SCEV *PtrSCEV = SE->getSCEV(Ptr);
+ if (isGuaranteedMemoryAccess(PtrSCEV)) {
+ LLVM_DEBUG(dbgs() << " [Guaranteed]: " << Inst
+ << " SCEV: " << *PtrSCEV << "\n");
+ }
+ }
+ }
+}
diff --git a/llvm/lib/Analysis/TargetTransformInfo.cpp b/llvm/lib/Analysis/TargetTransformInfo.cpp
index cdccd04f4c9ea..084fd5680c1c5 100644
--- a/llvm/lib/Analysis/TargetTransformInfo.cpp
+++ b/llvm/lib/Analysis/TargetTransformInfo.cpp
@@ -720,6 +720,10 @@ bool TargetTransformInfo::enableMaskedInterleavedAccessVectorization() const {
return TTIImpl->enableMaskedInterleavedAccessVectorization();
}
+bool TargetTransformInfo::shouldRewriteMaskedStoreAsLoadBlendStore() const {
+ return TTIImpl->shouldRewriteMaskedStoreAsLoadBlendStore();
+}
+
bool TargetTransformInfo::isFPVectorizationPotentiallyUnsafe() const {
return TTIImpl->isFPVectorizationPotentiallyUnsafe();
}
diff --git a/llvm/lib/Target/X86/X86.td b/llvm/lib/Target/X86/X86.td
index 9e833344e7341..9623d5c4ce2ea 100644
--- a/llvm/lib/Target/X86/X86.td
+++ b/llvm/lib/Target/X86/X86.td
@@ -502,6 +502,13 @@ def TuningSlowSHLD : SubtargetFeature<"slow-shld", "IsSHLDSlow", "true",
"SHLD instruction is slow",
[], InlineIgnore>;
+def TuningSlowMaskedStore
+ : SubtargetFeature<"slow-masked-store", "HasSlowMaskedStore", "true",
+ "Variable-mask vector store is microcoded / slow "
+ "(e.g. AMD znver1/2/3 vmaskmovps/vpmaskmovd path); "
+ "prefer rewriting safe masked stores as unconditional "
+ "load+select+store">;
+
def TuningSlowPMULLD : SubtargetFeature<"slow-pmulld", "IsPMULLDSlow", "true",
"PMULLD instruction is slow (compared to PMULLW/PMULHW and PMULUDQ)",
[], InlineIgnore>;
@@ -1679,6 +1686,7 @@ def ProcessorFeatures {
TuningFastImm16,
TuningSlowDivide64,
TuningSlowSHLD,
+ TuningSlowMaskedStore,
TuningSBBDepBreaking,
TuningInsertVZEROUPPER,
TuningAllowLight256Bit];
@@ -1701,8 +1709,11 @@ def ProcessorFeatures {
!listconcat(ZN2Features, ZN3AdditionalFeatures);
list<SubtargetFeature> ZN4AdditionalTuning = [TuningFastDPWSSD];
+ // znver4 (and later) has first-class AVX-512 masked-store hardware; drop the
+ // tuning that says variable-mask stores are slow.
list<SubtargetFeature> ZN4Tuning =
- !listconcat(ZN3Tuning, ZN4AdditionalTuning);
+ !listremove(!listconcat(ZN3Tuning, ZN4AdditionalTuning),
+ [TuningSlowMaskedStore]);
list<SubtargetFeature> ZN4AdditionalFeatures = [FeatureAVX512,
FeatureCDI,
FeatureDQI,
diff --git a/llvm/lib/Target/X86/X86TargetTransformInfo.cpp b/llvm/lib/Target/X86/X86TargetTransformInfo.cpp
index 8838fd7e71f02..60f5a72357c84 100644
--- a/llvm/lib/Target/X86/X86TargetTransformInfo.cpp
+++ b/llvm/lib/Target/X86/X86TargetTransformInfo.cpp
@@ -6851,6 +6851,14 @@ bool X86TTIImpl::enableInterleavedAccessVectorization() const {
return !(ST->isAtom());
}
+bool X86TTIImpl::shouldRewriteMaskedStoreAsLoadBlendStore() const {
+ // Driven by the X86 tuning feature `slow-masked-store`, which is set on
+ // znver1/znver2/znver3 (the AMD Zen generations whose variable-mask vector
+ // store path is microcoded). znver4 and later have first-class AVX-512
+ // masked stores and therefore opt out via X86.td.
+ return ST->hasSlowMaskedStore();
+}
+
bool X86TTIImpl::shouldExpandReduction(const IntrinsicInst *II) const {
switch (II->getIntrinsicID()) {
default:
diff --git a/llvm/lib/Target/X86/X86TargetTransformInfo.h b/llvm/lib/Target/X86/X86TargetTransformInfo.h
index 22171f5469d98..e023b7104fa9c 100644
--- a/llvm/lib/Target/X86/X86TargetTransformInfo.h
+++ b/llvm/lib/Target/X86/X86TargetTransformInfo.h
@@ -252,6 +252,8 @@ class X86TTIImpl final : public BasicTTIImplBase<X86TTIImpl> {
bool supportsEfficientVectorElementLoadStore() const override;
bool enableInterleavedAccessVectorization() const override;
+ bool shouldRewriteMaskedStoreAsLoadBlendStore() const override;
+
bool shouldExpandReduction(const IntrinsicInst *II) const override;
InstructionCost getBranchMispredictPenalty() const override;
diff --git a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
index f1ca4061bfd9e..610ae57774dc7 100644
--- a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
+++ b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
@@ -89,6 +89,7 @@
#include "llvm/Analysis/LoopAnalysisManager.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/LoopIterator.h"
+#include "llvm/Analysis/MemSafetyAnalysis.h"
#include "llvm/Analysis/OptimizationRemarkEmitter.h"
#include "llvm/Analysis/ProfileSummaryInfo.h"
#include "llvm/Analysis/ScalarEvolution.h"
@@ -178,6 +179,17 @@ static cl::opt<bool> EnableEpilogueVectorization(
"enable-epilogue-vectorization", cl::init(true), cl::Hidden,
cl::desc("Enable vectorization of epilogue loops."));
+// OptimizeMaskedMemory: rewrite masked stores as a load-blend-store sequence
+// when MemSafetyAnalysis proves the access is safe. On by default, but
+// further gated by TTI: only fires on targets whose
+// shouldRewriteMaskedStoreAsLoadBlendStore() returns true (today: X86 with
+// the slow-masked-store tuning feature, i.e. znver1/2/3). All other targets
+// see no IR change regardless of this flag's value.
+static cl::opt<bool> EnableOptimizeMaskedMemory(
+ "enable-masked-memory-optimization", cl::init(true), cl::Hidden,
+ cl::desc("Rewrite masked stores as load-blend-store when safe "
+ "(MemSafetyAnalysis-driven)."));
+
static cl::opt<unsigned> EpilogueVectorizationForceVF(
"epilogue-vectorization-force-VF", cl::init(1), cl::Hidden,
cl::desc("When epilogue vectorization is enabled, and a value greater than "
@@ -790,6 +802,16 @@ class LoopVectorizationCostModel {
LI(LI), Legal(Legal), TTI(TTI), TLI(TLI), AC(AC), ORE(ORE),
GetBFI(GetBFI), TheFunction(F), Hints(Hints), InterleaveInfo(IAI) {}
+ /// OptimizeMaskedMemory: per-loop analysis used by the load-blend-store
+ /// rewrite. Set by LoopVectorizePass::processLoop after legality succeeds;
+ /// null when -enable-masked-memory-optimization is off or the analysis is
+ /// not legal on this loop.
+ MemSafetyAnalysis *MSA = nullptr;
+
+ /// Attach a MemSafetyAnalysis to this cost model. Lifetime is owned by
+ /// the caller.
+ void setMSA(MemSafetyAnalysis *NewMSA) { MSA = NewMSA; }
+
/// \return An upper bound for the vectorization factors (both fixed and
/// scalable). If the factors are 0, vectorization and interleaving should be
/// avoided up front.
@@ -6238,8 +6260,38 @@ VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(VPInstruction *VPI,
if (Reverse)
StoredVal = Builder.createNaryOp(VPInstruction::Reverse, StoredVal,
Store->getDebugLoc());
- return new VPWidenStoreRecipe(*Store, Ptr, StoredVal, Mask, Consecutive, *VPI,
- Store->getDebugLoc());
+ auto *NewSR = new VPWidenStoreRecipe(*Store, Ptr, StoredVal, Mask, Consecutive,
+ *VPI, Store->getDebugLoc());
+
+ // OptimizeMaskedMemory: decide once, at recipe-build time, whether this
+ // masked store will be lowered as a load-blend-store. The decision is
+ // recorded on the recipe so that both the cost model and the execute path
+ // can consult the same answer.
+ //
+ // Gating:
+ // 1. The target must say it benefits from the rewrite. The TTI hook
+ // is target-specific (X86 turns it on only for znver1/2/3 via the
+ // `slow-masked-store` tuning feature); other targets and AVX-512
+ // class chips fall through to the masked-store path untouched.
+ // 2. -enable-masked-memory-optimization must be on (CM.MSA is otherwise
+ // null).
+ // 3. The store must be masked, consecutive, non-reverse: scatters and
+ // reversed stores stay on the masked-store path.
+ // 4. The loop must not be tail-folded by masking. With tail-folding the
+ // mask gates past-end addresses on the trailing iterations and the
+ // load-blend-store would over-read.
+ // 5. MemSafetyAnalysis must prove the access is guaranteed to execute
+ // on every iteration of the loop body.
+ if (CM.TTI.shouldRewriteMaskedStoreAsLoadBlendStore() &&
+ Mask && Consecutive && !Reverse && CM.MSA &&
+ CM.MSA->isLegalAnalysis() && !CM.foldTailByMasking()) {
+ auto *SE = Legal->getScalarEvolution();
+ const SCEV *PtrSCEV = SE->getSCEV(Store->getPointerOperand());
+ if (CM.MSA->isGuaranteedMemoryAccess(PtrSCEV))
+ NewSR->setRewriteAsLoadBlendStore();
+ }
+
+ return NewSR;
}
VPWidenIntOrFpInductionRecipe *
@@ -8050,6 +8102,17 @@ bool LoopVectorizePass::processLoop(Loop *L) {
OptForSize);
LoopVectorizationCostModel CM(SEL, L, PSE, LI, &LVL, *TTI, TLI, AC, ORE,
GetBFI, F, &Hints, IAI, Config);
+
+ // OptimizeMaskedMemory: build the per-loop MemSafetyAnalysis once. Its
+ // lifetime extends until the end of processLoop, covering both planning
+ // and execute. The CM holds a non-owning pointer to it.
+ std::unique_ptr<MemSafetyAnalysis> MSA;
+ if (IsInnerLoop && EnableOptimizeMaskedMemory) {
+ MSA = std::make_unique<MemSafetyAnalysis>(L, LI, PSE.getSE(), DT, TLI, TTI);
+ if (MSA->isLegalAnalysis())
+ CM.setMSA(MSA.get());
+ }
+
// Use the planner for vectorization.
LoopVectorizationPlanner LVP(L, LI, DT, TLI, *TTI, &LVL, CM, Config, IAI, PSE,
Hints, ORE);
diff --git a/llvm/lib/Transforms/Vectorize/VPlan.h b/llvm/lib/Transforms/Vectorize/VPlan.h
index eaf9d1433aff7..ddfc43ca33571 100644
--- a/llvm/lib/Transforms/Vectorize/VPlan.h
+++ b/llvm/lib/Transforms/Vectorize/VPlan.h
@@ -3906,9 +3906,12 @@ struct LLVM_ABI_FOR_TEST VPWidenStoreRecipe final : public VPRecipeBase,
}
VPWidenStoreRecipe *clone() override {
- return new VPWidenStoreRecipe(cast<StoreInst>(Ingredient), getAddr(),
- getStoredValue(), getMask(), Consecutive,
- *this, getDebugLoc());
+ auto *Copy =
+ new VPWidenStoreRecipe(cast<StoreInst>(Ingredient), getAddr(),
+ getStoredValue(), getMask(), Consecutive, *this,
+ getDebugLoc());
+ Copy->RewriteAsLoadBlendStore = RewriteAsLoadBlendStore;
+ return Copy;
}
VP_CLASSOF_IMPL(VPRecipeBase::VPWidenStoreSC);
@@ -3925,6 +3928,19 @@ struct LLVM_ABI_FOR_TEST VPWidenStoreRecipe final : public VPRecipeBase,
return VPWidenMemoryRecipe::computeCost(VF, Ctx);
}
+ /// OptimizeMaskedMemory: when set, the recipe will emit a
+ /// load-blend-store sequence (load, select-against-mask, plain store)
+ /// instead of a single masked store. Decided at recipe-build time by
+ /// VPRecipeBuilder::tryToWidenMemory after consulting MemSafetyAnalysis;
+ /// see -enable-masked-memory-optimization. The cost model honours the
+ /// same flag so the planner's compare-vs-other-VFs logic stays accurate.
+ void setRewriteAsLoadBlendStore(bool V = true) {
+ RewriteAsLoadBlendStore = V;
+ }
+ bool shouldRewriteAsLoadBlendStore() const {
+ return RewriteAsLoadBlendStore;
+ }
+
/// Returns true if the recipe only uses the first lane of operand \p Op.
bool usesFirstLaneOnly(const VPValue *Op) const override {
assert(is_contained(operands(), Op) &&
@@ -3934,6 +3950,10 @@ struct LLVM_ABI_FOR_TEST VPWidenStoreRecipe final : public VPRecipeBase,
return Op == getAddr() && isConsecutive() && Op != getStoredValue();
}
+private:
+ /// See setRewriteAsLoadBlendStore().
+ bool RewriteAsLoadBlendStore = false;
+
protected:
VPRecipeBase *getAsRecipe() override;
const VPRecipeBase *getAsRecipe() const override;
diff --git a/llvm/lib/Transforms/Vectorize/VPlanRecipes.cpp b/llvm/lib/Transforms/Vectorize/VPlanRecipes.cpp
index f45b9e4f6c35b..010007c6be8ca 100644
--- a/llvm/lib/Transforms/Vectorize/VPlanRecipes.cpp
+++ b/llvm/lib/Transforms/Vectorize/VPlanRecipes.cpp
@@ -4124,6 +4124,22 @@ InstructionCost VPWidenMemoryRecipe::computeCost(ElementCount VF,
InstructionCost Cost = 0;
if (IsMasked) {
+ // OptimizeMaskedMemory: when the masked store will be rewritten as
+ // load-blend-store (see VPWidenStoreRecipe::execute), cost the sequence
+ // accordingly so the planner sees the true cost when comparing VFs.
+ if (auto *Store = dyn_cast<VPWidenStoreRecipe>(R)) {
+ if (Store->shouldRewriteAsLoadBlendStore()) {
+ Cost += Ctx.TTI.getMemoryOpCost(Instruction::Load, Ty, Alignment, AS,
+ Ctx.CostKind);
+ Type *CondTy = VectorType::get(Type::getInt1Ty(Ctx.LLVMCtx), VF);
+ Cost += Ctx.TTI.getCmpSelInstrCost(Instruction::Select, Ty, CondTy,
+ CmpInst::BAD_ICMP_PREDICATE,
+ Ctx.CostKind);
+ Cost += Ctx.TTI.getMemoryOpCost(Instruction::Store, Ty, Alignment, AS,
+ Ctx.CostKind);
+ return Cost;
+ }
+ }
unsigned IID = isa<VPWidenLoadRecipe>(R) ? Intrinsic::masked_load
: Intrinsic::masked_store;
Cost += Ctx.TTI.getMemIntrinsicInstrCost(
@@ -4244,12 +4260,24 @@ void VPWidenStoreRecipe::execute(VPTransformState &State) {
Value *StoredVal = State.get(StoredVPValue);
Value *Addr = State.get(getAddr(), /*IsScalar*/ !CreateScatter);
Instruction *NewSI = nullptr;
- if (CreateScatter)
+ if (CreateScatter) {
NewSI = Builder.CreateMaskedScatter(StoredVal, Addr, Alignment, Mask);
- else if (Mask)
+ } else if (Mask && shouldRewriteAsLoadBlendStore()) {
+ // OptimizeMaskedMemory: emit a load-blend-store sequence instead of a
+ // single masked store. MemSafetyAnalysis already proved that the wide
+ // load and the unconditional store at this address are safe
+ // (guaranteed-execute on every iteration of the loop body).
+ auto *DataTy = cast<VectorType>(StoredVal->getType());
+ auto *Filler =
+ Builder.CreateAlignedLoad(DataTy, Addr, Alignment, "blend.load");
+ Value *Merged =
+ Builder.CreateSelect(Mask, StoredVal, Filler, "blend.sel");
+ NewSI = Builder.CreateAlignedStore(Merged, Addr, Alignment);
+ } else if (Mask) {
NewSI = Builder.CreateMaskedStore(StoredVal, Addr, Alignment, Mask);
- else
+ } else {
NewSI = Builder.CreateAlignedStore(StoredVal, Addr, Alignment);
+ }
applyMetadata(*NewSI);
}
diff --git a/llvm/test/Transforms/LoopVectorize/X86/optimize-masked-memory/mode-a-flag-off.ll b/llvm/test/Transforms/LoopVectorize/X86/optimize-masked-memory/mode-a-flag-off.ll
new file mode 100644
index 0000000000000..191db49cce9f7
--- /dev/null
+++ b/llvm/test/Transforms/LoopVectorize/X86/optimize-masked-memory/mode-a-flag-off.ll
@@ -0,0 +1,42 @@
+; Phase-1 / Mode-A: with -enable-masked-memory-optimization=false the IR
+; keeps its original @llvm.masked.store -- even on a target whose TTI hook
+; (X86 znver3) would otherwise opt in. The cl::opt is one of the gates in
+; tryToWidenMemory; explicitly disabling it must short-circuit the rewrite
+; regardless of the target.
+;
+; RUN: opt < %s -passes=loop-vectorize -mtriple=x86_64-unknown-linux-gnu \
+; RUN: -mcpu=znver3 -enable-masked-memory-optimization=false -S \
+; RUN: | FileCheck %s
+
+target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128"
+
+; CHECK-LABEL: @phase1_off
+; CHECK: call void @llvm.masked.store
+; CHECK-NOT: blend.load
+; CHECK-NOT: blend.sel
+define void @phase1_off(ptr noalias %A, ptr noalias %cond) {
+entry:
+ br label %loop.header
+
+loop.header:
+ %iv = phi i64 [ 0, %entry ], [ %iv.next, %loop.latch ]
+ %gep_cond = getelementptr inbounds i32, ptr %cond, i64 %iv
+ %cv = load i32, ptr %gep_cond, align 4
+ %gep_A = getelementptr inbounds i32, ptr %A, i64 %iv
+ %old = load i32, ptr %gep_A, align 4
+ %cmp = icmp ne i32 %cv, 0
+ br i1 %cmp, label %if.then, label %loop.latch
+
+if.then:
+ %new = add i32 %old, 1
+ store i32 %new, ptr %gep_A, align 4
+ br label %loop.latch
+
+loop.latch:
+ %iv.next = add i64 %iv, 1
+ %ec = icmp eq i64 %iv.next, 1024
+ br i1 %ec, label %exit, label %loop.header
+
+exit:
+ ret void
+}
diff --git a/llvm/test/Transforms/LoopVectorize/X86/optimize-masked-memory/mode-a-guaranteed-safe.ll b/llvm/test/Transforms/LoopVectorize/X86/optimize-masked-memory/mode-a-guaranteed-safe.ll
new file mode 100644
index 0000000000000..266b4102a55b7
--- /dev/null
+++ b/llvm/test/Transforms/LoopVectorize/X86/optimize-masked-memory/mode-a-guaranteed-safe.ll
@@ -0,0 +1,44 @@
+; Phase-1 / Mode-A: a masked store whose address is also accessed on a
+; guaranteed path is rewritten as load-blend-store when
+; -enable-masked-memory-optimization is on.
+;
+; RUN: opt < %s -passes=loop-vectorize -mtriple=x86_64-unknown-linux-gnu \
+; RUN: -mcpu=znver3 -enable-masked-memory-optimization -S \
+; RUN: | FileCheck %s
+
+target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128"
+
+; CHECK-LABEL: @phase1_safe
+; The masked store is replaced by load + select + plain store. We don't
+; care about the exact instruction order, just that the named values
+; introduced by the rewrite appear and no @llvm.masked.store is emitted.
+; CHECK: blend.load = load
+; CHECK: blend.sel = select
+; CHECK-NOT: @llvm.masked.store
+define void @phase1_safe(ptr noalias %A, ptr noalias %cond) {
+entry:
+ br label %loop.header
+
+loop.header:
+ %iv = phi i64 [ 0, %entry ], [ %iv.next, %loop.latch ]
+ %gep_cond = getelementptr inbounds i32, ptr %cond, i64 %iv
+ %cv = load i32, ptr %gep_cond, align 4
+ %gep_A = getelementptr inbounds i32, ptr %A, i64 %iv
+ ; Guaranteed read of A[iv] makes the same-SCEV predicated store safe.
+ %old = load i32, ptr %gep_A, align 4
+ %cmp = icmp ne i32 %cv, 0
+ br i1 %cmp, label %if.then, label %loop.latch
+
+if.then:
+ %new = add i32 %old, 1
+ store i32 %new, ptr %gep_A, align 4
+ br label %loop.latch
+
+loop.latch:
+ %iv.next = add i64 %iv, 1
+ %ec = icmp eq i64 %iv.next, 1024
+ br i1 %ec, label %exit, label %loop.header
+
+exit:
+ ret void
+}
diff --git a/llvm/test/Transforms/LoopVectorize/X86/optimize-masked-memory/mode-a-non-guaranteed.ll b/llvm/test/Transforms/LoopVectorize/X86/optimize-masked-memory/mode-a-non-guaranteed.ll
new file mode 100644
index 0000000000000..6a5db71cbe552
--- /dev/null
+++ b/llvm/test/Transforms/LoopVectorize/X86/optimize-masked-memory/mode-a-non-guaranteed.ll
@@ -0,0 +1,40 @@
+; Phase-1 / Mode-A: a predicated store with no guaranteed access at the same
+; SCEV must NOT be rewritten -- the load-blend-store would introduce a fault.
+;
+; RUN: opt < %s -passes=loop-vectorize -mtriple=x86_64-unknown-linux-gnu \
+; RUN: -mcpu=znver3 -enable-masked-memory-optimization -S \
+; RUN: | FileCheck %s
+
+target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128"
+
+; CHECK-LABEL: @phase1_not_safe
+; CHECK: call void @llvm.masked.store
+; CHECK-NOT: blend.load
+; CHECK-NOT: blend.sel
+define void @phase1_not_safe(ptr noalias %A, ptr noalias %cond) {
+entry:
+ br label %loop.header
+
+loop.header:
+ %iv = phi i64 [ 0, %entry ], [ %iv.next, %loop.latch ]
+ %gep_cond = getelementptr inbounds i32, ptr %cond, i64 %iv
+ %cv = load i32, ptr %gep_cond, align 4
+ %cmp = icmp ne i32 %cv, 0
+ br i1 %cmp, label %if.then, label %loop.latch
+
+if.then:
+ ; Predicated store with no companion guaranteed access at the same
+ ; SCEV anywhere else in the loop body.
+ %gep_A = getelementptr inbounds i32, ptr %A, i64 %iv
+ %val = trunc i64 %iv to i32
+ store i32 %val, ptr %gep_A, align 4
+ br label %loop.latch
+
+loop.latch:
+ %iv.next = add i64 %iv, 1
+ %ec = icmp eq i64 %iv.next, 1024
+ br i1 %ec, label %exit, label %loop.header
+
+exit:
+ ret void
+}
diff --git a/llvm/test/Transforms/LoopVectorize/X86/optimize-masked-memory/scatter-untouched.ll b/llvm/test/Transforms/LoopVectorize/X86/optimize-masked-memory/scatter-untouched.ll
new file mode 100644
index 0000000000000..67ca89a3ea8be
--- /dev/null
+++ b/llvm/test/Transforms/LoopVectorize/X86/optimize-masked-memory/scatter-untouched.ll
@@ -0,0 +1,42 @@
+; Non-consecutive (scatter) masked stores are not on the OptimizeMaskedMemory
+; rewrite path: only consecutive forward-strided stores qualify.
+;
+; RUN: opt < %s -passes=loop-vectorize -mtriple=x86_64-unknown-linux-gnu \
+; RUN: -mcpu=znver3 -enable-masked-memory-optimization -S \
+; RUN: | FileCheck %s
+
+target datalayout = "e-m:e-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-f80:128-n8:16:32:64-S128"
+
+; CHECK-LABEL: @scatter_untouched
+; A strided pointer (idx*2) makes the store non-consecutive. Whatever LV
+; chooses for this (masked scatter, scalarised predicated stores, etc.),
+; the OptimizeMaskedMemory rewrite must NOT touch it -- our rewrite is
+; gated to consecutive forward-strided stores only.
+; CHECK-NOT: blend.load
+; CHECK-NOT: blend.sel
+define void @scatter_untouched(ptr noalias %A, ptr noalias %cond) {
+entry:
+ br label %loop.header
+
+loop.header:
+ %iv = phi i64 [ 0, %entry ], [ %iv.next, %loop.latch ]
+ %gep_cond = getelementptr inbounds i32, ptr %cond, i64 %iv
+ %cv = load i32, ptr %gep_cond, align 4
+ %cmp = icmp ne i32 %cv, 0
+ br i1 %cmp, label %if.then, label %loop.latch
+
+if.then:
+ %idx = mul i64 %iv, 2
+ %gep_A = getelementptr inbounds i32, ptr %A, i64 %idx
+ %val = trunc i64 %iv to i32
+ store i32 %val, ptr %gep_A, align 4
+ br label %loop.latch
+
+loop.latch:
+ %iv.next = add i64 %iv, 1
+ %ec = icmp eq i64 %iv.next, 1024
+ br i1 %ec, label %exit, label %loop.header
+
+exit:
+ ret void
+}
>From e130d599f9d383c51398eb2db4b51a3a53a4c0af Mon Sep 17 00:00:00 2001
From: Arjun H Kumar <Arjun.HKumar at amd.com>
Date: Tue, 30 Jun 2026 11:49:04 +0530
Subject: [PATCH 2/2] [Experimental commit for AArch64 NEON predicated stores.]
---
.../AArch64/AArch64TargetTransformInfo.h | 11 ++
.../Transforms/Vectorize/LoopVectorize.cpp | 86 +++++++++++++--
.../optimize-masked-memory/neon-flag-off.ll | 41 +++++++
.../neon-guaranteed-safe.ll | 50 +++++++++
.../neon-non-guaranteed.ll | 41 +++++++
.../neon-scatter-untouched.ll | 40 +++++++
.../optimize-masked-memory/sve-neutral.ll | 43 ++++++++
.../AArch64/predication_costs.ll | 2 +-
...-interleave-to-widen-memory-multi-block.ll | 4 +-
.../Inputs/check-first-masked-replay-bench.c | 103 ++++++++++++++++++
.../VPlan/AArch64/single-scalar-cast.ll | 2 +-
11 files changed, 411 insertions(+), 12 deletions(-)
create mode 100644 llvm/test/Transforms/LoopVectorize/AArch64/optimize-masked-memory/neon-flag-off.ll
create mode 100644 llvm/test/Transforms/LoopVectorize/AArch64/optimize-masked-memory/neon-guaranteed-safe.ll
create mode 100644 llvm/test/Transforms/LoopVectorize/AArch64/optimize-masked-memory/neon-non-guaranteed.ll
create mode 100644 llvm/test/Transforms/LoopVectorize/AArch64/optimize-masked-memory/neon-scatter-untouched.ll
create mode 100644 llvm/test/Transforms/LoopVectorize/AArch64/optimize-masked-memory/sve-neutral.ll
create mode 100644 llvm/test/Transforms/LoopVectorize/Inputs/check-first-masked-replay-bench.c
diff --git a/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.h b/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.h
index 24934cb01cdd1..66d06594a0677 100644
--- a/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.h
+++ b/llvm/lib/Target/AArch64/AArch64TargetTransformInfo.h
@@ -335,6 +335,17 @@ class AArch64TTIImpl final : public BasicTTIImplBase<AArch64TTIImpl> {
return isLegalMaskedLoadStore(DataType, Alignment);
}
+ bool shouldRewriteMaskedStoreAsLoadBlendStore() const override {
+ // NEON has no masked-store instruction, so the loop vectorizer otherwise
+ // scalarizes a predicated store into a per-lane extract/branch/store
+ // ladder. Rewriting a guaranteed-safe masked store as an unconditional
+ // load + select + unconditional store removes that ladder entirely.
+ // Enable the rewrite only when SVE / Streaming-SVE is unavailable: with
+ // SVE the masked store lowers to a single predicated instruction, so the
+ // rewrite is neutral there (see RFC OptimizeMaskedMemory 7.2).
+ return !ST->isSVEorStreamingSVEAvailable();
+ }
+
bool isElementTypeLegalForCompressStore(Type *Ty) const {
return Ty->isFloatTy() || Ty->isDoubleTy() || Ty->isIntegerTy(32) ||
Ty->isIntegerTy(64);
diff --git a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
index 610ae57774dc7..46eedc0573e70 100644
--- a/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
+++ b/llvm/lib/Transforms/Vectorize/LoopVectorize.cpp
@@ -1033,6 +1033,18 @@ class LoopVectorizationCostModel {
/// \p VF is the vectorization factor that will be used to vectorize \p I.
bool isScalarWithPredication(Instruction *I, ElementCount VF);
+ /// OptimizeMaskedMemory: returns true if the predicated store \p I should be
+ /// lowered as an unconditional load + select (blend) + unconditional store
+ /// instead of being scalarized into a per-lane predicated ladder (or emitted
+ /// as @llvm.masked.store). This is the single source of truth consulted by
+ /// isScalarWithPredication (to keep the store widenable), getConsecutiveMemOpCost
+ /// (to cost the rewritten sequence), and VPRecipeBuilder::tryToWidenMemory
+ /// (to flag the recipe). It returns true only when the target opts in
+ /// (TTI hook), the access is a masked, consecutive, forward store, the loop
+ /// is not tail-folded by masking, and MemSafetyAnalysis proves the address
+ /// is read on every iteration anyway.
+ bool canRewriteStoreAsLoadBlendStore(Instruction *I, ElementCount VF);
+
/// Wrapper function for LoopVectorizationLegality::isMaskRequired,
/// that passes the Instruction \p I and if we fold tail.
bool isMaskRequired(Instruction *I) const;
@@ -2415,6 +2427,41 @@ void LoopVectorizationCostModel::collectLoopScalars(ElementCount VF) {
Scalars[VF].insert_range(Worklist);
}
+bool LoopVectorizationCostModel::canRewriteStoreAsLoadBlendStore(
+ Instruction *I, ElementCount VF) {
+ // Only vector stores are candidates.
+ auto *Store = dyn_cast<StoreInst>(I);
+ if (!Store || VF.isScalar())
+ return false;
+
+ // The target must opt in (e.g. X86 znver1/2/3, AArch64 NEON without SVE).
+ if (!TTI.shouldRewriteMaskedStoreAsLoadBlendStore())
+ return false;
+
+ // The store must actually be predicated/masked; an unconditional store has
+ // nothing to blend.
+ if (!isMaskRequired(I) || !isPredicatedInst(I))
+ return false;
+
+ // Tail-folding gates past-end addresses on the trailing iterations, so an
+ // unconditional load/store would over-read/over-write.
+ if (foldTailByMasking())
+ return false;
+
+ // Only forward consecutive stores: scatters and reversed stores keep their
+ // existing lowering.
+ if (Legal->isConsecutivePtr(getLoadStoreType(I),
+ getLoadStorePointerOperand(I)) != 1)
+ return false;
+
+ // MemSafetyAnalysis must prove the address is read on every iteration anyway,
+ // which makes the unconditional load + store safe.
+ if (!MSA || !MSA->isLegalAnalysis())
+ return false;
+ ScalarEvolution *SE = Legal->getScalarEvolution();
+ return MSA->isGuaranteedMemoryAccess(SE->getSCEV(Store->getPointerOperand()));
+}
+
bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I,
ElementCount VF) {
if (!isPredicatedInst(I))
@@ -2435,6 +2482,11 @@ bool LoopVectorizationCostModel::isScalarWithPredication(Instruction *I,
}
case Instruction::Load:
case Instruction::Store: {
+ // OptimizeMaskedMemory: a guaranteed-safe predicated store is lowered as a
+ // widened load-blend-store sequence, so its predication strategy is not
+ // scalarization.
+ if (isa<StoreInst>(I) && canRewriteStoreAsLoadBlendStore(I, VF))
+ return false;
bool IsConsecutive = Legal->isConsecutivePtr(getLoadStoreType(I),
getLoadStorePointerOperand(I));
return !(IsConsecutive && Config.isLegalMaskedLoadOrStore(I, VF)) &&
@@ -4312,6 +4364,21 @@ LoopVectorizationCostModel::getConsecutiveMemOpCost(Instruction *I,
"Stride should be 1 or -1 for consecutive memory access");
const Align Alignment = getLoadStoreAlignment(I);
InstructionCost Cost = 0;
+ if (canRewriteStoreAsLoadBlendStore(I, VF)) {
+ // OptimizeMaskedMemory: this masked store will be rewritten as an
+ // unconditional load + select (blend) + unconditional store (see
+ // VPWidenStoreRecipe::execute). Cost the sequence accordingly so the
+ // legacy widening cost matches VPWidenMemoryRecipe::computeCost and the
+ // planner sees the true (cheaper) cost when comparing VFs.
+ Cost += TTI.getMemoryOpCost(Instruction::Load, VectorTy, Alignment, AS,
+ Config.CostKind);
+ Type *CondTy = VectorType::get(Type::getInt1Ty(VectorTy->getContext()), VF);
+ Cost += TTI.getCmpSelInstrCost(Instruction::Select, VectorTy, CondTy,
+ CmpInst::BAD_ICMP_PREDICATE, Config.CostKind);
+ Cost += TTI.getMemoryOpCost(Instruction::Store, VectorTy, Alignment, AS,
+ Config.CostKind);
+ return Cost;
+ }
if (isMaskRequired(I)) {
unsigned IID = I->getOpcode() == Instruction::Load
? Intrinsic::masked_load
@@ -6282,14 +6349,17 @@ VPRecipeBase *VPRecipeBuilder::tryToWidenMemory(VPInstruction *VPI,
// load-blend-store would over-read.
// 5. MemSafetyAnalysis must prove the access is guaranteed to execute
// on every iteration of the loop body.
- if (CM.TTI.shouldRewriteMaskedStoreAsLoadBlendStore() &&
- Mask && Consecutive && !Reverse && CM.MSA &&
- CM.MSA->isLegalAnalysis() && !CM.foldTailByMasking()) {
- auto *SE = Legal->getScalarEvolution();
- const SCEV *PtrSCEV = SE->getSCEV(Store->getPointerOperand());
- if (CM.MSA->isGuaranteedMemoryAccess(PtrSCEV))
- NewSR->setRewriteAsLoadBlendStore();
- }
+ //
+ // All of these conditions are encapsulated in
+ // canRewriteStoreAsLoadBlendStore, which is the same predicate the cost
+ // model consults to keep the store widenable (isScalarWithPredication) and
+ // to cost it (getConsecutiveMemOpCost). Using the shared helper here keeps
+ // the widening decision and the recipe flag in sync; otherwise a store that
+ // was widened on the assumption of a rewrite could fall through to an
+ // illegal/expensive @llvm.masked.store on a target without one (e.g. NEON).
+ if (Mask && Consecutive && !Reverse &&
+ CM.canRewriteStoreAsLoadBlendStore(Store, Range.Start))
+ NewSR->setRewriteAsLoadBlendStore();
return NewSR;
}
diff --git a/llvm/test/Transforms/LoopVectorize/AArch64/optimize-masked-memory/neon-flag-off.ll b/llvm/test/Transforms/LoopVectorize/AArch64/optimize-masked-memory/neon-flag-off.ll
new file mode 100644
index 0000000000000..04884f400bc00
--- /dev/null
+++ b/llvm/test/Transforms/LoopVectorize/AArch64/optimize-masked-memory/neon-flag-off.ll
@@ -0,0 +1,41 @@
+; OptimizeMaskedMemory on AArch64 NEON: with
+; -enable-masked-memory-optimization=false the rewrite must not fire, even
+; though the NEON TTI hook would otherwise opt in. The store falls back to the
+; per-lane scalarized predicated ladder.
+;
+; RUN: opt < %s -passes=loop-vectorize -mtriple=aarch64-unknown-linux-gnu \
+; RUN: -mattr=+neon,-sve -enable-masked-memory-optimization=false -S \
+; RUN: | FileCheck %s
+
+target datalayout = "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"
+
+; CHECK-LABEL: @neon_off
+; CHECK-NOT: blend.load
+; CHECK-NOT: blend.sel
+define void @neon_off(ptr noalias %A, ptr noalias %cond) {
+entry:
+ br label %loop.header
+
+loop.header:
+ %iv = phi i64 [ 0, %entry ], [ %iv.next, %loop.latch ]
+ %gep_cond = getelementptr inbounds i32, ptr %cond, i64 %iv
+ %cv = load i32, ptr %gep_cond, align 4
+ %gep_A = getelementptr inbounds i32, ptr %A, i64 %iv
+ %old = load i32, ptr %gep_A, align 4
+ %cmp = icmp ne i32 %cv, 0
+ br i1 %cmp, label %if.then, label %loop.latch
+
+if.then:
+ %mul = mul i32 %old, 3
+ %new = add i32 %mul, 7
+ store i32 %new, ptr %gep_A, align 4
+ br label %loop.latch
+
+loop.latch:
+ %iv.next = add i64 %iv, 1
+ %ec = icmp eq i64 %iv.next, 1024
+ br i1 %ec, label %exit, label %loop.header
+
+exit:
+ ret void
+}
diff --git a/llvm/test/Transforms/LoopVectorize/AArch64/optimize-masked-memory/neon-guaranteed-safe.ll b/llvm/test/Transforms/LoopVectorize/AArch64/optimize-masked-memory/neon-guaranteed-safe.ll
new file mode 100644
index 0000000000000..1efd230437e6f
--- /dev/null
+++ b/llvm/test/Transforms/LoopVectorize/AArch64/optimize-masked-memory/neon-guaranteed-safe.ll
@@ -0,0 +1,50 @@
+; OptimizeMaskedMemory on AArch64 NEON: a predicated store whose address is
+; also accessed on a guaranteed path is rewritten as load-blend-store instead
+; of being scalarized into the per-lane predicated ladder.
+;
+; NEON has no @llvm.masked.store, so without this rewrite the vectorizer emits
+; a per-lane extractelement -> br i1 -> scalar store ladder. With the rewrite
+; the store becomes an unconditional vector load + select (blend) + plain
+; vector store.
+;
+; RUN: opt < %s -passes=loop-vectorize -mtriple=aarch64-unknown-linux-gnu \
+; RUN: -mattr=+neon,-sve -enable-masked-memory-optimization -S \
+; RUN: | FileCheck %s
+
+target datalayout = "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"
+
+; CHECK-LABEL: @neon_safe
+; The predicated store is replaced by load + select + plain store. No masked
+; store (NEON has none) and no per-lane scalarized store ladder.
+; CHECK: blend.load = load
+; CHECK: blend.sel = select
+; CHECK-NOT: @llvm.masked.store
+; CHECK-NOT: extractelement
+define void @neon_safe(ptr noalias %A, ptr noalias %cond) {
+entry:
+ br label %loop.header
+
+loop.header:
+ %iv = phi i64 [ 0, %entry ], [ %iv.next, %loop.latch ]
+ %gep_cond = getelementptr inbounds i32, ptr %cond, i64 %iv
+ %cv = load i32, ptr %gep_cond, align 4
+ %gep_A = getelementptr inbounds i32, ptr %A, i64 %iv
+ ; Guaranteed read of A[iv] makes the same-SCEV predicated store safe.
+ %old = load i32, ptr %gep_A, align 4
+ %cmp = icmp ne i32 %cv, 0
+ br i1 %cmp, label %if.then, label %loop.latch
+
+if.then:
+ %mul = mul i32 %old, 3
+ %new = add i32 %mul, 7
+ store i32 %new, ptr %gep_A, align 4
+ br label %loop.latch
+
+loop.latch:
+ %iv.next = add i64 %iv, 1
+ %ec = icmp eq i64 %iv.next, 1024
+ br i1 %ec, label %exit, label %loop.header
+
+exit:
+ ret void
+}
diff --git a/llvm/test/Transforms/LoopVectorize/AArch64/optimize-masked-memory/neon-non-guaranteed.ll b/llvm/test/Transforms/LoopVectorize/AArch64/optimize-masked-memory/neon-non-guaranteed.ll
new file mode 100644
index 0000000000000..f46c586e45cbf
--- /dev/null
+++ b/llvm/test/Transforms/LoopVectorize/AArch64/optimize-masked-memory/neon-non-guaranteed.ll
@@ -0,0 +1,41 @@
+; OptimizeMaskedMemory on AArch64 NEON: a predicated store with no guaranteed
+; access at the same SCEV must NOT be rewritten -- the unconditional
+; load-blend-store would introduce a fault on lanes the original code never
+; touched.
+;
+; RUN: opt < %s -passes=loop-vectorize -mtriple=aarch64-unknown-linux-gnu \
+; RUN: -mattr=+neon,-sve -enable-masked-memory-optimization -S \
+; RUN: | FileCheck %s
+
+target datalayout = "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"
+
+; CHECK-LABEL: @neon_not_safe
+; CHECK-NOT: blend.load
+; CHECK-NOT: blend.sel
+define void @neon_not_safe(ptr noalias %A, ptr noalias %cond) {
+entry:
+ br label %loop.header
+
+loop.header:
+ %iv = phi i64 [ 0, %entry ], [ %iv.next, %loop.latch ]
+ %gep_cond = getelementptr inbounds i32, ptr %cond, i64 %iv
+ %cv = load i32, ptr %gep_cond, align 4
+ %cmp = icmp ne i32 %cv, 0
+ br i1 %cmp, label %if.then, label %loop.latch
+
+if.then:
+ ; Predicated store with no companion guaranteed access at the same SCEV
+ ; anywhere else in the loop body.
+ %gep_A = getelementptr inbounds i32, ptr %A, i64 %iv
+ %val = trunc i64 %iv to i32
+ store i32 %val, ptr %gep_A, align 4
+ br label %loop.latch
+
+loop.latch:
+ %iv.next = add i64 %iv, 1
+ %ec = icmp eq i64 %iv.next, 1024
+ br i1 %ec, label %exit, label %loop.header
+
+exit:
+ ret void
+}
diff --git a/llvm/test/Transforms/LoopVectorize/AArch64/optimize-masked-memory/neon-scatter-untouched.ll b/llvm/test/Transforms/LoopVectorize/AArch64/optimize-masked-memory/neon-scatter-untouched.ll
new file mode 100644
index 0000000000000..5a6e04a33356b
--- /dev/null
+++ b/llvm/test/Transforms/LoopVectorize/AArch64/optimize-masked-memory/neon-scatter-untouched.ll
@@ -0,0 +1,40 @@
+; OptimizeMaskedMemory on AArch64 NEON: non-consecutive (scatter) stores are
+; not on the rewrite path. Only consecutive forward-strided stores qualify.
+;
+; RUN: opt < %s -passes=loop-vectorize -mtriple=aarch64-unknown-linux-gnu \
+; RUN: -mattr=+neon,-sve -enable-masked-memory-optimization -S \
+; RUN: | FileCheck %s
+
+target datalayout = "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"
+
+; CHECK-LABEL: @scatter_untouched
+; A strided pointer (idx*2) makes the store non-consecutive; the rewrite is
+; gated to consecutive forward-strided stores, so it must not fire.
+; CHECK-NOT: blend.load
+; CHECK-NOT: blend.sel
+define void @scatter_untouched(ptr noalias %A, ptr noalias %cond) {
+entry:
+ br label %loop.header
+
+loop.header:
+ %iv = phi i64 [ 0, %entry ], [ %iv.next, %loop.latch ]
+ %gep_cond = getelementptr inbounds i32, ptr %cond, i64 %iv
+ %cv = load i32, ptr %gep_cond, align 4
+ %cmp = icmp ne i32 %cv, 0
+ br i1 %cmp, label %if.then, label %loop.latch
+
+if.then:
+ %idx = mul i64 %iv, 2
+ %gep_A = getelementptr inbounds i32, ptr %A, i64 %idx
+ %val = trunc i64 %iv to i32
+ store i32 %val, ptr %gep_A, align 4
+ br label %loop.latch
+
+loop.latch:
+ %iv.next = add i64 %iv, 1
+ %ec = icmp eq i64 %iv.next, 1024
+ br i1 %ec, label %exit, label %loop.header
+
+exit:
+ ret void
+}
diff --git a/llvm/test/Transforms/LoopVectorize/AArch64/optimize-masked-memory/sve-neutral.ll b/llvm/test/Transforms/LoopVectorize/AArch64/optimize-masked-memory/sve-neutral.ll
new file mode 100644
index 0000000000000..11842bfbf9614
--- /dev/null
+++ b/llvm/test/Transforms/LoopVectorize/AArch64/optimize-masked-memory/sve-neutral.ll
@@ -0,0 +1,43 @@
+; OptimizeMaskedMemory is gated off on SVE: the AArch64 TTI hook
+; shouldRewriteMaskedStoreAsLoadBlendStore() returns false when SVE is
+; available, because the masked store lowers to a single predicated
+; instruction there (the rewrite would be neutral). The vectorizer therefore
+; keeps emitting @llvm.masked.store and the rewrite must not fire.
+;
+; RUN: opt < %s -passes=loop-vectorize -mtriple=aarch64-unknown-linux-gnu \
+; RUN: -mattr=+sve -enable-masked-memory-optimization -S \
+; RUN: | FileCheck %s
+
+target datalayout = "e-m:e-i8:8:32-i16:16:32-i64:64-i128:128-n32:64-S128"
+
+; CHECK-LABEL: @sve_neutral
+; CHECK: call void @llvm.masked.store
+; CHECK-NOT: blend.load
+; CHECK-NOT: blend.sel
+define void @sve_neutral(ptr noalias %A, ptr noalias %cond) {
+entry:
+ br label %loop.header
+
+loop.header:
+ %iv = phi i64 [ 0, %entry ], [ %iv.next, %loop.latch ]
+ %gep_cond = getelementptr inbounds i32, ptr %cond, i64 %iv
+ %cv = load i32, ptr %gep_cond, align 4
+ %gep_A = getelementptr inbounds i32, ptr %A, i64 %iv
+ %old = load i32, ptr %gep_A, align 4
+ %cmp = icmp ne i32 %cv, 0
+ br i1 %cmp, label %if.then, label %loop.latch
+
+if.then:
+ %mul = mul i32 %old, 3
+ %new = add i32 %mul, 7
+ store i32 %new, ptr %gep_A, align 4
+ br label %loop.latch
+
+loop.latch:
+ %iv.next = add i64 %iv, 1
+ %ec = icmp eq i64 %iv.next, 1024
+ br i1 %ec, label %exit, label %loop.header
+
+exit:
+ ret void
+}
diff --git a/llvm/test/Transforms/LoopVectorize/AArch64/predication_costs.ll b/llvm/test/Transforms/LoopVectorize/AArch64/predication_costs.ll
index fdb22beb19695..c44ea1749b80d 100644
--- a/llvm/test/Transforms/LoopVectorize/AArch64/predication_costs.ll
+++ b/llvm/test/Transforms/LoopVectorize/AArch64/predication_costs.ll
@@ -1,5 +1,5 @@
; REQUIRES: asserts
-; RUN: opt < %s -force-vector-width=2 -passes=loop-vectorize -debug-only=loop-vectorize -disable-output 2>&1 | FileCheck %s
+; RUN: opt < %s -force-vector-width=2 -passes=loop-vectorize -debug-only=loop-vectorize -enable-masked-memory-optimization=false -disable-output 2>&1 | FileCheck %s
target datalayout = "e-m:e-i64:64-i128:128-n32:64-S128"
target triple = "aarch64--linux-gnu"
diff --git a/llvm/test/Transforms/LoopVectorize/AArch64/transform-narrow-interleave-to-widen-memory-multi-block.ll b/llvm/test/Transforms/LoopVectorize/AArch64/transform-narrow-interleave-to-widen-memory-multi-block.ll
index 478a724f49c21..19c1ff0112073 100644
--- a/llvm/test/Transforms/LoopVectorize/AArch64/transform-narrow-interleave-to-widen-memory-multi-block.ll
+++ b/llvm/test/Transforms/LoopVectorize/AArch64/transform-narrow-interleave-to-widen-memory-multi-block.ll
@@ -1,6 +1,6 @@
; NOTE: Assertions have been autogenerated by utils/update_test_checks.py UTC_ARGS: --check-globals none --version 6
-; RUN: opt -p loop-vectorize -force-vector-width=2 -force-vector-interleave=1 -S %s | FileCheck --check-prefixes=VF2IC1 %s
-; RUN: opt -p loop-vectorize -force-vector-width=2 -force-vector-interleave=2 -S %s | FileCheck --check-prefixes=VF2IC2 %s
+; RUN: opt -p loop-vectorize -force-vector-width=2 -force-vector-interleave=1 -enable-masked-memory-optimization=false -S %s | FileCheck --check-prefixes=VF2IC1 %s
+; RUN: opt -p loop-vectorize -force-vector-width=2 -force-vector-interleave=2 -enable-masked-memory-optimization=false -S %s | FileCheck --check-prefixes=VF2IC2 %s
target datalayout = "e-m:o-p270:32:32-p271:32:32-p272:64:64-i64:64-i128:128-n32:64-S128-Fn32"
target triple = "arm64-apple-macosx"
diff --git a/llvm/test/Transforms/LoopVectorize/Inputs/check-first-masked-replay-bench.c b/llvm/test/Transforms/LoopVectorize/Inputs/check-first-masked-replay-bench.c
new file mode 100644
index 0000000000000..79e72e023c15f
--- /dev/null
+++ b/llvm/test/Transforms/LoopVectorize/Inputs/check-first-masked-replay-bench.c
@@ -0,0 +1,103 @@
+// Benchmark: Scalar replay vs. Masked vector replay for check-first
+// early-exit vectorization.
+//
+// Compile and run:
+// # Scalar replay (baseline):
+// clang -O2 -mllvm -enable-early-exit-vectorization \
+// -mllvm -enable-check-first-vectorization \
+// -o bench_scalar check-first-masked-replay-bench.c
+//
+// # Masked replay:
+// clang -O2 -mllvm -enable-early-exit-vectorization \
+// -mllvm -enable-check-first-vectorization \
+// -mllvm -enable-check-first-masked-replay \
+// -o bench_masked check-first-masked-replay-bench.c
+//
+// ./bench_scalar
+// ./bench_masked
+//
+// Expected: masked replay wins on short trip counts (N ~ 8-32) where
+// the VF/2 scalar replay dominates. On long trip counts the replay is
+// amortized so the difference is smaller.
+
+#include <stdint.h>
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+#include <time.h>
+
+#define ALLOC_SIZE 4096
+#define WARMUP_ITERS 100
+#define BENCH_ITERS 100000
+
+// memcpy-with-exit: copy bytes from src to dst until sentinel is found in chk.
+// Returns the index of the sentinel (or N if not found).
+__attribute__((noinline))
+int64_t memcpy_exit(uint8_t *__restrict dst,
+ const uint8_t *__restrict src,
+ const uint8_t *__restrict chk,
+ int64_t N) {
+ for (int64_t i = 0; i < N; i++) {
+ dst[i] = src[i];
+ if (chk[i] == 0)
+ return i;
+ }
+ return N;
+}
+
+static double bench(int64_t N, int64_t exit_pos, int iters) {
+ uint8_t *dst = (uint8_t *)aligned_alloc(64, ALLOC_SIZE);
+ uint8_t *src = (uint8_t *)aligned_alloc(64, ALLOC_SIZE);
+ uint8_t *chk = (uint8_t *)aligned_alloc(64, ALLOC_SIZE);
+
+ memset(src, 0xAA, ALLOC_SIZE);
+ memset(chk, 0xFF, ALLOC_SIZE);
+ if (exit_pos < N && exit_pos < ALLOC_SIZE)
+ chk[exit_pos] = 0;
+
+ // Warmup
+ volatile int64_t sink;
+ for (int w = 0; w < WARMUP_ITERS; w++)
+ sink = memcpy_exit(dst, src, chk, N);
+
+ struct timespec t0, t1;
+ clock_gettime(CLOCK_MONOTONIC, &t0);
+ for (int i = 0; i < iters; i++)
+ sink = memcpy_exit(dst, src, chk, N);
+ clock_gettime(CLOCK_MONOTONIC, &t1);
+
+ double elapsed = (t1.tv_sec - t0.tv_sec) + (t1.tv_nsec - t0.tv_nsec) * 1e-9;
+ free(dst);
+ free(src);
+ free(chk);
+ return elapsed;
+}
+
+int main(void) {
+ printf("%-12s %-12s %-12s %-12s\n", "N", "exit_pos", "time(ms)", "ns/iter");
+
+ struct { int64_t N; int64_t exit_pos; const char *desc; } cases[] = {
+ { 8, 3, "short, early exit" },
+ { 16, 7, "short, mid exit" },
+ { 32, 15, "short, late exit" },
+ { 32, 32, "short, no exit" },
+ { 128, 5, "med, early exit" },
+ { 128, 64, "med, mid exit" },
+ { 128, 128, "med, no exit" },
+ { 1024, 10, "long, early exit" },
+ { 1024, 512, "long, mid exit" },
+ { 1024, 1024, "long, no exit" },
+ };
+ int ncases = sizeof(cases) / sizeof(cases[0]);
+
+ for (int c = 0; c < ncases; c++) {
+ double t = bench(cases[c].N, cases[c].exit_pos, BENCH_ITERS);
+ double ms = t * 1000.0;
+ double ns_per = t * 1e9 / BENCH_ITERS;
+ printf("%-12ld %-12ld %-12.3f %-12.1f %s\n",
+ (long)cases[c].N, (long)cases[c].exit_pos,
+ ms, ns_per, cases[c].desc);
+ }
+
+ return 0;
+}
diff --git a/llvm/test/Transforms/LoopVectorize/VPlan/AArch64/single-scalar-cast.ll b/llvm/test/Transforms/LoopVectorize/VPlan/AArch64/single-scalar-cast.ll
index 7743c7bcbe058..bae7ee9785b46 100644
--- a/llvm/test/Transforms/LoopVectorize/VPlan/AArch64/single-scalar-cast.ll
+++ b/llvm/test/Transforms/LoopVectorize/VPlan/AArch64/single-scalar-cast.ll
@@ -1,5 +1,5 @@
; NOTE: Assertions have been autogenerated by utils/update_analyze_test_checks.py UTC_ARGS: --filter-out-after "middle.block:" --filter-out-after "middleb.block:" --version 6
-; RUN: opt -passes=loop-vectorize -force-vector-interleave=1 -force-vector-width=2 -vplan-print-after=printOptimizedVPlan -disable-output %s 2>&1 | FileCheck %s
+; RUN: opt -passes=loop-vectorize -force-vector-interleave=1 -force-vector-width=2 -enable-masked-memory-optimization=false -vplan-print-after=printOptimizedVPlan -disable-output %s 2>&1 | FileCheck %s
target triple = "arm64-apple-macosx"
More information about the llvm-commits
mailing list