Skip to content

Commit 58f5089

Browse files
Rollup merge of #150444 - Sa4dUs:offload-intrinsic2, r=ZuseZ4
Expose kernel launch options as offload intrinsic args Allows modifying the workgroup and thread grid dimensions directly from the intrinsic call. ```rust core::intrinsics::offload(_kernel_1, [256, 1, 1], [32, 1, 1], (x,)) ``` r? `@ZuseZ4`
2 parents 51faf00 + 58e2610 commit 58f5089

7 files changed

Lines changed: 108 additions & 25 deletions

File tree

compiler/rustc_codegen_llvm/src/builder/gpu_offload.rs

Lines changed: 64 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,9 @@ use std::ffi::CString;
22

33
use llvm::Linkage::*;
44
use rustc_abi::Align;
5+
use rustc_codegen_ssa::mir::operand::{OperandRef, OperandValue};
56
use rustc_codegen_ssa::traits::{BaseTypeCodegenMethods, BuilderMethods};
7+
use rustc_middle::bug;
68
use rustc_middle::ty::offload_meta::OffloadMetadata;
79

810
use crate::builder::Builder;
@@ -69,6 +71,57 @@ impl<'ll> OffloadGlobals<'ll> {
6971
}
7072
}
7173

74+
pub(crate) struct OffloadKernelDims<'ll> {
75+
num_workgroups: &'ll Value,
76+
threads_per_block: &'ll Value,
77+
workgroup_dims: &'ll Value,
78+
thread_dims: &'ll Value,
79+
}
80+
81+
impl<'ll> OffloadKernelDims<'ll> {
82+
pub(crate) fn from_operands<'tcx>(
83+
builder: &mut Builder<'_, 'll, 'tcx>,
84+
workgroup_op: &OperandRef<'tcx, &'ll llvm::Value>,
85+
thread_op: &OperandRef<'tcx, &'ll llvm::Value>,
86+
) -> Self {
87+
let cx = builder.cx;
88+
let arr_ty = cx.type_array(cx.type_i32(), 3);
89+
let four = Align::from_bytes(4).unwrap();
90+
91+
let OperandValue::Ref(place) = workgroup_op.val else {
92+
bug!("expected array operand by reference");
93+
};
94+
let workgroup_val = builder.load(arr_ty, place.llval, four);
95+
96+
let OperandValue::Ref(place) = thread_op.val else {
97+
bug!("expected array operand by reference");
98+
};
99+
let thread_val = builder.load(arr_ty, place.llval, four);
100+
101+
fn mul_dim3<'ll, 'tcx>(
102+
builder: &mut Builder<'_, 'll, 'tcx>,
103+
arr: &'ll Value,
104+
) -> &'ll Value {
105+
let x = builder.extract_value(arr, 0);
106+
let y = builder.extract_value(arr, 1);
107+
let z = builder.extract_value(arr, 2);
108+
109+
let xy = builder.mul(x, y);
110+
builder.mul(xy, z)
111+
}
112+
113+
let num_workgroups = mul_dim3(builder, workgroup_val);
114+
let threads_per_block = mul_dim3(builder, thread_val);
115+
116+
OffloadKernelDims {
117+
workgroup_dims: workgroup_val,
118+
thread_dims: thread_val,
119+
num_workgroups,
120+
threads_per_block,
121+
}
122+
}
123+
}
124+
72125
// ; Function Attrs: nounwind
73126
// declare i32 @__tgt_target_kernel(ptr, i64, i32, i32, ptr, ptr) #2
74127
fn generate_launcher<'ll>(cx: &CodegenCx<'ll, '_>) -> (&'ll llvm::Value, &'ll llvm::Type) {
@@ -204,12 +257,12 @@ impl KernelArgsTy {
204257
num_args: u64,
205258
memtransfer_types: &'ll Value,
206259
geps: [&'ll Value; 3],
260+
workgroup_dims: &'ll Value,
261+
thread_dims: &'ll Value,
207262
) -> [(Align, &'ll Value); 13] {
208263
let four = Align::from_bytes(4).expect("4 Byte alignment should work");
209264
let eight = Align::EIGHT;
210265

211-
let ti32 = cx.type_i32();
212-
let ci32_0 = cx.get_const_i32(0);
213266
[
214267
(four, cx.get_const_i32(KernelArgsTy::OFFLOAD_VERSION)),
215268
(four, cx.get_const_i32(num_args)),
@@ -222,8 +275,8 @@ impl KernelArgsTy {
222275
(eight, cx.const_null(cx.type_ptr())), // dbg
223276
(eight, cx.get_const_i64(KernelArgsTy::TRIPCOUNT)),
224277
(eight, cx.get_const_i64(KernelArgsTy::FLAGS)),
225-
(four, cx.const_array(ti32, &[cx.get_const_i32(2097152), ci32_0, ci32_0])),
226-
(four, cx.const_array(ti32, &[cx.get_const_i32(256), ci32_0, ci32_0])),
278+
(four, workgroup_dims),
279+
(four, thread_dims),
227280
(four, cx.get_const_i32(0)),
228281
]
229282
}
@@ -413,10 +466,13 @@ pub(crate) fn gen_call_handling<'ll, 'tcx>(
413466
types: &[&Type],
414467
metadata: &[OffloadMetadata],
415468
offload_globals: &OffloadGlobals<'ll>,
469+
offload_dims: &OffloadKernelDims<'ll>,
416470
) {
417471
let cx = builder.cx;
418472
let OffloadKernelGlobals { offload_sizes, offload_entry, memtransfer_types, region_id } =
419473
offload_data;
474+
let OffloadKernelDims { num_workgroups, threads_per_block, workgroup_dims, thread_dims } =
475+
offload_dims;
420476

421477
let tgt_decl = offload_globals.launcher_fn;
422478
let tgt_target_kernel_ty = offload_globals.launcher_ty;
@@ -554,7 +610,8 @@ pub(crate) fn gen_call_handling<'ll, 'tcx>(
554610
num_args,
555611
s_ident_t,
556612
);
557-
let values = KernelArgsTy::new(&cx, num_args, memtransfer_types, geps);
613+
let values =
614+
KernelArgsTy::new(&cx, num_args, memtransfer_types, geps, workgroup_dims, thread_dims);
558615

559616
// Step 3)
560617
// Here we fill the KernelArgsTy, see the documentation above
@@ -567,9 +624,8 @@ pub(crate) fn gen_call_handling<'ll, 'tcx>(
567624
s_ident_t,
568625
// FIXME(offload) give users a way to select which GPU to use.
569626
cx.get_const_i64(u64::MAX), // MAX == -1.
570-
// FIXME(offload): Don't hardcode the numbers of threads in the future.
571-
cx.get_const_i32(2097152),
572-
cx.get_const_i32(256),
627+
num_workgroups,
628+
threads_per_block,
573629
region_id,
574630
a5,
575631
];

compiler/rustc_codegen_llvm/src/intrinsic.rs

Lines changed: 4 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -30,7 +30,7 @@ use tracing::debug;
3030
use crate::abi::FnAbiLlvmExt;
3131
use crate::builder::Builder;
3232
use crate::builder::autodiff::{adjust_activity_to_abi, generate_enzyme_call};
33-
use crate::builder::gpu_offload::{gen_call_handling, gen_define_handling};
33+
use crate::builder::gpu_offload::{OffloadKernelDims, gen_call_handling, gen_define_handling};
3434
use crate::context::CodegenCx;
3535
use crate::declare::declare_raw_fn;
3636
use crate::errors::{
@@ -1384,7 +1384,8 @@ fn codegen_offload<'ll, 'tcx>(
13841384
}
13851385
};
13861386

1387-
let args = get_args_from_tuple(bx, args[1], fn_target);
1387+
let offload_dims = OffloadKernelDims::from_operands(bx, &args[1], &args[2]);
1388+
let args = get_args_from_tuple(bx, args[3], fn_target);
13881389
let target_symbol = symbol_name_for_instance_in_crate(tcx, fn_target, LOCAL_CRATE);
13891390

13901391
let sig = tcx.fn_sig(fn_target.def_id()).skip_binder().skip_binder();
@@ -1403,7 +1404,7 @@ fn codegen_offload<'ll, 'tcx>(
14031404
}
14041405
};
14051406
let offload_data = gen_define_handling(&cx, &metadata, &types, target_symbol, offload_globals);
1406-
gen_call_handling(bx, &offload_data, &args, &types, &metadata, offload_globals);
1407+
gen_call_handling(bx, &offload_data, &args, &types, &metadata, offload_globals, &offload_dims);
14071408
}
14081409

14091410
fn get_args_from_tuple<'ll, 'tcx>(

compiler/rustc_hir_analysis/src/check/intrinsic.rs

Lines changed: 12 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use rustc_abi::ExternAbi;
44
use rustc_errors::DiagMessage;
55
use rustc_hir::{self as hir, LangItem};
66
use rustc_middle::traits::{ObligationCause, ObligationCauseCode};
7-
use rustc_middle::ty::{self, Ty, TyCtxt};
7+
use rustc_middle::ty::{self, Const, Ty, TyCtxt};
88
use rustc_span::def_id::LocalDefId;
99
use rustc_span::{Span, Symbol, sym};
1010

@@ -315,7 +315,17 @@ pub(crate) fn check_intrinsic_type(
315315
let type_id = tcx.type_of(tcx.lang_items().type_id().unwrap()).instantiate_identity();
316316
(0, 0, vec![type_id, type_id], tcx.types.bool)
317317
}
318-
sym::offload => (3, 0, vec![param(0), param(1)], param(2)),
318+
sym::offload => (
319+
3,
320+
0,
321+
vec![
322+
param(0),
323+
Ty::new_array_with_const_len(tcx, tcx.types.u32, Const::from_target_usize(tcx, 3)),
324+
Ty::new_array_with_const_len(tcx, tcx.types.u32, Const::from_target_usize(tcx, 3)),
325+
param(1),
326+
],
327+
param(2),
328+
),
319329
sym::offset => (2, 0, vec![param(0), param(1)], param(0)),
320330
sym::arith_offset => (
321331
1,

library/core/src/intrinsics/mod.rs

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -3385,11 +3385,17 @@ pub const fn autodiff<F, G, T: crate::marker::Tuple, R>(f: F, df: G, args: T) ->
33853385
/// - `T`: A tuple of arguments passed to `f`.
33863386
/// - `R`: The return type of the kernel.
33873387
///
3388+
/// Arguments:
3389+
/// - `f`: The kernel function to offload.
3390+
/// - `workgroup_dim`: A 3D size specifying the number of workgroups to launch.
3391+
/// - `thread_dim`: A 3D size specifying the number of threads per workgroup.
3392+
/// - `args`: A tuple of arguments forwarded to `f`.
3393+
///
33883394
/// Example usage (pseudocode):
33893395
///
33903396
/// ```rust,ignore (pseudocode)
33913397
/// fn kernel(x: *mut [f64; 128]) {
3392-
/// core::intrinsics::offload(kernel_1, (x,))
3398+
/// core::intrinsics::offload(kernel_1, [256, 1, 1], [32, 1, 1], (x,))
33933399
/// }
33943400
///
33953401
/// #[cfg(target_os = "linux")]
@@ -3408,7 +3414,12 @@ pub const fn autodiff<F, G, T: crate::marker::Tuple, R>(f: F, df: G, args: T) ->
34083414
/// <https://clang.llvm.org/docs/OffloadingDesign.html>.
34093415
#[rustc_nounwind]
34103416
#[rustc_intrinsic]
3411-
pub const fn offload<F, T: crate::marker::Tuple, R>(f: F, args: T) -> R;
3417+
pub const fn offload<F, T: crate::marker::Tuple, R>(
3418+
f: F,
3419+
workgroup_dim: [u32; 3],
3420+
thread_dim: [u32; 3],
3421+
args: T,
3422+
) -> R;
34123423

34133424
/// Inform Miri that a given pointer definitely has a certain alignment.
34143425
#[cfg(miri)]

src/doc/rustc-dev-guide/src/offload/usage.md

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -57,7 +57,7 @@ fn main() {
5757

5858
#[inline(never)]
5959
unsafe fn kernel(x: *mut [f64; 256]) {
60-
core::intrinsics::offload(kernel_1, (x,))
60+
core::intrinsics::offload(_kernel_1, [256, 1, 1], [32, 1, 1], (x,))
6161
}
6262

6363
#[cfg(target_os = "linux")]

tests/codegen-llvm/gpu_offload/control_flow.rs

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,14 +21,19 @@
2121
// CHECK-NOT define
2222
// CHECK: bb3
2323
// CHECK: call void @__tgt_target_data_begin_mapper(ptr nonnull @anon.{{.*}}.1, i64 -1, i32 1, ptr nonnull %.offload_baseptrs, ptr nonnull %.offload_ptrs, ptr nonnull %.offload_sizes, ptr nonnull @.offload_maptypes.foo, ptr null, ptr null)
24-
// CHECK: %10 = call i32 @__tgt_target_kernel(ptr nonnull @anon.{{.*}}.1, i64 -1, i32 2097152, i32 256, ptr nonnull @.foo.region_id, ptr nonnull %kernel_args)
24+
// CHECK: %10 = call i32 @__tgt_target_kernel(ptr nonnull @anon.{{.*}}.1, i64 -1, i32 256, i32 32, ptr nonnull @.foo.region_id, ptr nonnull %kernel_args)
2525
// CHECK-NEXT: call void @__tgt_target_data_end_mapper(ptr nonnull @anon.{{.*}}.1, i64 -1, i32 1, ptr nonnull %.offload_baseptrs, ptr nonnull %.offload_ptrs, ptr nonnull %.offload_sizes, ptr nonnull @.offload_maptypes.foo, ptr null, ptr null)
2626
#[unsafe(no_mangle)]
2727
unsafe fn main() {
2828
let A = [1.0, 1.0, 1.0, 1.0, 1.0, 1.0];
2929

3030
for i in 0..100 {
31-
core::intrinsics::offload::<_, _, ()>(foo, (A.as_ptr() as *const [f32; 6],));
31+
core::intrinsics::offload::<_, _, ()>(
32+
foo,
33+
[256, 1, 1],
34+
[32, 1, 1],
35+
(A.as_ptr() as *const [f32; 6],),
36+
);
3237
}
3338
}
3439

tests/codegen-llvm/gpu_offload/gpu_host.rs

Lines changed: 7 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -82,14 +82,14 @@ fn main() {
8282
// CHECK-NEXT: %5 = getelementptr inbounds nuw i8, ptr %kernel_args, i64 40
8383
// CHECK-NEXT: %6 = getelementptr inbounds nuw i8, ptr %kernel_args, i64 72
8484
// CHECK-NEXT: call void @llvm.memset.p0.i64(ptr noundef nonnull align 8 dereferenceable(32) %5, i8 0, i64 32, i1 false)
85-
// CHECK-NEXT: store <4 x i32> <i32 2097152, i32 0, i32 0, i32 256>, ptr %6, align 8
86-
// CHECK-NEXT: %.fca.1.gep3 = getelementptr inbounds nuw i8, ptr %kernel_args, i64 88
87-
// CHECK-NEXT: store i32 0, ptr %.fca.1.gep3, align 8
88-
// CHECK-NEXT: %.fca.2.gep4 = getelementptr inbounds nuw i8, ptr %kernel_args, i64 92
89-
// CHECK-NEXT: store i32 0, ptr %.fca.2.gep4, align 4
85+
// CHECK-NEXT: store <4 x i32> <i32 256, i32 1, i32 1, i32 32>, ptr %6, align 8
86+
// CHECK-NEXT: %.fca.1.gep5 = getelementptr inbounds nuw i8, ptr %kernel_args, i64 88
87+
// CHECK-NEXT: store i32 1, ptr %.fca.1.gep5, align 8
88+
// CHECK-NEXT: %.fca.2.gep7 = getelementptr inbounds nuw i8, ptr %kernel_args, i64 92
89+
// CHECK-NEXT: store i32 1, ptr %.fca.2.gep7, align 4
9090
// CHECK-NEXT: %7 = getelementptr inbounds nuw i8, ptr %kernel_args, i64 96
9191
// CHECK-NEXT: store i32 0, ptr %7, align 8
92-
// CHECK-NEXT: %8 = call i32 @__tgt_target_kernel(ptr nonnull @anon.{{.*}}.1, i64 -1, i32 2097152, i32 256, ptr nonnull @._kernel_1.region_id, ptr nonnull %kernel_args)
92+
// CHECK-NEXT: %8 = call i32 @__tgt_target_kernel(ptr nonnull @anon.{{.*}}.1, i64 -1, i32 256, i32 32, ptr nonnull @._kernel_1.region_id, ptr nonnull %kernel_args)
9393
// CHECK-NEXT: call void @__tgt_target_data_end_mapper(ptr nonnull @anon.{{.*}}.1, i64 -1, i32 1, ptr nonnull %.offload_baseptrs, ptr nonnull %.offload_ptrs, ptr nonnull %.offload_sizes, ptr nonnull @.offload_maptypes._kernel_1, ptr null, ptr null)
9494
// CHECK-NEXT: call void @__tgt_unregister_lib(ptr nonnull %EmptyDesc)
9595
// CHECK-NEXT: ret void
@@ -98,7 +98,7 @@ fn main() {
9898
#[unsafe(no_mangle)]
9999
#[inline(never)]
100100
pub fn kernel_1(x: &mut [f32; 256]) {
101-
core::intrinsics::offload(_kernel_1, (x,))
101+
core::intrinsics::offload(_kernel_1, [256, 1, 1], [32, 1, 1], (x,))
102102
}
103103

104104
#[unsafe(no_mangle)]

0 commit comments

Comments
 (0)