From b63216b66e30579084043ff648fc175f793cc1d9 Mon Sep 17 00:00:00 2001 From: minzyfox Date: Sun, 29 Nov 2026 19:40:03 -0800 Subject: [PATCH 1/2] tasks: copy each value that a task moves or copies at its spawn A task that ran in a loop could see the value of a later pass of the loop. Each local of a loop body has one stack slot for all the passes. The lowering of a task copied a slot into the task at the `spawn` only when the task loaded the whole value. For any other use, such as a read of one field, the task got the address of the slot. The next pass then wrote its own value into the slot before the task read it. So three kinds of program gave wrong values: - a task that moved a value with a channel end in it. Since #3166, such a task starts with a call that reads a field of that value, for the deadlock report. - a task that moved one field of a struct, as in `take(h.id, h.rx)`. - a task that read a field of a `Copy` struct, with no channel at all. Two tasks could then own the same `Sender`, so the program dropped one channel end twice and never dropped another. Now the checker decides, not the shape of the code. The checker already knows whether a task moves, copies, writes or reads each variable from outside. It saves the names that the task moves or copies on the task body. The flat code generator starts the task with a new op, `vx.take_at_spawn`, for each one that is in memory. The lowering copies each marked slot into the task at the `spawn`, and every use in the task goes to a slot of the task's own. A reference is left out: the task copies the address, not what the reference points to. The lowering also checks the result. A task that nothing joins must not get the address of a slot that the loop around its `spawn` writes again in each pass. If it does, the compile stops with an error that says the compiler has a bug. Tests: - values_moved_into_tasks_in_a_loop_are_the_values_of_their_pass.vx: six cases, with each task runtime, two seeds and --legacy-codegen. Five cases gave wrong values or crashed before this change. The sixth checks that a task that writes a borrowed struct still writes the struct itself. - a_task_copies_a_slot_that_it_takes_at_its_spawn.mlr and a_task_that_reads_a_slot_a_loop_writes_again_is_refused.mlr check the lowering and its new error on hand-written MLIR. Part of: #4345 Co-Authored-By: Claude Opus 5.5 --- include/VxDialect.td | 9 + src/bytecode.rs | 5 + src/codegen/flat.rs | 1 + src/codegen/flat/emit/parallel.rs | 23 ++ src/dialect/VxLowering.cpp | 137 +++++++++- src/hir/check/drops.rs | 7 +- src/hir/check/tasks.rs | 13 + src/hir/flatten.rs | 23 ++ src/parser/expr.rs | 1 + src/syntax/expr.rs | 5 + ..._in_a_loop_are_the_values_of_their_pass.vx | 234 ++++++++++++++++++ ...pies_a_slot_that_it_takes_at_its_spawn.mlr | 52 ++++ ..._a_slot_a_loop_writes_again_is_refused.mlr | 40 +++ 13 files changed, 543 insertions(+), 7 deletions(-) create mode 100644 tests/backend/pass/values_moved_into_tasks_in_a_loop_are_the_values_of_their_pass.vx create mode 100644 tests/optimizations/pass/a_task_copies_a_slot_that_it_takes_at_its_spawn.mlr create mode 100644 tests/optimizations/pass/a_task_that_reads_a_slot_a_loop_writes_again_is_refused.mlr diff --git a/include/VxDialect.td b/include/VxDialect.td index cbb402c44..6b974224e 100644 --- a/include/VxDialect.td +++ b/include/VxDialect.td @@ -28,6 +28,15 @@ def Vx_SpawnOp : Vx_Op<"spawn"> { let assemblyFormat = "`topology` `(` $topology `)` $body attr-dict (`:` type($results)^)?"; } +// At the start of a task: the task takes the value of type `value_type` in +// `slot` at its `spawn`, because it moves or copies the variable. The lowering +// of the task copies the value into the task, and the task then uses a slot of +// its own. The op declares no memory effects, so no pass deletes it first. +def Vx_TakeAtSpawnOp : Vx_Op<"take_at_spawn"> { + let summary = "A task takes the value in a slot at its spawn."; + let arguments = (ins AnyType:$slot, TypeAttr:$value_type); +} + // A transfer operation to move memory/execution context between topologies // It reads the source and allocates the copy. The general write is the copy // into the target's memory, and keeps an unused transfer from being deleted. diff --git a/src/bytecode.rs b/src/bytecode.rs index f4852a10e..2957a7425 100644 --- a/src/bytecode.rs +++ b/src/bytecode.rs @@ -364,6 +364,10 @@ pub enum Opcode { /// register, in its low 32 bits. Its high 32 bits hold the operation, the `Opcode` of /// `Add`, `Sub`, `Mul` or `Div`. See `elementwise_into_imm`. ElementwiseInto = 87, + /// At the start of a task: the task takes the value in the slot `operand1` at its `spawn`, + /// because it moves or copies the variable. The task then works on a slot of its own. It + /// never reads the slot outside, which the code around the task can use for a new value. + TaskTakes = 88, } /// The `imm` of an `ElementwiseInto` that writes `op` of its operands into `dst`. @@ -611,6 +615,7 @@ impl Opcode { 85 => TensorCast, 86 => TensorRange, 87 => ElementwiseInto, + 88 => TaskTakes, 8 => Call, 9 => Ret, 10 => Matmul, diff --git a/src/codegen/flat.rs b/src/codegen/flat.rs index 4acbe104f..f8798862d 100644 --- a/src/codegen/flat.rs +++ b/src/codegen/flat.rs @@ -2746,6 +2746,7 @@ impl<'a> FnEmit<'a> { // terminator already ended it), stamp the `topology` attribute, and resume emitting into // the enclosing block (which the spawn op did not terminate). Opcode::SpawnEnd => self.op_spawn_end(idx, ins), + Opcode::TaskTakes => self.op_task_takes(ins), Opcode::TasksWait => { let join = if ins.imm == 1 { " {join}" } else { "" }; self.body += &format!(" \"vx.tasks_wait\"(){join} : () -> ()\n"); diff --git a/src/codegen/flat/emit/parallel.rs b/src/codegen/flat/emit/parallel.rs index 2238564ad..e0b674953 100644 --- a/src/codegen/flat/emit/parallel.rs +++ b/src/codegen/flat/emit/parallel.rs @@ -221,6 +221,29 @@ impl FnEmit<'_> { Ok(marks) } + /// `vx.take_at_spawn`: the task takes the value in a slot at its `spawn` (`TaskTakes`). Only + /// a slot that is an `!llvm.ptr` gets one: a struct, a pointer or a scalar whose address is + /// taken. The task can reach into such a slot by its address. A scalar in a rank-0 memref is + /// only loaded, and the lowering copies it anyway. + pub(crate) fn op_task_takes(&mut self, ins: &HirInstruction) -> Lowered<()> { + let r = ins.operand1.0 as usize; + let value_ty = if let Some(&Some(gid)) = self.agg_of.get(r) { + let agg = self.ctx.aggs.get(&gid).ok_or(crate::emitter_gap!())?; + agg.struct_ty.clone() + } else if self.pslot_of.get(r).copied().unwrap_or(false) { + "!llvm.ptr".to_string() + } else if let Some(e) = self.sslot_of.get(r).cloned().flatten() { + mlir_scalar(&e).ok_or(crate::emitter_gap!())?.to_string() + } else { + return Ok(()); + }; + let slot = self.names.get(r).ok_or(crate::emitter_gap!())?; + self.body += &format!( + " \"vx.take_at_spawn\"({slot}) {{value_type = {value_ty}}} : (!llvm.ptr) -> ()\n" + ); + Ok(()) + } + // Close the `vx.spawn` region: terminate its last block with `vx.yield` (unless a body // terminator already ended it), stamp the `topology` attribute, and resume emitting into // the enclosing block (which the spawn op did not terminate). diff --git a/src/dialect/VxLowering.cpp b/src/dialect/VxLowering.cpp index 98dd0ae37..a47c17128 100644 --- a/src/dialect/VxLowering.cpp +++ b/src/dialect/VxLowering.cpp @@ -7974,10 +7974,11 @@ static Operation *resultSlotStore(vx::SpawnOp task, Value &slot) { } /// The value that a load of the stack slot `capture` gives, when the task -/// only loads it: a scalar local, the cell of a `let mut` tensor, or a struct -/// that the task moves or copies. The task copies such a slot at its `spawn` -/// (T4), because the variable may end, and its slot get a new value, before -/// the task reads it. A null type for any other capture. +/// only loads it: a scalar local, or the cell of a `let mut` tensor. The task +/// copies such a slot at its `spawn` (T4), because the variable may end, and +/// its slot get a new value, before the task reads it. A null type for any +/// other capture. A slot that the task moves or copies and can reach by its +/// address, such as a struct, has a `vx.take_at_spawn` instead. static Type copiedAtSpawn(Value capture, Region &body) { Type loaded; if (auto type = dyn_cast(capture.getType())) { @@ -8011,6 +8012,69 @@ static SmallVector loadsIn(Value slot, func::FuncOp fn) { return loads; } +/// The blocks of the region of `task` that are on a cycle through the block of +/// `task`: the code of a loop around the `spawn`. Empty when no loop is around +/// it in its region. +static SmallPtrSet loopAroundSpawn(vx::SpawnOp task) { + Block *start = task->getBlock(); + auto walk = [start](bool forward) { + SmallPtrSet seen; + SmallVector work; + auto next = [&](Block *b) { + if (forward) + work.append(b->getSuccessors().begin(), b->getSuccessors().end()); + else + work.append(b->getPredecessors().begin(), b->getPredecessors().end()); + }; + next(start); + while (!work.empty()) { + Block *b = work.pop_back_val(); + if (seen.insert(b).second) + next(b); + } + return seen; + }; + SmallPtrSet after = walk(true); + SmallPtrSet loop; + if (!after.contains(start)) + return loop; + for (Block *b : walk(false)) + if (after.contains(b)) + loop.insert(b); + return loop; +} + +/// Whether code outside `task`, in a block of `loop`, gives the stack slot +/// `slot` a new value: a store to it or to a field of it, or a new start of its +/// lifetime, as the `let` of a variable in a loop makes in each pass. +static bool newValueOnLoop(Value slot, vx::SpawnOp task, + const SmallPtrSet &loop) { + Region *region = task->getParentRegion(); + SmallVector places = {slot}; + while (!places.empty()) { + Value place = places.pop_back_val(); + for (OpOperand &use : place.getUses()) { + Operation *user = use.getOwner(); + if (task->isAncestor(user)) + continue; + Block *block = region->findAncestorBlockInRegion(*user->getBlock()); + if (!block || !loop.contains(block)) + continue; + if (auto gep = dyn_cast(user)) { + places.push_back(gep.getResult()); + continue; + } + auto store = dyn_cast(user); + auto cellStore = dyn_cast(user); + if ((store && store.getAddr() == place) || + (cellStore && cellStore.getMemRef() == place) || + isa(user)) + return true; + } + } + return false; +} + /// Outlines `task` into a function that runs on a thread of `group`. static LogicalResult lowerTask(vx::SpawnOp task, Value group, ModuleOp module, SmallVectorImpl &slots) { @@ -8049,13 +8113,38 @@ static LogicalResult lowerTask(vx::SpawnOp task, Value group, ModuleOp module, if (resultSlot) captures.insert(resultSlot); + // The slots that the task moves or copies, which the checker marked with + // `vx.take_at_spawn`. The `spawn` copies each one into the task, whatever the + // task does with it. Then the code around the task can give the slot a new + // value, as the next pass of a loop does, before the task reads it. + DenseMap taken; + SmallVector takeOps; + body.walk([&](vx::TakeAtSpawnOp op) { + if (op->getParentOfType() != task) + return; + takeOps.push_back(op); + Value slot = op.getSlot(); + assert(captures.contains(slot) && "a task takes a slot from outside it"); + assert(isa(slot.getType()) && + "a task takes a value from a place in memory"); + auto [it, inserted] = taken.try_emplace(slot, op.getValueType()); + assert((inserted || it->second == op.getValueType()) && + "a task takes a slot with one type"); + (void)it; + (void)inserted; + }); + // The environment: the header, then one field for each captured value, then // the result when no slot takes it. // A copied slot has the type of its value, and every other capture its own. SmallVector copied; SmallVector fieldTypes = {ptrTy, i64Ty}; for (Value capture : captures) { - Type copy = capture != resultSlot ? copiedAtSpawn(capture, body) : Type(); + Type copy; + if (auto it = taken.find(capture); it != taken.end()) + copy = it->second; + else if (capture != resultSlot) + copy = copiedAtSpawn(capture, body); copied.push_back(copy); Type type = copy ? copy : capture.getType(); Type field = converter.convertType(type); @@ -8063,6 +8152,23 @@ static LogicalResult lowerTask(vx::SpawnOp task, Value group, ModuleOp module, return task.emitError("a task cannot take a value of type ") << type; fieldTypes.push_back(field); } + // A task that nothing joins runs until its `tasks` block ends. When a loop + // around its `spawn` gives a slot a new value in each pass, the task must + // copy the slot: with the address, it can read the value of a later pass. + if (task.getNumResults() == 0) { + SmallPtrSet loop = loopAroundSpawn(task); + for (auto [i, capture] : llvm::enumerate(captures)) { + bool slot = capture.getDefiningOp() || + capture.getDefiningOp(); + if (!copied[i] && slot && !loop.empty() && + newValueOnLoop(capture, task, loop)) + return task.emitError( + "the compiler gives this task the address of a variable, and the " + "loop around the `spawn` gives the variable a new value in each " + "pass. So the task can read the value of a later pass. This is a " + "bug in the compiler"); + } + } std::optional resultField; Type resultFieldType; if (result && !resultSlot) { @@ -8110,13 +8216,22 @@ static LogicalResult lowerTask(vx::SpawnOp task, Value group, ModuleOp module, cast->setAttr("vx.task_takes", UnitAttr::get(ctx)); v = cast.getResult(0); } + // A slot that the task takes: the task gets a slot of its own with the + // value, and each use in the task goes to that slot. + if (taken.contains(capture)) { + Value one = LLVM::ConstantOp::create(b, loc, b.getI32Type(), + b.getI32IntegerAttr(1)); + Value own = LLVM::AllocaOp::create(b, loc, ptrTy, type, one); + LLVM::StoreOp::create(b, loc, v, own); + v = own; + } inTask.push_back(v); } Block *first = &body.front(); fn.getBody().getBlocks().splice(fn.getBody().end(), body.getBlocks()); cf::BranchOp::create(b, loc, first); for (auto [i, capture] : llvm::enumerate(captures)) { - if (copied[i]) { + if (copied[i] && !taken.contains(capture)) { for (Operation *load : loadsIn(capture, fn)) { load->getResult(0).replaceAllUsesWith(inTask[i]); load->erase(); @@ -8127,6 +8242,16 @@ static LogicalResult lowerTask(vx::SpawnOp task, Value group, ModuleOp module, return fn->isProperAncestor(use.getOwner()); }); } + for (vx::TakeAtSpawnOp op : takeOps) + op.erase(); + // A copied capture has no use left in the task: the task never reads the + // slot outside it. + for (auto [i, capture] : llvm::enumerate(captures)) + assert((!copied[i] || llvm::none_of(capture.getUsers(), + [&](Operation *user) { + return fn->isProperAncestor(user); + })) && + "a task reads a slot outside it that it copied"); Value slotInTask; if (resultSlot) slotInTask = inTask[llvm::find(captures, resultSlot) - captures.begin()]; diff --git a/src/hir/check/drops.rs b/src/hir/check/drops.rs index f21369dcf..21a535362 100644 --- a/src/hir/check/drops.rs +++ b/src/hir/check/drops.rs @@ -775,7 +775,12 @@ fn rename_in_node(e: &mut Expr, from: &str, to: &str) { rename_stmt_names(b, from, to); } } - Expr::UnsafeBlock(b) => rename_stmt_names(&mut b.stmts, from, to), + Expr::UnsafeBlock(b) => { + for n in b.takes.iter_mut().filter(|n| n.as_ref() == from) { + *n = to.into(); + } + rename_stmt_names(&mut b.stmts, from, to); + } Expr::ComptimeBlock(b) => rename_stmt_names(&mut b.stmts, from, to), Expr::SpawnOn(b) => rename_stmt_names(&mut b.stmts, from, to), Expr::TaskBlock(b) => rename_stmt_names(&mut b.stmts, from, to), diff --git a/src/hir/check/tasks.rs b/src/hir/check/tasks.rs index 9cfe79c3c..480470458 100644 --- a/src/hir/check/tasks.rs +++ b/src/hir/check/tasks.rs @@ -477,6 +477,7 @@ impl TypeChecker<'_> { cancels_on_err, value_ty, closure_body: false, + takes: Vec::new(), }); } @@ -912,6 +913,9 @@ impl TypeChecker<'_> { } let mut uses = Vec::new(); + // What the task moves or copies. The code generator copies each one into the task at + // its `spawn`, so the task never reads a slot that the code around it can change. + let mut takes = Vec::new(); for (name, var_ty) in &used { let Some(var_depth) = self.lookup_with_depth(name).map(|(_, _, d)| d) else { continue; @@ -934,6 +938,12 @@ impl TypeChecker<'_> { Take::Reads }; self.check_task_takes(name, var_ty, take, &span); + // A reference is the address of what it borrows: the task copies the address, and + // must not copy what it points to. + if matches!(take, Take::Moves | Take::Copies) && !matches!(var_ty, Type::Borrow { .. }) + { + takes.push(name.clone()); + } if take == Take::Moves { continue; } @@ -1008,6 +1018,9 @@ impl TypeChecker<'_> { // The type of the value of a task with a handle, for an exit that gives it early. let value_ty = (place == Some(SpawnPlace::Let)).then(|| ty.clone()); self.task_block_to_plain_block(expr, ret, None, cancels_on_err, value_ty); + if let Expr::UnsafeBlock(block) = expr { + block.takes = takes; + } ty } diff --git a/src/hir/flatten.rs b/src/hir/flatten.rs index 84990ed18..fd24ff7fd 100644 --- a/src/hir/flatten.rs +++ b/src/hir/flatten.rs @@ -508,6 +508,9 @@ struct Lowerer<'r> { /// The `Result` type of the next task region, when its task can fail. An `Err` value at its /// end cancels its `tasks` block (F3). region_cancels_on_err: Option, + /// The variables that the next task region moves or copies. The region starts with a + /// `TaskTakes` for each one that is in a slot. + region_takes: Vec, /// Tensor-type side table `GID -> (element, shape)`, recorded as tensor-typed values are emitted. /// Tensor GIDs are content hashes, so codegen recovers a tensor's memref shape from here rather /// than by inverting the GID (which is impossible). Committed onto the worker. @@ -669,6 +672,7 @@ impl<'r> Lowerer<'r> { task_bodies: Vec::new(), region_tail_slot: None, region_cancels_on_err: None, + region_takes: Vec::new(), tensor_types: Vec::new(), strings: Vec::new(), ast_types: HashMap::new(), @@ -4301,6 +4305,7 @@ impl<'r> Lowerer<'r> { self.region_cancels_on_err = u.cancels_on_err.clone(); let task = kind == crate::syntax::TaskBlockKind::Spawn; if task { + self.region_takes = u.takes.clone(); self.task_bodies.push(TaskBody { spawn_depth: self.spawn_depth + 1, want_value, @@ -4542,6 +4547,7 @@ impl<'r> Lowerer<'r> { ) -> Lowered> { let tail_slot = self.region_tail_slot.take(); let cancels_on_err = self.region_cancels_on_err.take(); + let takes = std::mem::take(&mut self.region_takes); let on_device = !matches!( imm as u32 as i32, crate::arch::TASK_DISPATCH_ID | crate::arch::TASKS_BLOCK_DISPATCH_ID @@ -4562,6 +4568,23 @@ impl<'r> Lowerer<'r> { Vec::new() }; self.emit_effect(Opcode::Spawn, Register(0), Register(0), imm); + for name in &takes { + match self.scope.get(name) { + Some(Binding::Slot { reg, .. }) => { + let reg = *reg; + self.emit_effect(Opcode::TaskTakes, reg, Register(0), 0); + } + // A value in a register is copied into the task anyway. A struct value in a + // register is in a slot, and the code generator finds it. + Some(Binding::Reg(v)) => { + let reg = v.reg; + self.emit_effect(Opcode::TaskTakes, reg, Register(0), 0); + } + // A reference that has no address in memory: the task reads what it names. + Some(Binding::Place { .. }) => {} + None => panic!("the task takes '{name}', which has no binding"), + } + } if launch.across { self.emit_effect(Opcode::AcrossRegion, Register(0), Register(0), 0); } diff --git a/src/parser/expr.rs b/src/parser/expr.rs index 78abdf670..eda131687 100644 --- a/src/parser/expr.rs +++ b/src/parser/expr.rs @@ -1075,6 +1075,7 @@ impl<'a> Parser<'a> { cancels_on_err: None, value_ty: None, closure_body: false, + takes: Vec::new(), }); return Ok(self.wrap_try(expr)); } else if self.check(&TokenType::If) { diff --git a/src/syntax/expr.rs b/src/syntax/expr.rs index 7de6258c2..317e38164 100644 --- a/src/syntax/expr.rs +++ b/src/syntax/expr.rs @@ -569,6 +569,9 @@ pub struct UnsafeBlockExpr { /// The program wrote this block as the body of a closure, `|x| { .. }`. It is a plain block, /// so the code in it cannot do what needs `unsafe`. pub closure_body: bool, + /// A task body: the variables from outside that the task moves or copies (T4), set by the + /// checker. The task takes each one at its `spawn`, and then uses a copy of its own. + pub takes: Vec, } impl UnsafeBlockExpr { pub fn new(stmts: Vec, ret: Option>, span: Span) -> Self { @@ -582,6 +585,7 @@ impl UnsafeBlockExpr { cancels_on_err: None, value_ty: None, closure_body: false, + takes: Vec::new(), } } } @@ -1964,6 +1968,7 @@ impl Expr { cancels_on_err: e.cancels_on_err.as_ref().map(|t| t.substitute(mapping)), value_ty: e.value_ty.as_ref().map(|t| t.substitute(mapping)), closure_body: e.closure_body, + takes: e.takes.clone(), }), Expr::StructInit(e) => { let mut new_name = e.name.clone(); diff --git a/tests/backend/pass/values_moved_into_tasks_in_a_loop_are_the_values_of_their_pass.vx b/tests/backend/pass/values_moved_into_tasks_in_a_loop_are_the_values_of_their_pass.vx new file mode 100644 index 000000000..3a6e57f42 --- /dev/null +++ b/tests/backend/pass/values_moved_into_tasks_in_a_loop_are_the_values_of_their_pass.vx @@ -0,0 +1,234 @@ +//===- values_moved_into_tasks_in_a_loop_are_the_values_of_their_pass.vx -*- Vx -*-===// +// +// Part of the Vx Project, under the Apache License v2.0 with LLVM Exceptions. +// See LICENSE for license information. +// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception +// +//===----------------------------------------------------------------------===// +// In each pass of a loop, a `spawn` starts a task that takes a local of that pass. Each task must +// see the value of its own pass, also when the loop gives the local a new value before the task +// runs. Each task sends `1000 * pass + value` on a channel, and the main code prints the values +// in the order of the passes. +// +// - `receiver_per_pass`: each task moves the `Receiver` of its own channel. +// - `struct_with_a_sender`: each task moves a struct that holds a `Sender` and an `id`. +// - `sender_two_fields_deep`: the `Sender` is in a struct in a struct. +// - `one_field_moved`: each task moves one field of a struct and reads another. +// - `copy_struct_read_by_field`: each task reads one field of a `Copy` struct. +// - `borrow_joined_in_the_same_pass`: each task writes a field of a struct of its pass, and the +// pass joins the task. The task must write the struct itself, not a copy, so the main code +// then reads the value that the task wrote. +// +// RUN: vxc %s 2>&1 | FileCheck %s --implicit-check-not=Error +// RUN: env VX_TASK_RUNTIME=threads vxc %s 2>&1 | FileCheck %s --implicit-check-not=Error +// RUN: env VX_TASK_RUNTIME=shared vxc %s 2>&1 | FileCheck %s --implicit-check-not=Error +// RUN: env VX_TASK_SEED=1 vxc %s 2>&1 | FileCheck %s --implicit-check-not=Error +// RUN: env VX_TASK_SEED=2 vxc %s 2>&1 | FileCheck %s --implicit-check-not=Error +// RUN: vxc %s --legacy-codegen 2>&1 | FileCheck %s --implicit-check-not=Error +// CHECK: {{^}}receiver_per_pass: pass 0 got 100{{$}} +// CHECK-NEXT: {{^}}receiver_per_pass: pass 1 got 101{{$}} +// CHECK-NEXT: {{^}}receiver_per_pass: pass 2 got 102{{$}} +// CHECK-NEXT: {{^}}struct_with_a_sender: pass 0 got 0{{$}} +// CHECK-NEXT: {{^}}struct_with_a_sender: pass 1 got 1{{$}} +// CHECK-NEXT: {{^}}struct_with_a_sender: pass 2 got 2{{$}} +// CHECK-NEXT: {{^}}sender_two_fields_deep: pass 0 got 0{{$}} +// CHECK-NEXT: {{^}}sender_two_fields_deep: pass 1 got 1{{$}} +// CHECK-NEXT: {{^}}sender_two_fields_deep: pass 2 got 2{{$}} +// CHECK-NEXT: {{^}}one_field_moved: pass 0 got 200{{$}} +// CHECK-NEXT: {{^}}one_field_moved: pass 1 got 201{{$}} +// CHECK-NEXT: {{^}}one_field_moved: pass 2 got 202{{$}} +// CHECK-NEXT: {{^}}copy_struct_read_by_field: pass 0 got 0{{$}} +// CHECK-NEXT: {{^}}copy_struct_read_by_field: pass 1 got 1{{$}} +// CHECK-NEXT: {{^}}copy_struct_read_by_field: pass 2 got 2{{$}} +// CHECK-NEXT: {{^}}borrow_joined_in_the_same_pass: pass 0 got 100{{$}} +// CHECK-NEXT: {{^}}borrow_joined_in_the_same_pass: pass 1 got 101{{$}} +// CHECK-NEXT: {{^}}borrow_joined_in_the_same_pass: pass 2 got 102{{$}} + +import std::sync::channel; +import std::vec; + +// The number of passes of each loop. +const PASSES : i64 = 3; + +fn send(tx : &Sender, value : i64) -> void { + match tx.send(value) { + Result>::Ok() => {} + Result>::Err(_e) => { + println!("a send failed"); + } + } +} + +fn receive(rx : &Receiver) -> i64 { + match rx.recv() { + Result::Ok(v) => { + return v; + } + Result::Err(_e) => { + return -1; + } + } +} + +// Receives one `1000 * pass + value` for each pass, and prints the values in the order of the +// passes. +fn print_by_pass(name : *const i8, rx : &Receiver) -> void { + let mut got : Vec = Vec::new(); + for _p in 0i64..PASSES { + got.push(-1i64); + } + for _k in 0i64..PASSES { + let r = receive(rx); + got.set((r / 1000i64) as i32, r % 1000i64); + } + for p in 0i64..PASSES { + println!("{}: pass {} got {}", name, p, got.get(p as i32)); + } +} + +fn read_own_channel(pass : i64, rx : Receiver, out : Sender) -> void { + send(&out, 1000i64 * pass + receive(&rx)); +} + +fn receiver_per_pass() -> void { + let (out, results) = channel(8); + tasks { + for i in 0i64..PASSES { + let (tx, rx) = channel(1); + send(&tx, 100i64 + i); + let out_of_pass = out.clone(); + spawn { + read_own_channel(i, rx, out_of_pass); + }; + } + }; + print_by_pass("receiver_per_pass", &results); +} + +struct WithSender { + id : i64, + tx : Sender, +} + +fn send_id(pass : i64, w : WithSender) -> void { + send(&w.tx, 1000i64 * pass + w.id); +} + +fn struct_with_a_sender() -> void { + let (out, results) = channel(8); + tasks { + for i in 0i64..PASSES { + let w = WithSender { + id: i, tx: out.clone() + }; + spawn { + send_id(i, w); + }; + } + }; + print_by_pass("struct_with_a_sender", &results); +} + +struct Outer { + inner : WithSender, +} + +fn send_inner_id(pass : i64, o : Outer) -> void { + send_id(pass, o.inner); +} + +fn sender_two_fields_deep() -> void { + let (out, results) = channel(8); + tasks { + for i in 0i64..PASSES { + let o = Outer { + inner: WithSender { + id: i, tx: out.clone() + } + }; + spawn { + send_inner_id(i, o); + }; + } + }; + print_by_pass("sender_two_fields_deep", &results); +} + +struct WithReceiver { + id : i64, + rx : Receiver, +} + +fn send_from_channel(pass : i64, rx : Receiver, out : &Sender) -> void { + send(out, 1000i64 * pass + receive(&rx)); +} + +fn one_field_moved() -> void { + let (out, results) = channel(8); + tasks { + for i in 0i64..PASSES { + let (tx, rx) = channel(1); + send(&tx, 200i64 + i); + let w = WithReceiver { + id: i, rx: rx + }; + let out_of_pass = out.clone(); + spawn { + send_from_channel(w.id, w.rx, &out_of_pass); + }; + } + }; + print_by_pass("one_field_moved", &results); +} + +struct Point { + id : i64, + y : i64, +} + +impl Copy for Point {} + +fn copy_struct_read_by_field() -> void { + let (out, results) = channel(8); + tasks { + for i in 0i64..PASSES { + let p = Point { + id: i, y: 0i64 + }; + let out_of_pass = out.clone(); + spawn { + send(&out_of_pass, 1000i64 * i + p.id + p.y); + }; + } + }; + print_by_pass("copy_struct_read_by_field", &results); +} + +struct Counter { + n : i64, +} + +fn borrow_joined_in_the_same_pass() -> void { + tasks { + for i in 0i64..PASSES { + let mut c = Counter { + n: i + }; + let h = spawn { + c.n = c.n + 100i64; + }; + h.join(); + println!("borrow_joined_in_the_same_pass: pass {} got {}", i, c.n); + } + }; +} + +fn main() -> i32 { + receiver_per_pass(); + struct_with_a_sender(); + sender_two_fields_deep(); + one_field_moved(); + copy_struct_read_by_field(); + borrow_joined_in_the_same_pass(); + return 0; +} diff --git a/tests/optimizations/pass/a_task_copies_a_slot_that_it_takes_at_its_spawn.mlr b/tests/optimizations/pass/a_task_copies_a_slot_that_it_takes_at_its_spawn.mlr new file mode 100644 index 000000000..584ec476b --- /dev/null +++ b/tests/optimizations/pass/a_task_copies_a_slot_that_it_takes_at_its_spawn.mlr @@ -0,0 +1,52 @@ +// RUN: vx-opt %s --pass-pipeline="builtin.module(convert-vx-to-standard)" | FileCheck %s + +// A loop starts a task in each pass. The task reads a field of a struct of its pass. The loop +// gives the struct's slot a new value in each pass, so the `spawn` must copy the slot: the task +// then reads its own copy, not the slot, which already holds the value of a later pass. + +module { + func.func private @use(i64) + + // The `spawn` loads the whole struct from the slot and puts it in the task's environment. + // CHECK-LABEL: func.func @main + // CHECK: %[[VALUE:.*]] = llvm.load %[[SLOT:.*]] : !llvm.ptr -> !llvm.struct<(i64, i64)> + // CHECK: llvm.store %[[VALUE]], %{{.*}} : !llvm.struct<(i64, i64)>, !llvm.ptr + // CHECK: llvm.call @vx_task_start_at + + // The task puts the value in a slot of its own, and reads the field there. + // CHECK-LABEL: func.func private @vx_task_ + // CHECK: %[[COPY:.*]] = llvm.load %{{.*}} : !llvm.ptr -> !llvm.struct<(i64, i64)> + // CHECK: %[[OWN:.*]] = llvm.alloca %{{.*}} x !llvm.struct<(i64, i64)> + // CHECK: llvm.store %[[COPY]], %[[OWN]] + // CHECK: llvm.getelementptr %[[OWN]][0, 0] + // CHECK-NOT: vx.take_at_spawn + func.func @main() { + vx.spawn topology(10) { + %c0 = arith.constant 0 : i64 + %c1 = arith.constant 1 : i64 + %c3 = arith.constant 3 : i64 + %one = llvm.mlir.constant(1 : i32) : i32 + %slot = llvm.alloca %one x !llvm.struct<(i64, i64)> : (i32) -> !llvm.ptr + cf.br ^head(%c0 : i64) + ^head(%i: i64): + %more = arith.cmpi slt, %i, %c3 : i64 + cf.cond_br %more, ^body, ^exit + ^body: + llvm.intr.lifetime.start %slot : !llvm.ptr + %id = llvm.getelementptr %slot[0, 0] : (!llvm.ptr) -> !llvm.ptr, !llvm.struct<(i64, i64)> + llvm.store %i, %id : i64, !llvm.ptr + vx.spawn topology(11) { + "vx.take_at_spawn"(%slot) {value_type = !llvm.struct<(i64, i64)>} : (!llvm.ptr) -> () + %field = llvm.getelementptr %slot[0, 0] : (!llvm.ptr) -> !llvm.ptr, !llvm.struct<(i64, i64)> + %v = llvm.load %field : !llvm.ptr -> i64 + func.call @use(%v) : (i64) -> () + vx.yield + } + %next = arith.addi %i, %c1 : i64 + cf.br ^head(%next : i64) + ^exit: + vx.yield + } + return + } +} diff --git a/tests/optimizations/pass/a_task_that_reads_a_slot_a_loop_writes_again_is_refused.mlr b/tests/optimizations/pass/a_task_that_reads_a_slot_a_loop_writes_again_is_refused.mlr new file mode 100644 index 000000000..fa2d9f9f7 --- /dev/null +++ b/tests/optimizations/pass/a_task_that_reads_a_slot_a_loop_writes_again_is_refused.mlr @@ -0,0 +1,40 @@ +// RUN: not vx-opt %s --pass-pipeline="builtin.module(convert-vx-to-standard)" 2>&1 | FileCheck %s + +// A loop starts a task in each pass, and the task reads a field of a struct of its pass. Here the +// task has no `vx.take_at_spawn` for the struct, so it would get the address of the slot. The +// loop gives the slot a new value in each pass, before the task reads it. The lowering must stop +// with an error, and not make a task that can read the value of a later pass. + +module { + func.func private @use(i64) + + // CHECK: error: the compiler gives this task the address of a variable, and the loop around the `spawn` gives the variable a new value in each pass. So the task can read the value of a later pass. This is a bug in the compiler + func.func @main() { + vx.spawn topology(10) { + %c0 = arith.constant 0 : i64 + %c1 = arith.constant 1 : i64 + %c3 = arith.constant 3 : i64 + %one = llvm.mlir.constant(1 : i32) : i32 + %slot = llvm.alloca %one x !llvm.struct<(i64, i64)> : (i32) -> !llvm.ptr + cf.br ^head(%c0 : i64) + ^head(%i: i64): + %more = arith.cmpi slt, %i, %c3 : i64 + cf.cond_br %more, ^body, ^exit + ^body: + llvm.intr.lifetime.start %slot : !llvm.ptr + %id = llvm.getelementptr %slot[0, 0] : (!llvm.ptr) -> !llvm.ptr, !llvm.struct<(i64, i64)> + llvm.store %i, %id : i64, !llvm.ptr + vx.spawn topology(11) { + %field = llvm.getelementptr %slot[0, 0] : (!llvm.ptr) -> !llvm.ptr, !llvm.struct<(i64, i64)> + %v = llvm.load %field : !llvm.ptr -> i64 + func.call @use(%v) : (i64) -> () + vx.yield + } + %next = arith.addi %i, %c1 : i64 + cf.br ^head(%next : i64) + ^exit: + vx.yield + } + return + } +} From 107a71471de8dc62796ca5160dde53aa1c1cb018 Mon Sep 17 00:00:00 2001 From: Minzy Fox Date: Tue, 1 Dec 2026 19:33:49 -0800 Subject: [PATCH 2/2] tests: reject leftover spawn markers throughout lowered output Use --implicit-check-not=take_at_spawn so FileCheck checks the whole output. Remove the scoped CHECK-NOT that missed markers before the last field access. The real lowered output passed. Markers inserted independently at the start of main and the task failed the intended assertion. The refusal test, all six runtime modes, and backend coverage also passed. Issue: #4345 --- .../pass/a_task_copies_a_slot_that_it_takes_at_its_spawn.mlr | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/tests/optimizations/pass/a_task_copies_a_slot_that_it_takes_at_its_spawn.mlr b/tests/optimizations/pass/a_task_copies_a_slot_that_it_takes_at_its_spawn.mlr index 584ec476b..beff3dcef 100644 --- a/tests/optimizations/pass/a_task_copies_a_slot_that_it_takes_at_its_spawn.mlr +++ b/tests/optimizations/pass/a_task_copies_a_slot_that_it_takes_at_its_spawn.mlr @@ -1,4 +1,4 @@ -// RUN: vx-opt %s --pass-pipeline="builtin.module(convert-vx-to-standard)" | FileCheck %s +// RUN: vx-opt %s --pass-pipeline="builtin.module(convert-vx-to-standard)" | FileCheck %s --implicit-check-not=take_at_spawn // A loop starts a task in each pass. The task reads a field of a struct of its pass. The loop // gives the struct's slot a new value in each pass, so the `spawn` must copy the slot: the task @@ -19,7 +19,6 @@ module { // CHECK: %[[OWN:.*]] = llvm.alloca %{{.*}} x !llvm.struct<(i64, i64)> // CHECK: llvm.store %[[COPY]], %[[OWN]] // CHECK: llvm.getelementptr %[[OWN]][0, 0] - // CHECK-NOT: vx.take_at_spawn func.func @main() { vx.spawn topology(10) { %c0 = arith.constant 0 : i64