1use crate::attr::{AggregatedSpirvAttributes, IntrinsicType};
5use crate::codegen_cx::CodegenCx;
6use crate::maybe_pqp_cg_ssa::traits::ConstCodegenMethods as _;
7use crate::spirv_type::{SpirvType, name_type_id};
8use itertools::Itertools;
9use rspirv::spirv::{Dim, ImageFormat, StorageClass, Word};
10use rustc_abi::ExternAbi as Abi;
11use rustc_abi::{
12 Align, BackendRepr, FieldIdx, FieldsShape, Primitive, Scalar, Size, VariantIdx, Variants,
13};
14use rustc_data_structures::fx::FxHashMap;
15use rustc_errors::ErrorGuaranteed;
16use rustc_index::Idx;
17use rustc_middle::ty::layout::{FnAbiOf, LayoutOf, TyAndLayout};
18use rustc_middle::ty::{
19 self, Const, CoroutineArgs, CoroutineArgsExt as _, FloatTy, IntTy, PolyFnSig, Ty, TyCtxt,
20 TyKind, UintTy, ValTreeKindExt,
21};
22use rustc_middle::ty::{GenericArgsRef, ScalarInt};
23use rustc_middle::util::Providers;
24use rustc_middle::{bug, span_bug};
25use rustc_session::config::OptLevel;
26use rustc_span::DUMMY_SP;
27use rustc_span::def_id::DefId;
28use rustc_span::{Span, Symbol};
29use rustc_target::callconv::{ArgAbi, ArgAttributes, FnAbi, PassMode};
30use std::cell::RefCell;
31use std::collections::hash_map::Entry;
32use std::fmt;
33
34fn rewrite_c_abi_to_rust<'tcx>(
35 fn_sig: ty::EarlyBinder<'tcx, ty::PolyFnSig<'tcx>>,
36) -> ty::EarlyBinder<'tcx, ty::PolyFnSig<'tcx>> {
37 fn_sig.map_bound(|outer| {
38 outer.map_bound(|inner: ty::FnSig<'_>| {
39 if let Abi::C { .. } = inner.abi() {
40 ty::FnSig {
41 fn_sig_kind: inner.fn_sig_kind.set_abi(Abi::Rust),
42 ..inner
43 }
44 } else {
45 inner
46 }
47 })
48 })
49}
50
51pub(crate) fn provide(providers: &mut Providers) {
52 providers.queries.fn_sig = |tcx, def_id| {
67 let result = (rustc_interface::DEFAULT_QUERY_PROVIDERS.queries.fn_sig)(tcx, def_id);
70 rewrite_c_abi_to_rust(result)
71 };
72 providers.extern_queries.fn_sig = |tcx, def_id| {
73 let result = (rustc_interface::DEFAULT_QUERY_PROVIDERS
76 .extern_queries
77 .fn_sig)(tcx, def_id);
78 rewrite_c_abi_to_rust(result)
79 };
80
81 fn readjust_fn_abi<'tcx>(
86 tcx: TyCtxt<'tcx>,
87 fn_abi: &'tcx FnAbi<'tcx, Ty<'tcx>>,
88 ) -> &'tcx FnAbi<'tcx, Ty<'tcx>> {
89 let readjust_arg_abi = |arg: &ArgAbi<'tcx, Ty<'tcx>>| {
90 let mut arg = ArgAbi::new(arg.layout, |_, _| ArgAttributes::new());
91 arg.mode = if let PassMode::Indirect { .. } = arg.mode {
95 PassMode::Direct(ArgAttributes::new())
96 } else if arg.layout.is_zst() {
97 PassMode::Ignore
98 } else if let PassMode::Ignore | PassMode::Direct(..) | PassMode::Pair(..) = arg.mode {
99 arg.mode
100 } else {
101 panic!("Tried to make {:?} direct", arg.mode)
102 };
103
104 if arg.layout.is_zst() {
106 arg.mode = PassMode::Ignore;
107 }
108
109 arg
110 };
111 tcx.arena.alloc(FnAbi {
112 args: fn_abi.args.iter().map(readjust_arg_abi).collect(),
113 ret: readjust_arg_abi(&fn_abi.ret),
114
115 c_variadic: fn_abi.c_variadic,
119 fixed_count: fn_abi.fixed_count,
120 conv: fn_abi.conv,
121 can_unwind: fn_abi.can_unwind,
122 })
123 }
124 providers.queries.fn_abi_of_fn_ptr = |tcx, key| {
125 let result = (rustc_interface::DEFAULT_QUERY_PROVIDERS
126 .queries
127 .fn_abi_of_fn_ptr)(tcx, key);
128 Ok(readjust_fn_abi(tcx, result?))
129 };
130 providers.queries.fn_abi_of_instance_no_deduced_attrs = |tcx, key| {
131 let result = (rustc_interface::DEFAULT_QUERY_PROVIDERS
132 .queries
133 .fn_abi_of_instance_no_deduced_attrs)(tcx, key);
134 if tcx.sess.opts.optimize != OptLevel::No && tcx.sess.opts.incremental.is_none() {
139 result
140 } else {
141 Ok(readjust_fn_abi(tcx, result?))
142 }
143 };
144 providers.queries.fn_abi_of_instance_raw = |tcx, key| {
145 let result = (rustc_interface::DEFAULT_QUERY_PROVIDERS
146 .queries
147 .fn_abi_of_instance_raw)(tcx, key);
148 Ok(readjust_fn_abi(tcx, result?))
149 };
150
151 providers.queries.check_mono_item = |_, _| {};
158}
159
160#[derive(Default)]
166pub struct RecursivePointeeCache<'tcx> {
167 map: RefCell<FxHashMap<PointeeTy<'tcx>, PointeeDefState>>,
168}
169
170impl<'tcx> RecursivePointeeCache<'tcx> {
171 fn begin(&self, cx: &CodegenCx<'tcx>, span: Span, pointee: PointeeTy<'tcx>) -> Option<Word> {
172 match self.map.borrow_mut().entry(pointee) {
173 Entry::Vacant(entry) => {
176 entry.insert(PointeeDefState::Defining);
177 None
178 }
179 Entry::Occupied(mut entry) => match *entry.get() {
180 PointeeDefState::Defining => {
184 let new_id = cx.emit_global().id();
185 cx.emit_global()
189 .type_forward_pointer(new_id, StorageClass::Generic);
190 entry.insert(PointeeDefState::DefiningWithForward(new_id));
191 cx.zombie_with_span(
192 new_id,
193 span,
194 "cannot create self-referential types, even through pointers",
195 );
196 Some(new_id)
197 }
198 PointeeDefState::DefiningWithForward(id) | PointeeDefState::Defined(id) => Some(id),
202 },
203 }
204 }
205
206 fn end(
207 &self,
208 cx: &CodegenCx<'tcx>,
209 span: Span,
210 pointee: PointeeTy<'tcx>,
211 pointee_spv: Word,
212 ) -> Word {
213 match self.map.borrow_mut().entry(pointee) {
214 Entry::Vacant(_) => {
216 span_bug!(span, "RecursivePointeeCache::end should always have entry")
217 }
218 Entry::Occupied(mut entry) => match *entry.get() {
219 PointeeDefState::Defining => {
222 let id = SpirvType::Pointer {
223 pointee: pointee_spv,
224 }
225 .def(span, cx);
226 entry.insert(PointeeDefState::Defined(id));
227 id
228 }
229 PointeeDefState::DefiningWithForward(id) => {
232 entry.insert(PointeeDefState::Defined(id));
233 SpirvType::Pointer {
234 pointee: pointee_spv,
235 }
236 .def_with_id(cx, span, id)
237 }
238 PointeeDefState::Defined(_) => {
239 span_bug!(span, "RecursivePointeeCache::end defined pointer twice")
240 }
241 },
242 }
243 }
244}
245
246#[derive(Eq, PartialEq, Hash, Copy, Clone, Debug)]
247enum PointeeTy<'tcx> {
248 Ty(TyAndLayout<'tcx>),
249 Fn(PolyFnSig<'tcx>),
250}
251
252impl fmt::Display for PointeeTy<'_> {
253 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
254 match self {
255 PointeeTy::Ty(ty) => write!(f, "{}", ty.ty),
256 PointeeTy::Fn(ty) => write!(f, "{ty}"),
257 }
258 }
259}
260
261enum PointeeDefState {
262 Defining,
263 DefiningWithForward(Word),
264 Defined(Word),
265}
266
267pub trait ConvSpirvType<'tcx> {
270 fn spirv_type(&self, span: Span, cx: &CodegenCx<'tcx>) -> Word;
271}
272
273impl<'tcx> ConvSpirvType<'tcx> for PointeeTy<'tcx> {
274 fn spirv_type(&self, span: Span, cx: &CodegenCx<'tcx>) -> Word {
275 match *self {
276 PointeeTy::Ty(ty) => ty.spirv_type(span, cx),
277 PointeeTy::Fn(ty) => cx
278 .fn_abi_of_fn_ptr(ty, ty::List::empty())
279 .spirv_type(span, cx),
280 }
281 }
282}
283
284impl<'tcx> ConvSpirvType<'tcx> for FnAbi<'tcx, Ty<'tcx>> {
285 fn spirv_type(&self, span: Span, cx: &CodegenCx<'tcx>) -> Word {
286 let mut argument_types = Vec::new();
288
289 let return_type = match self.ret.mode {
290 PassMode::Ignore => SpirvType::Void.def(span, cx),
291 PassMode::Direct(_) | PassMode::Pair(..) => self.ret.layout.spirv_type(span, cx),
292 PassMode::Cast { .. } | PassMode::Indirect { .. } => span_bug!(
293 span,
294 "query hooks should've made this `PassMode` impossible: {:#?}",
295 self.ret
296 ),
297 };
298
299 for arg in self.args.iter() {
300 let arg_type = match arg.mode {
301 PassMode::Ignore => continue,
302 PassMode::Direct(_) => arg.layout.spirv_type(span, cx),
303 PassMode::Pair(_, _) => {
304 argument_types.push(scalar_pair_element_backend_type(cx, span, arg.layout, 0));
305 argument_types.push(scalar_pair_element_backend_type(cx, span, arg.layout, 1));
306 continue;
307 }
308 PassMode::Cast { .. } | PassMode::Indirect { .. } => span_bug!(
309 span,
310 "query hooks should've made this `PassMode` impossible: {:#?}",
311 arg
312 ),
313 };
314 argument_types.push(arg_type);
315 }
316
317 SpirvType::Function {
318 return_type,
319 arguments: &argument_types,
320 }
321 .def(span, cx)
322 }
323}
324
325fn sole_structural_newtype_field<'tcx>(
334 cx: &CodegenCx<'tcx>,
335 layout: TyAndLayout<'tcx>,
336) -> Option<TyAndLayout<'tcx>> {
337 let mut non_zst = (0..layout.fields.count()).filter(|&i| !layout.field(cx, i).is_zst());
338 let i = non_zst.next()?;
339 if non_zst.next().is_some() {
340 return None;
341 }
342 let field = layout.field(cx, i);
343 (layout.fields.offset(i) == Size::ZERO
346 && field.size == layout.size
347 && field.align.abi == layout.align.abi
348 && field.backend_repr.eq_up_to_validity(&layout.backend_repr))
349 .then_some(field)
350}
351
352impl<'tcx> ConvSpirvType<'tcx> for TyAndLayout<'tcx> {
353 fn spirv_type(&self, mut span: Span, cx: &CodegenCx<'tcx>) -> Word {
354 if let TyKind::Adt(adt, args) = *self.ty.kind() {
355 if span == DUMMY_SP {
356 span = cx.tcx.def_span(adt.did());
357 }
358
359 let attrs = AggregatedSpirvAttributes::parse(
360 cx,
361 cx.tcx
362 .get_attrs_by_path(
363 adt.did(),
364 &[cx.sym.rust_gpu, cx.sym.spirv_attr_with_version],
365 )
366 .chain(cx.tcx.get_attrs_by_path(
367 adt.did(),
368 &[cx.sym.rust_gpu, cx.sym.vector, cx.sym.v1],
369 )),
370 );
371
372 if let Some(intrinsic_type_attr) = attrs.intrinsic_type.map(|attr| attr.value)
373 && let Ok(spirv_type) =
374 trans_intrinsic_type(cx, span, *self, args, intrinsic_type_attr)
375 {
376 return spirv_type;
377 }
378 }
379
380 match self.backend_repr {
384 _ if self.uninhabited => SpirvType::Adt {
385 def_id: def_id_for_spirv_type_adt(*self),
386 size: Some(Size::ZERO),
387 align: Align::from_bytes(0).unwrap(),
388 field_types: &[],
389 field_offsets: &[],
390 field_names: None,
391 }
392 .def_with_name(cx, span, TyLayoutNameKey::from(*self)),
393 BackendRepr::Scalar(scalar) => trans_scalar(cx, span, *self, scalar, Size::ZERO),
394 BackendRepr::ScalarPair { a, b, .. } => {
395 if let Some(field) = sole_structural_newtype_field(cx, *self) {
411 return field.spirv_type(span, cx);
412 }
413
414 let a_offset = Size::ZERO;
417 let b_offset = a
418 .primitive()
419 .size(cx)
420 .align_to(b.primitive().default_align(cx).abi);
421 let a = trans_scalar(cx, span, *self, a, a_offset);
422 let b = trans_scalar(cx, span, *self, b, b_offset);
423 let size = if self.is_unsized() {
424 None
425 } else {
426 Some(self.size)
427 };
428 let mut field_names = Vec::new();
430 if let TyKind::Adt(adt, _) = self.ty.kind()
431 && let Variants::Single { index } = self.variants
432 {
433 for i in self.fields.index_by_increasing_offset() {
434 let field = &adt.variants()[index].fields[FieldIdx::new(i)];
435 field_names.push(field.name);
436 }
437 }
438 SpirvType::Adt {
439 def_id: def_id_for_spirv_type_adt(*self),
440 size,
441 align: self.align.abi,
442 field_types: &[a, b],
443 field_offsets: &[a_offset, b_offset],
444 field_names: if field_names.len() == 2 {
445 Some(&field_names)
446 } else {
447 None
448 },
449 }
450 .def_with_name(cx, span, TyLayoutNameKey::from(*self))
451 }
452 BackendRepr::SimdVector { element, count } => {
453 let elem_spirv = trans_scalar(cx, span, *self, element, Size::ZERO);
454 SpirvType::Vector {
455 element: elem_spirv,
456 count: count.as_u32(),
457 size: self.size,
458 align: self.align.abi,
459 }
460 .def(span, cx)
461 }
462 BackendRepr::SimdScalableVector { .. } => cx
463 .tcx
464 .dcx()
465 .fatal("scalable vectors are not supported in SPIR-V backend"),
466 BackendRepr::Memory { sized: _ } => {
467 if let TyKind::Adt(adt, _) = self.ty.kind()
473 && adt.repr().transparent()
474 && let Some(field) = sole_structural_newtype_field(cx, *self)
475 {
476 let inner_id = field.spirv_type(span, cx);
477 name_type_id(cx, inner_id, TyLayoutNameKey::from(*self));
480 return inner_id;
481 }
482 trans_aggregate(cx, span, *self)
483 }
484 }
485 }
486}
487
488pub fn scalar_pair_element_backend_type<'tcx>(
491 cx: &CodegenCx<'tcx>,
492 span: Span,
493 ty: TyAndLayout<'tcx>,
494 index: usize,
495) -> Word {
496 let [a, b] = match ty.backend_repr {
497 BackendRepr::ScalarPair { a, b, .. } => [a, b],
498 other => span_bug!(
499 span,
500 "scalar_pair_element_backend_type invalid abi: {:?}",
501 other
502 ),
503 };
504 let offset = match index {
505 0 => Size::ZERO,
506 1 => a
507 .primitive()
508 .size(cx)
509 .align_to(b.primitive().default_align(cx).abi),
510 _ => unreachable!(),
511 };
512 trans_scalar(cx, span, ty, [a, b][index], offset)
513}
514
515fn trans_scalar<'tcx>(
523 cx: &CodegenCx<'tcx>,
524 span: Span,
525 ty: TyAndLayout<'tcx>,
526 scalar: Scalar,
527 offset: Size,
528) -> Word {
529 if scalar.is_bool() {
530 return SpirvType::Bool.def(span, cx);
531 }
532
533 match scalar.primitive() {
534 Primitive::Int(int_kind, signedness) => {
535 SpirvType::Integer(int_kind.size().bits() as u32, signedness).def(span, cx)
536 }
537 Primitive::Float(float_kind) => {
538 SpirvType::Float(float_kind.size().bits() as u32).def(span, cx)
539 }
540 Primitive::Pointer(_) => {
541 let pointee_ty = dig_scalar_pointee(cx, ty, offset);
542 if let Some(predefined_result) = cx
545 .type_cache
546 .recursive_pointee_cache
547 .begin(cx, span, pointee_ty)
548 {
549 predefined_result
550 } else {
551 let pointee = pointee_ty.spirv_type(span, cx);
552 cx.type_cache
553 .recursive_pointee_cache
554 .end(cx, span, pointee_ty, pointee)
555 }
556 }
557 }
558}
559
560fn dig_scalar_pointee<'tcx>(
571 cx: &CodegenCx<'tcx>,
572 layout: TyAndLayout<'tcx>,
573 offset: Size,
574) -> PointeeTy<'tcx> {
575 if let FieldsShape::Primitive = layout.fields {
576 assert_eq!(offset, Size::ZERO);
577 let pointee = match *layout.ty.kind() {
578 TyKind::Ref(_, pointee_ty, _) | TyKind::RawPtr(pointee_ty, _) => {
579 PointeeTy::Ty(cx.layout_of(pointee_ty))
580 }
581 TyKind::FnPtr(sig_tys, hdr) => PointeeTy::Fn(sig_tys.with(hdr)),
582 _ => bug!("Pointer is not `&T`, `*T` or `fn` pointer: {:#?}", layout),
583 };
584 return pointee;
585 }
586
587 let all_fields = (match &layout.variants {
588 Variants::Empty => 0..0,
589 Variants::Multiple { variants, .. } => 0..variants.len(),
590 Variants::Single { index } => {
591 let i = index.as_usize();
592 i..i + 1
593 }
594 })
595 .flat_map(|variant_idx| {
596 let variant = layout.for_variant(cx, VariantIdx::new(variant_idx));
597 (0..variant.fields.count()).map(move |field_idx| {
598 (
599 variant.field(cx, field_idx),
600 variant.fields.offset(field_idx),
601 )
602 })
603 });
604
605 let mut pointee = None;
606 for (field, field_offset) in all_fields {
607 if field.is_zst() {
608 continue;
609 }
610 if (field_offset..field_offset + field.size).contains(&offset) {
611 let new_pointee = dig_scalar_pointee(cx, field, offset - field_offset);
612 match pointee {
613 Some(old_pointee) if old_pointee != new_pointee => {
614 cx.tcx.dcx().fatal(format!(
615 "dig_scalar_pointee: unsupported Pointer with different \
616 pointee types ({old_pointee:?} vs {new_pointee:?}) at offset {offset:?} in {layout:#?}"
617 ));
618 }
619 _ => pointee = Some(new_pointee),
620 }
621 }
622 }
623 pointee.unwrap_or_else(|| {
624 bug!(
625 "field containing Pointer scalar at offset {:?} not found in {:#?}",
626 offset,
627 layout
628 )
629 })
630}
631
632fn trans_aggregate<'tcx>(cx: &CodegenCx<'tcx>, span: Span, ty: TyAndLayout<'tcx>) -> Word {
635 fn create_zst<'tcx>(cx: &CodegenCx<'tcx>, span: Span, ty: TyAndLayout<'tcx>) -> Word {
636 assert_eq!(ty.size, Size::ZERO);
637 SpirvType::Adt {
638 def_id: def_id_for_spirv_type_adt(ty),
639 size: Some(Size::ZERO),
640 align: ty.align.abi,
641 field_types: &[],
642 field_offsets: &[],
643 field_names: None,
644 }
645 .def_with_name(cx, span, TyLayoutNameKey::from(ty))
646 }
647 match ty.fields {
648 FieldsShape::Primitive => span_bug!(
649 span,
650 "trans_aggregate called for FieldsShape::Primitive layout {:#?}",
651 ty
652 ),
653 FieldsShape::Union(_) => {
654 assert!(!ty.is_unsized(), "{ty:#?}");
655
656 let largest_case = (0..ty.fields.count())
662 .map(|i| (FieldIdx::from_usize(i), ty.field(cx, i)))
663 .max_by_key(|(_, case)| case.size);
664
665 if let Some((case_idx, case)) = largest_case {
666 if ty.align != case.align {
667 trans_struct_or_union(cx, span, ty, Some(case_idx))
669 } else {
670 assert_eq!(ty.size, case.size);
671 case.spirv_type(span, cx)
672 }
673 } else {
674 create_zst(cx, span, ty)
675 }
676 }
677 FieldsShape::Array { stride, count } => {
678 let element_type = ty.field(cx, 0).spirv_type(span, cx);
679 if ty.is_unsized() {
680 assert_eq!(count, 0);
683 SpirvType::RuntimeArray {
684 element: element_type,
685 }
686 .def(span, cx)
687 } else if count == 0 {
688 create_zst(cx, span, ty)
690 } else {
691 let count_const = cx.constant_u32(span, count as u32);
692 let element_spv = cx.lookup_type(element_type);
693 let stride_spv = element_spv
694 .sizeof(cx)
695 .expect("Unexpected unsized type in sized FieldsShape::Array")
696 .align_to(element_spv.alignof(cx));
697 assert_eq!(stride_spv, stride);
698 SpirvType::Array {
699 element: element_type,
700 count: count_const,
701 }
702 .def(span, cx)
703 }
704 }
705 FieldsShape::Arbitrary { .. } => trans_struct_or_union(cx, span, ty, None),
706 }
707}
708
709pub fn auto_struct_layout(
711 cx: &CodegenCx<'_>,
712 field_types: &[Word],
713) -> (Vec<Size>, Option<Size>, Align) {
714 let mut field_offsets = Vec::with_capacity(field_types.len());
716 let mut offset = Some(Size::ZERO);
717 let mut max_align = Align::from_bytes(0).unwrap();
718 for &field_type in field_types {
719 let spirv_type = cx.lookup_type(field_type);
720 let field_size = spirv_type.sizeof(cx);
721 let field_align = spirv_type.alignof(cx);
722 let this_offset = offset
723 .expect("Unsized values can only be the last field in a struct")
724 .align_to(field_align);
725
726 field_offsets.push(this_offset);
727 if field_align > max_align {
728 max_align = field_align;
729 }
730 offset = field_size.map(|size| this_offset + size);
731 }
732 (field_offsets, offset, max_align)
733}
734
735fn trans_struct_or_union<'tcx>(
737 cx: &CodegenCx<'tcx>,
738 span: Span,
739 ty: TyAndLayout<'tcx>,
740 union_case: Option<FieldIdx>,
741) -> Word {
742 let size = if ty.is_unsized() { None } else { Some(ty.size) };
743 let align = ty.align.abi;
744 let mut field_types = Vec::new();
746 let mut field_offsets = Vec::new();
747 let mut field_names = Vec::new();
748 for i in ty.fields.index_by_increasing_offset() {
749 if let Some(expected_field_idx) = union_case
750 && i != expected_field_idx.as_usize()
751 {
752 continue;
753 }
754
755 let field_ty = ty.field(cx, i);
756 field_types.push(field_ty.spirv_type(span, cx));
757 let offset = ty.fields.offset(i);
758 field_offsets.push(offset);
759 if let Variants::Single { index } = ty.variants {
760 if let TyKind::Adt(adt, _) = ty.ty.kind() {
761 let field = &adt.variants()[index].fields[FieldIdx::new(i)];
762 field_names.push(field.name);
763 } else {
764 field_names.push(Symbol::intern(&format!("{i}")));
766 }
767 } else {
768 if let TyKind::Adt(_, _) = ty.ty.kind() {
769 } else {
770 span_bug!(span, "Variants::Multiple not TyKind::Adt");
771 }
772 if i == 0 {
773 field_names.push(cx.sym.discriminant);
774 } else {
775 cx.tcx.dcx().fatal("Variants::Multiple has multiple fields")
776 }
777 };
778 }
779
780 if union_case.is_none()
790 && let Variants::Multiple { variants, .. } = &ty.variants
791 {
792 let mut covered: Vec<(Size, Size)> = field_offsets
794 .iter()
795 .zip(&field_types)
796 .map(|(&offset, &field_ty)| {
797 let end = cx
798 .lookup_type(field_ty)
799 .sizeof(cx)
800 .map_or(offset, |size| offset + size);
801 (offset, end)
802 })
803 .collect();
804
805 let mut extra = Vec::new();
806 for variant_idx in variants.indices() {
807 let variant = ty.for_variant(cx, variant_idx);
808 for i in variant.fields.index_by_increasing_offset() {
809 let field = variant.field(cx, i);
810 if field.is_zst() {
811 continue;
812 }
813 let offset = variant.fields.offset(i);
814 let end = offset + field.size;
815 if covered.iter().any(|&(o, e)| offset < e && o < end) {
816 continue;
817 }
818 covered.push((offset, end));
819 let name = match ty.ty.kind() {
820 TyKind::Adt(adt, _) => {
821 adt.variants()[variant_idx].fields[FieldIdx::new(i)].name
822 }
823 _ => Symbol::intern(&format!("variant{}_field{i}", variant_idx.as_usize())),
824 };
825 extra.push((offset, field.spirv_type(span, cx), name));
826 }
827 }
828
829 if !extra.is_empty() {
833 let mut merged: Vec<_> = field_offsets
834 .iter()
835 .zip(&field_types)
836 .zip(&field_names)
837 .map(|((&offset, &field_ty), &name)| (offset, field_ty, name))
838 .collect();
839 merged.extend(extra);
840 merged.sort_by_key(|&(offset, ..)| offset);
841
842 field_offsets.clear();
843 field_types.clear();
844 field_names.clear();
845 for (offset, field_ty, name) in merged {
846 field_offsets.push(offset);
847 field_types.push(field_ty);
848 field_names.push(name);
849 }
850 }
851 }
852
853 SpirvType::Adt {
854 def_id: def_id_for_spirv_type_adt(ty),
855 size,
856 align,
857 field_types: &field_types,
858 field_offsets: &field_offsets,
859 field_names: Some(&field_names),
860 }
861 .def_with_name(cx, span, TyLayoutNameKey::from(ty))
862}
863
864fn def_id_for_spirv_type_adt(layout: TyAndLayout<'_>) -> Option<DefId> {
868 match *layout.ty.kind() {
869 TyKind::Adt(def, _) => Some(def.did()),
870 TyKind::Foreign(def_id) | TyKind::Closure(def_id, _) | TyKind::Coroutine(def_id, ..) => {
871 Some(def_id)
872 }
873 _ => None,
874 }
875}
876
877fn span_for_spirv_type_adt(cx: &CodegenCx<'_>, layout: TyAndLayout<'_>) -> Option<Span> {
878 def_id_for_spirv_type_adt(layout).map(|did| cx.tcx.def_span(did))
879}
880
881#[derive(Copy, Clone, PartialEq, Eq, Hash)]
884pub struct TyLayoutNameKey<'tcx> {
885 ty: Ty<'tcx>,
886 variant: Option<VariantIdx>,
887}
888
889impl<'tcx> From<TyAndLayout<'tcx>> for TyLayoutNameKey<'tcx> {
890 fn from(layout: TyAndLayout<'tcx>) -> Self {
891 TyLayoutNameKey {
892 ty: layout.ty,
893 variant: match layout.variants {
894 Variants::Single { index } => Some(index),
895 _ => None,
896 },
897 }
898 }
899}
900
901impl fmt::Display for TyLayoutNameKey<'_> {
902 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
903 write!(f, "{}", self.ty)?;
904 if let (TyKind::Adt(def, _), Some(index)) = (self.ty.kind(), self.variant)
905 && def.is_enum()
906 && !def.variants().is_empty()
907 {
908 write!(f, "::{}", def.variants()[index].name)?;
909 }
910 if let (TyKind::Coroutine(_, _), Some(index)) = (self.ty.kind(), self.variant) {
911 write!(f, "::{}", CoroutineArgs::variant_name(index))?;
912 }
913 Ok(())
914 }
915}
916
917fn trans_intrinsic_type<'tcx>(
918 cx: &CodegenCx<'tcx>,
919 span: Span,
920 ty: TyAndLayout<'tcx>,
921 args: GenericArgsRef<'tcx>,
922 intrinsic_type_attr: IntrinsicType,
923) -> Result<Word, ErrorGuaranteed> {
924 trait FromScalarInt: Sized {
925 fn from_scalar_int(n: ScalarInt) -> Option<Self>;
926 }
927
928 impl FromScalarInt for u32 {
929 fn from_scalar_int(n: ScalarInt) -> Option<Self> {
930 Some(n.try_to_bits(Size::from_bits(32)).ok()?.try_into().unwrap())
931 }
932 }
933
934 impl FromScalarInt for Dim {
935 fn from_scalar_int(n: ScalarInt) -> Option<Self> {
936 Dim::from_u32(u32::from_scalar_int(n)?)
937 }
938 }
939
940 impl FromScalarInt for ImageFormat {
941 fn from_scalar_int(n: ScalarInt) -> Option<Self> {
942 ImageFormat::from_u32(u32::from_scalar_int(n)?)
943 }
944 }
945
946 fn const_int_value<'tcx, P: FromScalarInt>(
947 cx: &CodegenCx<'tcx>,
948 const_: Const<'tcx>,
949 ) -> Result<P, ErrorGuaranteed> {
950 let ty::Value {
951 ty: const_ty,
952 valtree: const_val,
953 } = const_.to_value();
954 assert!(const_ty.is_integral());
955 const_val
956 .try_to_scalar()
957 .and_then(|scalar| scalar.try_to_scalar_int().ok())
958 .and_then(P::from_scalar_int)
959 .ok_or_else(|| {
960 cx.tcx
961 .dcx()
962 .err(format!("invalid value for const generic: {const_}"))
963 })
964 }
965
966 match intrinsic_type_attr {
967 IntrinsicType::GenericImageType => {
968 if ty.size != Size::from_bytes(4) {
970 return Err(cx
971 .tcx
972 .dcx()
973 .err("#[spirv(generic_image)] type must have size 4"));
974 }
975
976 let sampled_type = match args.type_at(0).kind() {
989 TyKind::Int(int) => match int {
990 IntTy::Isize => {
991 SpirvType::Integer(cx.tcx.data_layout.pointer_size().bits() as u32, true)
992 .def(span, cx)
993 }
994 IntTy::I8 => SpirvType::Integer(8, true).def(span, cx),
995 IntTy::I16 => SpirvType::Integer(16, true).def(span, cx),
996 IntTy::I32 => SpirvType::Integer(32, true).def(span, cx),
997 IntTy::I64 => SpirvType::Integer(64, true).def(span, cx),
998 IntTy::I128 => SpirvType::Integer(128, true).def(span, cx),
999 },
1000 TyKind::Uint(uint) => match uint {
1001 UintTy::Usize => {
1002 SpirvType::Integer(cx.tcx.data_layout.pointer_size().bits() as u32, false)
1003 .def(span, cx)
1004 }
1005 UintTy::U8 => SpirvType::Integer(8, false).def(span, cx),
1006 UintTy::U16 => SpirvType::Integer(16, false).def(span, cx),
1007 UintTy::U32 => SpirvType::Integer(32, false).def(span, cx),
1008 UintTy::U64 => SpirvType::Integer(64, false).def(span, cx),
1009 UintTy::U128 => SpirvType::Integer(128, false).def(span, cx),
1010 },
1011 TyKind::Float(FloatTy::F32) => SpirvType::Float(32).def(span, cx),
1012 TyKind::Float(FloatTy::F64) => SpirvType::Float(64).def(span, cx),
1013 _ => {
1014 return Err(cx
1015 .tcx
1016 .dcx()
1017 .span_err(span, "Invalid sampled type to `Image`."));
1018 }
1019 };
1020
1021 let dim = const_int_value(cx, args.const_at(1))?;
1030 let depth = const_int_value(cx, args.const_at(2))?;
1031 let arrayed = const_int_value(cx, args.const_at(3))?;
1032 let multisampled = const_int_value(cx, args.const_at(4))?;
1033 let sampled = const_int_value(cx, args.const_at(5))?;
1034 let image_format = const_int_value(cx, args.const_at(6))?;
1035
1036 let ty = SpirvType::Image {
1037 sampled_type,
1038 dim,
1039 depth,
1040 arrayed,
1041 multisampled,
1042 sampled,
1043 image_format,
1044 };
1045 Ok(ty.def(span, cx))
1046 }
1047 IntrinsicType::Sampler => {
1048 if ty.size != Size::from_bytes(4) {
1050 return Err(cx.tcx.dcx().err("#[spirv(sampler)] type must have size 4"));
1051 }
1052 Ok(SpirvType::Sampler.def(span, cx))
1053 }
1054 IntrinsicType::AccelerationStructureKhr => {
1055 Ok(SpirvType::AccelerationStructureKhr.def(span, cx))
1056 }
1057 IntrinsicType::RayQueryKhr => Ok(SpirvType::RayQueryKhr.def(span, cx)),
1058 IntrinsicType::CooperativeMatrixKhr => {
1059 if ty.size != Size::from_bytes(4) {
1060 return Err(cx.tcx.dcx().err("cooperative_matrix type must have size 4"));
1061 }
1062
1063 let component_type = cx.layout_of(args.type_at(0)).spirv_type(span, cx);
1065 let usage = cx
1067 .const_u32(const_int_value(cx, args.const_at(1))?)
1068 .def_cx(cx);
1069 let rows = cx
1071 .const_u32(const_int_value(cx, args.const_at(2))?)
1072 .def_cx(cx);
1073 let columns = cx
1075 .const_u32(const_int_value(cx, args.const_at(3))?)
1076 .def_cx(cx);
1077 let scope = cx.const_u32(3).def_cx(cx);
1079
1080 Ok(SpirvType::CooperativeMatrixKhr {
1081 component_type,
1082 usage,
1083 rows,
1084 columns,
1085 scope,
1086 }
1087 .def(span, cx))
1088 }
1089 IntrinsicType::SampledImage => {
1090 if ty.size != Size::from_bytes(4) {
1092 return Err(cx
1093 .tcx
1094 .dcx()
1095 .err("#[spirv(sampled_image)] type must have size 4"));
1096 }
1097
1098 if let Some(image_ty) = args.types().next() {
1101 let image_type = cx.layout_of(image_ty).spirv_type(span, cx);
1103 Ok(SpirvType::SampledImage { image_type }.def(span, cx))
1104 } else {
1105 Err(cx
1106 .tcx
1107 .dcx()
1108 .err("#[spirv(sampled_image)] type must have a generic image type"))
1109 }
1110 }
1111 IntrinsicType::RuntimeArray => {
1112 if ty.size != Size::from_bytes(4) {
1113 return Err(cx
1114 .tcx
1115 .dcx()
1116 .err("#[spirv(runtime_array)] type must have size 4"));
1117 }
1118
1119 if let Some(elem_ty) = args.types().next() {
1122 Ok(SpirvType::RuntimeArray {
1123 element: cx.layout_of(elem_ty).spirv_type(span, cx),
1124 }
1125 .def(span, cx))
1126 } else {
1127 Err(cx
1128 .tcx
1129 .dcx()
1130 .err("#[spirv(runtime_array)] type must have a generic element type"))
1131 }
1132 }
1133 IntrinsicType::TypedBuffer => {
1134 if ty.size != Size::from_bytes(4) {
1135 return Err(cx
1136 .tcx
1137 .sess
1138 .dcx()
1139 .err("#[spirv(typed_buffer)] type must have size 4"));
1140 }
1141
1142 if let Some(data_ty) = args.types().next() {
1145 Ok(SpirvType::InterfaceBlock {
1150 inner_type: cx.layout_of(data_ty).spirv_type(span, cx),
1151 }
1152 .def(span, cx))
1153 } else {
1154 Err(cx
1155 .tcx
1156 .sess
1157 .dcx()
1158 .err("#[spirv(typed_buffer)] type must have a generic data type"))
1159 }
1160 }
1161 IntrinsicType::Matrix => {
1162 let span = span_for_spirv_type_adt(cx, ty).unwrap();
1163 let err_attr_name = "`#[spirv(matrix)]`";
1164 let (element, count) = trans_glam_like_struct(cx, span, ty, args, err_attr_name)?;
1165 match cx.lookup_type(element) {
1166 SpirvType::Vector { .. } => (),
1167 ty => {
1168 return Err(cx
1169 .tcx
1170 .dcx()
1171 .struct_span_err(
1172 span,
1173 format!("{err_attr_name} type fields must all be vectors"),
1174 )
1175 .with_note(format!("field type is {}", ty.debug(element, cx)))
1176 .emit());
1177 }
1178 }
1179 Ok(SpirvType::Matrix { element, count }.def(span, cx))
1180 }
1181 IntrinsicType::Vector => {
1182 let span = span_for_spirv_type_adt(cx, ty).unwrap();
1183 let err_attr_name = "`#[spirv(vector)]`";
1184 let (element, count) = trans_glam_like_struct(cx, span, ty, args, err_attr_name)?;
1185 match cx.lookup_type(element) {
1186 SpirvType::Bool | SpirvType::Float { .. } | SpirvType::Integer { .. } => (),
1187 ty => {
1188 return Err(cx
1189 .tcx
1190 .dcx()
1191 .struct_span_err(
1192 span,
1193 format!(
1194 "{err_attr_name} type fields must all be floats, integers or bools"
1195 ),
1196 )
1197 .with_note(format!("field type is {}", ty.debug(element, cx)))
1198 .emit());
1199 }
1200 }
1201 Ok(SpirvType::Vector {
1202 element,
1203 count,
1204 size: ty.size,
1205 align: ty.align.abi,
1206 }
1207 .def(span, cx))
1208 }
1209 }
1210}
1211
1212fn trans_glam_like_struct<'tcx>(
1215 cx: &CodegenCx<'tcx>,
1216 span: Span,
1217 ty: TyAndLayout<'tcx>,
1218 args: GenericArgsRef<'tcx>,
1219 err_attr_name: &str,
1220) -> Result<(Word, u32), ErrorGuaranteed> {
1221 let tcx = cx.tcx;
1222 if let Some(adt) = ty.ty.ty_adt_def()
1223 && adt.is_struct()
1224 {
1225 let (count, element) = adt
1226 .non_enum_variant()
1227 .fields
1228 .iter()
1229 .map(|f| f.ty(tcx, args).skip_norm_wip())
1230 .dedup_with_count()
1231 .exactly_one()
1232 .map_err(|_e| {
1233 tcx.dcx().span_err(
1234 span,
1235 format!("{err_attr_name} member types must all be the same"),
1236 )
1237 })?;
1238
1239 let element = cx.layout_of(element);
1240 let element_word = element.spirv_type(span, cx);
1241 let count = u32::try_from(count)
1242 .ok()
1243 .filter(|count| 2 <= *count && *count <= 4)
1244 .ok_or_else(|| {
1245 tcx.dcx()
1246 .span_err(span, format!("{err_attr_name} must have 2, 3 or 4 members"))
1247 })?;
1248
1249 for i in 0..ty.fields.count() {
1250 let expected = element.size.checked_mul(i as u64, cx).unwrap();
1251 let actual = ty.fields.offset(i);
1252 if actual != expected {
1253 let name: &str = adt
1254 .non_enum_variant()
1255 .fields
1256 .get(FieldIdx::from(i))
1257 .unwrap()
1258 .name
1259 .as_str();
1260 tcx.dcx().span_fatal(
1261 span,
1262 format!(
1263 "Unexpected layout for {err_attr_name} annotated struct: \
1264 Expected member `{name}` at offset {expected:?}, but was at {actual:?}"
1265 ),
1266 )
1267 }
1268 }
1269
1270 Ok((element_word, count))
1271 } else {
1272 Err(tcx
1273 .dcx()
1274 .span_err(span, format!("{err_attr_name} type must be a struct")))
1275 }
1276}