Skip to content

A lightweight WebAssembly runtime that is fast, secure, and standards-compliant

Never eliminate atomic stores in dead-store elimination (#14005)

Nick Fitzgerald60154144e428
diff --git a/cranelift/codegen/src/alias_analysis.rs b/cranelift/codegen/src/alias_analysis.rs
index aae88ec46a..b5bbbc58a2 100644
--- a/cranelift/codegen/src/alias_analysis.rs
+++ b/cranelift/codegen/src/alias_analysis.rs
@@ -606,6 +606,10 @@ impl<'a> AliasAnalysis<'a> {
// from (and therefore observe) memory before
// storing to it.
&& !func.dfg.insts[inst].opcode().can_load()
+ // A store with memory fence semantics (such as an
+ // atomic store) is observable by other threads, so it
+ // can never be eliminated.
+ && !has_memory_fence_semantics(func.dfg.insts[last_store].opcode())
// `last_store` must really be a store that
// writes exactly the bytes this store
// overwrites (same region, address, offset,
diff --git a/cranelift/filetests/filetests/alias/not-dead-atomic-store-before-trap.clif b/cranelift/filetests/filetests/alias/not-dead-atomic-store-before-trap.clif
new file mode 100644
index 0000000000..036fc07e27
--- /dev/null
+++ b/cranelift/filetests/filetests/alias/not-dead-atomic-store-before-trap.clif
@@ -0,0 +1,49 @@
+test optimize precise-output
+set opt_level=speed
+target aarch64
+
+;; Regression test for issue #13960.
+
+;; An `atomic_store` has memory fence semantics, so it is recorded in the
+;; `last_fence` slot rather than as a region store. A following trapping
+;; instruction (`udiv`, divide by zero) observes all regions, and so, even
+;; though a second `atomic_store` to the same location fully overwrites it, the
+;; first `atomic_store` must survive.
+function %atomic_store_before_trap(i64, i32, i32, i32) {
+ region0 = 0 "R0"
+block0(v0: i64, v1: i32, v2: i32, v3: i32):
+ atomic_store.i32 region0 v1, v0
+ v4 = udiv.i32 v2, v3
+ atomic_store.i32 region0 v2, v0
+ return
+}
+
+; function %atomic_store_before_trap(i64, i32, i32, i32) fast {
+; region0 = 0 "R0"
+;
+; block0(v0: i64, v1: i32, v2: i32, v3: i32):
+; atomic_store region0 v1, v0
+; v4 = udiv v2, v3
+; atomic_store region0 v2, v0
+; return
+; }
+
+;; Two consecutive atomic stores to the same location with nothing in between.
+;; The first must still survive: an atomic store is observable by other threads,
+;; so it is never a dead store even when directly overwritten.
+function %atomic_store_then_atomic_store(i64, i32, i32) {
+ region0 = 0 "R0"
+block0(v0: i64, v1: i32, v2: i32):
+ atomic_store.i32 region0 v1, v0
+ atomic_store.i32 region0 v2, v0
+ return
+}
+
+; function %atomic_store_then_atomic_store(i64, i32, i32) fast {
+; region0 = 0 "R0"
+;
+; block0(v0: i64, v1: i32, v2: i32):
+; atomic_store region0 v1, v0
+; atomic_store region0 v2, v0
+; return
+; }