1use std::iter;
2
3use rustc_abi::Primitive::Pointer;
4use rustc_abi::{BackendRepr, ExternAbi, PointerKind, Scalar, Size};
5use rustc_hir as hir;
6use rustc_hir::lang_items::LangItem;
7use rustc_middle::bug;
8use rustc_middle::query::Providers;
9use rustc_middle::ty::layout::{
10 FnAbiError, HasTyCtxt, HasTypingEnv, LayoutCx, LayoutOf, TyAndLayout, fn_can_unwind,
11};
12use rustc_middle::ty::{self, InstanceKind, Ty, TyCtxt};
13use rustc_session::config::OptLevel;
14use rustc_span::def_id::DefId;
15use rustc_target::callconv::{
16 ArgAbi, ArgAttribute, ArgAttributes, ArgExtension, Conv, FnAbi, PassMode, RiscvInterruptKind,
17};
18use tracing::debug;
19
20pub(crate) fn provide(providers: &mut Providers) {
21 *providers = Providers { fn_abi_of_fn_ptr, fn_abi_of_instance, ..*providers };
22}
23
24#[tracing::instrument(level = "debug", skip(tcx, typing_env))]
30fn fn_sig_for_fn_abi<'tcx>(
31 tcx: TyCtxt<'tcx>,
32 instance: ty::Instance<'tcx>,
33 typing_env: ty::TypingEnv<'tcx>,
34) -> ty::FnSig<'tcx> {
35 if let InstanceKind::ThreadLocalShim(..) = instance.def {
36 return tcx.mk_fn_sig(
37 [],
38 tcx.thread_local_ptr_ty(instance.def_id()),
39 false,
40 hir::Safety::Safe,
41 rustc_abi::ExternAbi::Unadjusted,
42 );
43 }
44
45 let ty = instance.ty(tcx, typing_env);
46 match *ty.kind() {
47 ty::FnDef(def_id, args) => {
48 let mut sig = tcx
49 .instantiate_bound_regions_with_erased(tcx.fn_sig(def_id).instantiate(tcx, args));
50
51 if let ty::InstanceKind::VTableShim(..) = instance.def {
53 let mut inputs_and_output = sig.inputs_and_output.to_vec();
54 inputs_and_output[0] = Ty::new_mut_ptr(tcx, inputs_and_output[0]);
55 sig.inputs_and_output = tcx.mk_type_list(&inputs_and_output);
56 }
57
58 if let ty::InstanceKind::ReifyShim(def_id, _) = instance.def
60 && let Some((rpitit_def_id, fn_args)) =
61 tcx.return_position_impl_trait_in_trait_shim_data(def_id)
62 {
63 let fn_args = fn_args.instantiate(tcx, args);
64 let rpitit_args =
65 fn_args.extend_to(tcx, rpitit_def_id, |param, _| match param.kind {
66 ty::GenericParamDefKind::Lifetime => tcx.lifetimes.re_erased.into(),
67 ty::GenericParamDefKind::Type { .. }
68 | ty::GenericParamDefKind::Const { .. } => {
69 unreachable!("rpitit should have no addition ty/ct")
70 }
71 });
72 let dyn_star_ty = Ty::new_dynamic(
73 tcx,
74 tcx.item_bounds_to_existential_predicates(rpitit_def_id, rpitit_args),
75 tcx.lifetimes.re_erased,
76 ty::DynStar,
77 );
78 let mut inputs_and_output = sig.inputs_and_output.to_vec();
79 *inputs_and_output.last_mut().unwrap() = dyn_star_ty;
80 sig.inputs_and_output = tcx.mk_type_list(&inputs_and_output);
81 }
82
83 sig
84 }
85 ty::Closure(def_id, args) => {
86 let sig = tcx.instantiate_bound_regions_with_erased(args.as_closure().sig());
87 let env_ty = tcx.closure_env_ty(
88 Ty::new_closure(tcx, def_id, args),
89 args.as_closure().kind(),
90 tcx.lifetimes.re_erased,
91 );
92
93 tcx.mk_fn_sig(
94 iter::once(env_ty).chain(sig.inputs().iter().cloned()),
95 sig.output(),
96 sig.c_variadic,
97 sig.safety,
98 sig.abi,
99 )
100 }
101 ty::CoroutineClosure(def_id, args) => {
102 let coroutine_ty = Ty::new_coroutine_closure(tcx, def_id, args);
103 let sig = args.as_coroutine_closure().coroutine_closure_sig();
104
105 let mut coroutine_kind = args.as_coroutine_closure().kind();
110
111 let env_ty =
112 if let InstanceKind::ConstructCoroutineInClosureShim { receiver_by_ref, .. } =
113 instance.def
114 {
115 coroutine_kind = ty::ClosureKind::FnOnce;
116
117 if receiver_by_ref {
120 Ty::new_imm_ref(tcx, tcx.lifetimes.re_erased, coroutine_ty)
121 } else {
122 coroutine_ty
123 }
124 } else {
125 tcx.closure_env_ty(coroutine_ty, coroutine_kind, tcx.lifetimes.re_erased)
126 };
127
128 let sig = tcx.instantiate_bound_regions_with_erased(sig);
129
130 tcx.mk_fn_sig(
131 iter::once(env_ty).chain([sig.tupled_inputs_ty]),
132 sig.to_coroutine_given_kind_and_upvars(
133 tcx,
134 args.as_coroutine_closure().parent_args(),
135 tcx.coroutine_for_closure(def_id),
136 coroutine_kind,
137 tcx.lifetimes.re_erased,
138 args.as_coroutine_closure().tupled_upvars_ty(),
139 args.as_coroutine_closure().coroutine_captures_by_ref_ty(),
140 ),
141 sig.c_variadic,
142 sig.safety,
143 sig.abi,
144 )
145 }
146 ty::Coroutine(did, args) => {
147 let coroutine_kind = tcx.coroutine_kind(did).unwrap();
148 let sig = args.as_coroutine().sig();
149
150 let env_ty = Ty::new_mut_ref(tcx, tcx.lifetimes.re_erased, ty);
151
152 let pin_did = tcx.require_lang_item(LangItem::Pin, None);
153 let pin_adt_ref = tcx.adt_def(pin_did);
154 let pin_args = tcx.mk_args(&[env_ty.into()]);
155 let env_ty = match coroutine_kind {
156 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _) => {
157 env_ty
160 }
161 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _)
162 | hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _)
163 | hir::CoroutineKind::Coroutine(_) => Ty::new_adt(tcx, pin_adt_ref, pin_args),
164 };
165
166 let (resume_ty, ret_ty) = match coroutine_kind {
173 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Async, _) => {
174 assert_eq!(sig.yield_ty, tcx.types.unit);
176
177 let poll_did = tcx.require_lang_item(LangItem::Poll, None);
178 let poll_adt_ref = tcx.adt_def(poll_did);
179 let poll_args = tcx.mk_args(&[sig.return_ty.into()]);
180 let ret_ty = Ty::new_adt(tcx, poll_adt_ref, poll_args);
181
182 #[cfg(debug_assertions)]
185 {
186 if let ty::Adt(resume_ty_adt, _) = sig.resume_ty.kind() {
187 let expected_adt =
188 tcx.adt_def(tcx.require_lang_item(LangItem::ResumeTy, None));
189 assert_eq!(*resume_ty_adt, expected_adt);
190 } else {
191 panic!("expected `ResumeTy`, found `{:?}`", sig.resume_ty);
192 };
193 }
194 let context_mut_ref = Ty::new_task_context(tcx);
195
196 (Some(context_mut_ref), ret_ty)
197 }
198 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::Gen, _) => {
199 let option_did = tcx.require_lang_item(LangItem::Option, None);
201 let option_adt_ref = tcx.adt_def(option_did);
202 let option_args = tcx.mk_args(&[sig.yield_ty.into()]);
203 let ret_ty = Ty::new_adt(tcx, option_adt_ref, option_args);
204
205 assert_eq!(sig.return_ty, tcx.types.unit);
206 assert_eq!(sig.resume_ty, tcx.types.unit);
207
208 (None, ret_ty)
209 }
210 hir::CoroutineKind::Desugared(hir::CoroutineDesugaring::AsyncGen, _) => {
211 assert_eq!(sig.return_ty, tcx.types.unit);
214
215 let ret_ty = sig.yield_ty;
217
218 #[cfg(debug_assertions)]
221 {
222 if let ty::Adt(resume_ty_adt, _) = sig.resume_ty.kind() {
223 let expected_adt =
224 tcx.adt_def(tcx.require_lang_item(LangItem::ResumeTy, None));
225 assert_eq!(*resume_ty_adt, expected_adt);
226 } else {
227 panic!("expected `ResumeTy`, found `{:?}`", sig.resume_ty);
228 };
229 }
230 let context_mut_ref = Ty::new_task_context(tcx);
231
232 (Some(context_mut_ref), ret_ty)
233 }
234 hir::CoroutineKind::Coroutine(_) => {
235 let state_did = tcx.require_lang_item(LangItem::CoroutineState, None);
237 let state_adt_ref = tcx.adt_def(state_did);
238 let state_args = tcx.mk_args(&[sig.yield_ty.into(), sig.return_ty.into()]);
239 let ret_ty = Ty::new_adt(tcx, state_adt_ref, state_args);
240
241 (Some(sig.resume_ty), ret_ty)
242 }
243 };
244
245 if let Some(resume_ty) = resume_ty {
246 tcx.mk_fn_sig(
247 [env_ty, resume_ty],
248 ret_ty,
249 false,
250 hir::Safety::Safe,
251 rustc_abi::ExternAbi::Rust,
252 )
253 } else {
254 tcx.mk_fn_sig(
256 [env_ty],
257 ret_ty,
258 false,
259 hir::Safety::Safe,
260 rustc_abi::ExternAbi::Rust,
261 )
262 }
263 }
264 _ => bug!("unexpected type {:?} in Instance::fn_sig", ty),
265 }
266}
267
268#[inline]
269fn conv_from_spec_abi(tcx: TyCtxt<'_>, abi: ExternAbi, c_variadic: bool) -> Conv {
270 use rustc_abi::ExternAbi::*;
271 match tcx.sess.target.adjust_abi(abi, c_variadic) {
272 RustIntrinsic | Rust | RustCall => Conv::Rust,
273
274 RustCold => Conv::PreserveMost,
277
278 System { .. } => bug!("system abi should be selected elsewhere"),
280 EfiApi => bug!("eficall abi should be selected elsewhere"),
281
282 Stdcall { .. } => Conv::X86Stdcall,
283 Fastcall { .. } => Conv::X86Fastcall,
284 Vectorcall { .. } => Conv::X86VectorCall,
285 Thiscall { .. } => Conv::X86ThisCall,
286 C { .. } => Conv::C,
287 Unadjusted => Conv::C,
288 Win64 { .. } => Conv::X86_64Win64,
289 SysV64 { .. } => Conv::X86_64SysV,
290 Aapcs { .. } => Conv::ArmAapcs,
291 CCmseNonSecureCall => Conv::CCmseNonSecureCall,
292 CCmseNonSecureEntry => Conv::CCmseNonSecureEntry,
293 PtxKernel => Conv::GpuKernel,
294 Msp430Interrupt => Conv::Msp430Intr,
295 X86Interrupt => Conv::X86Intr,
296 GpuKernel => Conv::GpuKernel,
297 AvrInterrupt => Conv::AvrInterrupt,
298 AvrNonBlockingInterrupt => Conv::AvrNonBlockingInterrupt,
299 RiscvInterruptM => Conv::RiscvInterrupt { kind: RiscvInterruptKind::Machine },
300 RiscvInterruptS => Conv::RiscvInterrupt { kind: RiscvInterruptKind::Supervisor },
301
302 Cdecl { .. } => Conv::C,
304 }
305}
306
307fn fn_abi_of_fn_ptr<'tcx>(
308 tcx: TyCtxt<'tcx>,
309 query: ty::PseudoCanonicalInput<'tcx, (ty::PolyFnSig<'tcx>, &'tcx ty::List<Ty<'tcx>>)>,
310) -> Result<&'tcx FnAbi<'tcx, Ty<'tcx>>, &'tcx FnAbiError<'tcx>> {
311 let ty::PseudoCanonicalInput { typing_env, value: (sig, extra_args) } = query;
312
313 let cx = LayoutCx::new(tcx, typing_env);
314 fn_abi_new_uncached(
315 &cx,
316 tcx.instantiate_bound_regions_with_erased(sig),
317 extra_args,
318 None,
319 None,
320 false,
321 )
322}
323
324fn fn_abi_of_instance<'tcx>(
325 tcx: TyCtxt<'tcx>,
326 query: ty::PseudoCanonicalInput<'tcx, (ty::Instance<'tcx>, &'tcx ty::List<Ty<'tcx>>)>,
327) -> Result<&'tcx FnAbi<'tcx, Ty<'tcx>>, &'tcx FnAbiError<'tcx>> {
328 let ty::PseudoCanonicalInput { typing_env, value: (instance, extra_args) } = query;
329
330 let sig = fn_sig_for_fn_abi(tcx, instance, typing_env);
331
332 let caller_location =
333 instance.def.requires_caller_location(tcx).then(|| tcx.caller_location_ty());
334
335 fn_abi_new_uncached(
336 &LayoutCx::new(tcx, typing_env),
337 sig,
338 extra_args,
339 caller_location,
340 Some(instance.def_id()),
341 matches!(instance.def, ty::InstanceKind::Virtual(..)),
342 )
343}
344
345fn adjust_for_rust_scalar<'tcx>(
347 cx: LayoutCx<'tcx>,
348 attrs: &mut ArgAttributes,
349 scalar: Scalar,
350 layout: TyAndLayout<'tcx>,
351 offset: Size,
352 is_return: bool,
353 drop_target_pointee: Option<Ty<'tcx>>,
354) {
355 if scalar.is_bool() {
357 attrs.ext(ArgExtension::Zext);
358 attrs.set(ArgAttribute::NoUndef);
359 return;
360 }
361
362 if !scalar.is_uninit_valid() {
363 attrs.set(ArgAttribute::NoUndef);
364 }
365
366 let Scalar::Initialized { value: Pointer(_), valid_range } = scalar else { return };
368
369 if !valid_range.contains(0) || drop_target_pointee.is_some() {
372 attrs.set(ArgAttribute::NonNull);
373 }
374
375 let tcx = cx.tcx();
376
377 if let Some(pointee) = layout.pointee_info_at(&cx, offset) {
378 let kind = if let Some(kind) = pointee.safe {
379 Some(kind)
380 } else if let Some(pointee) = drop_target_pointee {
381 Some(PointerKind::MutableRef { unpin: pointee.is_unpin(tcx, cx.typing_env) })
383 } else {
384 None
385 };
386 if let Some(kind) = kind {
387 attrs.pointee_align = Some(pointee.align);
388
389 attrs.pointee_size = match kind {
396 PointerKind::Box { .. }
397 | PointerKind::SharedRef { frozen: false }
398 | PointerKind::MutableRef { unpin: false } => Size::ZERO,
399 PointerKind::SharedRef { frozen: true }
400 | PointerKind::MutableRef { unpin: true } => pointee.size,
401 };
402
403 let noalias_for_box = tcx.sess.opts.unstable_opts.box_noalias;
407
408 let noalias_mut_ref = tcx.sess.opts.unstable_opts.mutable_noalias;
412
413 let no_alias = match kind {
420 PointerKind::SharedRef { frozen } => frozen,
421 PointerKind::MutableRef { unpin } => unpin && noalias_mut_ref,
422 PointerKind::Box { unpin, global } => unpin && global && noalias_for_box,
423 };
424 if no_alias && !is_return {
427 attrs.set(ArgAttribute::NoAlias);
428 }
429
430 if matches!(kind, PointerKind::SharedRef { frozen: true }) && !is_return {
431 attrs.set(ArgAttribute::ReadOnly);
432 }
433 }
434 }
435}
436
437fn fn_abi_sanity_check<'tcx>(
439 cx: &LayoutCx<'tcx>,
440 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
441 spec_abi: ExternAbi,
442) {
443 fn fn_arg_sanity_check<'tcx>(
444 cx: &LayoutCx<'tcx>,
445 fn_abi: &FnAbi<'tcx, Ty<'tcx>>,
446 spec_abi: ExternAbi,
447 arg: &ArgAbi<'tcx, Ty<'tcx>>,
448 ) {
449 let tcx = cx.tcx();
450
451 if spec_abi == ExternAbi::Rust
452 || spec_abi == ExternAbi::RustCall
453 || spec_abi == ExternAbi::RustCold
454 {
455 if arg.layout.is_zst() {
456 assert!(arg.is_ignore());
459 }
460 if let PassMode::Indirect { on_stack, .. } = arg.mode {
461 assert!(!on_stack, "rust abi shouldn't use on_stack");
462 }
463 }
464
465 match &arg.mode {
466 PassMode::Ignore => {
467 assert!(arg.layout.is_zst() || arg.layout.is_uninhabited());
468 }
469 PassMode::Direct(_) => {
470 match arg.layout.backend_repr {
475 BackendRepr::Uninhabited
476 | BackendRepr::Scalar(_)
477 | BackendRepr::Vector { .. } => {}
478 BackendRepr::ScalarPair(..) => {
479 panic!("`PassMode::Direct` used for ScalarPair type {}", arg.layout.ty)
480 }
481 BackendRepr::Memory { sized } => {
482 assert!(sized, "`PassMode::Direct` for unsized type in ABI: {:#?}", fn_abi);
485 match spec_abi {
496 ExternAbi::Unadjusted => {}
497 ExternAbi::C { unwind: _ }
498 if matches!(&*tcx.sess.target.arch, "wasm32" | "wasm64") => {}
499 _ => {
500 panic!(
501 "`PassMode::Direct` for aggregates only allowed for \"unadjusted\" functions and on wasm\n\
502 Problematic type: {:#?}",
503 arg.layout,
504 );
505 }
506 }
507 }
508 }
509 }
510 PassMode::Pair(_, _) => {
511 assert!(
514 matches!(arg.layout.backend_repr, BackendRepr::ScalarPair(..)),
515 "PassMode::Pair for type {}",
516 arg.layout.ty
517 );
518 }
519 PassMode::Cast { .. } => {
520 assert!(arg.layout.is_sized());
522 }
523 PassMode::Indirect { meta_attrs: None, .. } => {
524 assert!(arg.layout.is_sized());
529 }
530 PassMode::Indirect { meta_attrs: Some(_), on_stack, .. } => {
531 assert!(arg.layout.is_unsized() && !on_stack);
533 let tail = tcx.struct_tail_for_codegen(arg.layout.ty, cx.typing_env);
535 if matches!(tail.kind(), ty::Foreign(..)) {
536 panic!("unsized arguments must not be `extern` types");
541 }
542 }
543 }
544 }
545
546 for arg in fn_abi.args.iter() {
547 fn_arg_sanity_check(cx, fn_abi, spec_abi, arg);
548 }
549 fn_arg_sanity_check(cx, fn_abi, spec_abi, &fn_abi.ret);
550}
551
552#[tracing::instrument(level = "debug", skip(cx, caller_location, fn_def_id, force_thin_self_ptr))]
555fn fn_abi_new_uncached<'tcx>(
556 cx: &LayoutCx<'tcx>,
557 sig: ty::FnSig<'tcx>,
558 extra_args: &[Ty<'tcx>],
559 caller_location: Option<Ty<'tcx>>,
560 fn_def_id: Option<DefId>,
561 force_thin_self_ptr: bool,
563) -> Result<&'tcx FnAbi<'tcx, Ty<'tcx>>, &'tcx FnAbiError<'tcx>> {
564 let tcx = cx.tcx();
565 let sig = tcx.normalize_erasing_regions(cx.typing_env, sig);
566
567 let conv = conv_from_spec_abi(cx.tcx(), sig.abi, sig.c_variadic);
568
569 let mut inputs = sig.inputs();
570 let extra_args = if sig.abi == ExternAbi::RustCall {
571 assert!(!sig.c_variadic && extra_args.is_empty());
572
573 if let Some(input) = sig.inputs().last() {
574 if let ty::Tuple(tupled_arguments) = input.kind() {
575 inputs = &sig.inputs()[0..sig.inputs().len() - 1];
576 tupled_arguments
577 } else {
578 bug!(
579 "argument to function with \"rust-call\" ABI \
580 is not a tuple"
581 );
582 }
583 } else {
584 bug!(
585 "argument to function with \"rust-call\" ABI \
586 is not a tuple"
587 );
588 }
589 } else {
590 assert!(sig.c_variadic || extra_args.is_empty());
591 extra_args
592 };
593
594 let is_drop_in_place =
595 fn_def_id.is_some_and(|def_id| tcx.is_lang_item(def_id, LangItem::DropInPlace));
596
597 let arg_of = |ty: Ty<'tcx>, arg_idx: Option<usize>| -> Result<_, &'tcx FnAbiError<'tcx>> {
598 let span = tracing::debug_span!("arg_of");
599 let _entered = span.enter();
600 let is_return = arg_idx.is_none();
601 let is_drop_target = is_drop_in_place && arg_idx == Some(0);
602 let drop_target_pointee = is_drop_target.then(|| match ty.kind() {
603 ty::RawPtr(ty, _) => *ty,
604 _ => bug!("argument to drop_in_place is not a raw ptr: {:?}", ty),
605 });
606
607 let layout = cx.layout_of(ty).map_err(|err| &*tcx.arena.alloc(FnAbiError::Layout(*err)))?;
608 let layout = if force_thin_self_ptr && arg_idx == Some(0) {
609 make_thin_self_ptr(cx, layout)
613 } else {
614 layout
615 };
616
617 let mut arg = ArgAbi::new(cx, layout, |layout, scalar, offset| {
618 let mut attrs = ArgAttributes::new();
619 adjust_for_rust_scalar(
620 *cx,
621 &mut attrs,
622 scalar,
623 *layout,
624 offset,
625 is_return,
626 drop_target_pointee,
627 );
628 attrs
629 });
630
631 if arg.layout.is_zst() {
632 arg.mode = PassMode::Ignore;
633 }
634
635 Ok(arg)
636 };
637
638 let mut fn_abi = FnAbi {
639 ret: arg_of(sig.output(), None)?,
640 args: inputs
641 .iter()
642 .copied()
643 .chain(extra_args.iter().copied())
644 .chain(caller_location)
645 .enumerate()
646 .map(|(i, ty)| arg_of(ty, Some(i)))
647 .collect::<Result<_, _>>()?,
648 c_variadic: sig.c_variadic,
649 fixed_count: inputs.len() as u32,
650 conv,
651 can_unwind: fn_can_unwind(cx.tcx(), fn_def_id, sig.abi),
652 };
653 fn_abi_adjust_for_abi(cx, &mut fn_abi, sig.abi, fn_def_id);
654 debug!("fn_abi_new_uncached = {:?}", fn_abi);
655 fn_abi_sanity_check(cx, &fn_abi, sig.abi);
656 Ok(tcx.arena.alloc(fn_abi))
657}
658
659#[tracing::instrument(level = "trace", skip(cx))]
660fn fn_abi_adjust_for_abi<'tcx>(
661 cx: &LayoutCx<'tcx>,
662 fn_abi: &mut FnAbi<'tcx, Ty<'tcx>>,
663 abi: ExternAbi,
664 fn_def_id: Option<DefId>,
665) {
666 if abi == ExternAbi::Unadjusted {
667 fn unadjust<'tcx>(arg: &mut ArgAbi<'tcx, Ty<'tcx>>) {
670 if matches!(arg.layout.backend_repr, BackendRepr::Memory { .. }) {
673 assert!(
674 arg.layout.backend_repr.is_sized(),
675 "'unadjusted' ABI does not support unsized arguments"
676 );
677 }
678 arg.make_direct_deprecated();
679 }
680
681 unadjust(&mut fn_abi.ret);
682 for arg in fn_abi.args.iter_mut() {
683 unadjust(arg);
684 }
685 return;
686 }
687
688 let tcx = cx.tcx();
689
690 if abi == ExternAbi::Rust || abi == ExternAbi::RustCall || abi == ExternAbi::RustIntrinsic {
691 fn_abi.adjust_for_rust_abi(cx, abi);
692
693 let deduced_param_attrs =
697 if tcx.sess.opts.optimize != OptLevel::No && tcx.sess.opts.incremental.is_none() {
698 fn_def_id.map(|fn_def_id| tcx.deduced_param_attrs(fn_def_id)).unwrap_or_default()
699 } else {
700 &[]
701 };
702
703 for (arg_idx, arg) in fn_abi.args.iter_mut().enumerate() {
704 if arg.is_ignore() {
705 continue;
706 }
707
708 if let &mut PassMode::Indirect { ref mut attrs, .. } = &mut arg.mode {
714 if let Some(deduced_param_attrs) = deduced_param_attrs.get(arg_idx) {
718 if deduced_param_attrs.read_only {
719 attrs.regular.insert(ArgAttribute::ReadOnly);
720 debug!("added deduced read-only attribute");
721 }
722 }
723 }
724 }
725 } else {
726 fn_abi.adjust_for_foreign_abi(cx, abi);
727 }
728}
729
730#[tracing::instrument(level = "debug", skip(cx))]
731fn make_thin_self_ptr<'tcx>(
732 cx: &(impl HasTyCtxt<'tcx> + HasTypingEnv<'tcx>),
733 layout: TyAndLayout<'tcx>,
734) -> TyAndLayout<'tcx> {
735 let tcx = cx.tcx();
736 let wide_pointer_ty = if layout.is_unsized() {
737 Ty::new_mut_ptr(tcx, layout.ty)
740 } else {
741 match layout.backend_repr {
742 BackendRepr::ScalarPair(..) | BackendRepr::Scalar(..) => (),
743 _ => bug!("receiver type has unsupported layout: {:?}", layout),
744 }
745
746 let mut wide_pointer_layout = layout;
752 while !wide_pointer_layout.ty.is_raw_ptr() && !wide_pointer_layout.ty.is_ref() {
753 wide_pointer_layout = wide_pointer_layout
754 .non_1zst_field(cx)
755 .expect("not exactly one non-1-ZST field in a `DispatchFromDyn` type")
756 .1
757 }
758
759 wide_pointer_layout.ty
760 };
761
762 let unit_ptr_ty = Ty::new_mut_ptr(tcx, tcx.types.unit);
766
767 TyAndLayout {
768 ty: wide_pointer_ty,
769
770 ..tcx.layout_of(ty::TypingEnv::fully_monomorphized().as_query_input(unit_ptr_ty)).unwrap()
773 }
774}