]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_ty_utils/src/abi.rs
Rollup merge of #102406 - mejrs:missing_copy, r=wesleywiser
[rust.git] / compiler / rustc_ty_utils / src / abi.rs
1 use rustc_hir as hir;
2 use rustc_hir::lang_items::LangItem;
3 use rustc_middle::ty::layout::{
4     fn_can_unwind, FnAbiError, HasParamEnv, HasTyCtxt, LayoutCx, LayoutOf, TyAndLayout,
5 };
6 use rustc_middle::ty::{self, Ty, TyCtxt};
7 use rustc_session::config::OptLevel;
8 use rustc_span::def_id::DefId;
9 use rustc_target::abi::call::{
10     ArgAbi, ArgAttribute, ArgAttributes, ArgExtension, Conv, FnAbi, PassMode, Reg, RegKind,
11 };
12 use rustc_target::abi::*;
13 use rustc_target::spec::abi::Abi as SpecAbi;
14
15 use std::iter;
16
17 pub fn provide(providers: &mut ty::query::Providers) {
18     *providers = ty::query::Providers { fn_abi_of_fn_ptr, fn_abi_of_instance, ..*providers };
19 }
20
21 // NOTE(eddyb) this is private to avoid using it from outside of
22 // `fn_abi_of_instance` - any other uses are either too high-level
23 // for `Instance` (e.g. typeck would use `Ty::fn_sig` instead),
24 // or should go through `FnAbi` instead, to avoid losing any
25 // adjustments `fn_abi_of_instance` might be performing.
26 #[tracing::instrument(level = "debug", skip(tcx, param_env))]
27 fn fn_sig_for_fn_abi<'tcx>(
28     tcx: TyCtxt<'tcx>,
29     instance: ty::Instance<'tcx>,
30     param_env: ty::ParamEnv<'tcx>,
31 ) -> ty::PolyFnSig<'tcx> {
32     let ty = instance.ty(tcx, param_env);
33     match *ty.kind() {
34         ty::FnDef(..) => {
35             // HACK(davidtwco,eddyb): This is a workaround for polymorphization considering
36             // parameters unused if they show up in the signature, but not in the `mir::Body`
37             // (i.e. due to being inside a projection that got normalized, see
38             // `src/test/ui/polymorphization/normalized_sig_types.rs`), and codegen not keeping
39             // track of a polymorphization `ParamEnv` to allow normalizing later.
40             //
41             // We normalize the `fn_sig` again after substituting at a later point.
42             let mut sig = match *ty.kind() {
43                 ty::FnDef(def_id, substs) => tcx
44                     .bound_fn_sig(def_id)
45                     .map_bound(|fn_sig| {
46                         tcx.normalize_erasing_regions(tcx.param_env(def_id), fn_sig)
47                     })
48                     .subst(tcx, substs),
49                 _ => unreachable!(),
50             };
51
52             if let ty::InstanceDef::VTableShim(..) = instance.def {
53                 // Modify `fn(self, ...)` to `fn(self: *mut Self, ...)`.
54                 sig = sig.map_bound(|mut sig| {
55                     let mut inputs_and_output = sig.inputs_and_output.to_vec();
56                     inputs_and_output[0] = tcx.mk_mut_ptr(inputs_and_output[0]);
57                     sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
58                     sig
59                 });
60             }
61             sig
62         }
63         ty::Closure(def_id, substs) => {
64             let sig = substs.as_closure().sig();
65
66             let bound_vars = tcx.mk_bound_variable_kinds(
67                 sig.bound_vars().iter().chain(iter::once(ty::BoundVariableKind::Region(ty::BrEnv))),
68             );
69             let br = ty::BoundRegion {
70                 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
71                 kind: ty::BoundRegionKind::BrEnv,
72             };
73             let env_region = ty::ReLateBound(ty::INNERMOST, br);
74             let env_ty = tcx.closure_env_ty(def_id, substs, env_region).unwrap();
75
76             let sig = sig.skip_binder();
77             ty::Binder::bind_with_vars(
78                 tcx.mk_fn_sig(
79                     iter::once(env_ty).chain(sig.inputs().iter().cloned()),
80                     sig.output(),
81                     sig.c_variadic,
82                     sig.unsafety,
83                     sig.abi,
84                 ),
85                 bound_vars,
86             )
87         }
88         ty::Generator(_, substs, _) => {
89             let sig = substs.as_generator().poly_sig();
90
91             let bound_vars = tcx.mk_bound_variable_kinds(
92                 sig.bound_vars().iter().chain(iter::once(ty::BoundVariableKind::Region(ty::BrEnv))),
93             );
94             let br = ty::BoundRegion {
95                 var: ty::BoundVar::from_usize(bound_vars.len() - 1),
96                 kind: ty::BoundRegionKind::BrEnv,
97             };
98             let env_region = ty::ReLateBound(ty::INNERMOST, br);
99             let env_ty = tcx.mk_mut_ref(tcx.mk_region(env_region), ty);
100
101             let pin_did = tcx.require_lang_item(LangItem::Pin, None);
102             let pin_adt_ref = tcx.adt_def(pin_did);
103             let pin_substs = tcx.intern_substs(&[env_ty.into()]);
104             let env_ty = tcx.mk_adt(pin_adt_ref, pin_substs);
105
106             let sig = sig.skip_binder();
107             let state_did = tcx.require_lang_item(LangItem::GeneratorState, None);
108             let state_adt_ref = tcx.adt_def(state_did);
109             let state_substs = tcx.intern_substs(&[sig.yield_ty.into(), sig.return_ty.into()]);
110             let ret_ty = tcx.mk_adt(state_adt_ref, state_substs);
111             ty::Binder::bind_with_vars(
112                 tcx.mk_fn_sig(
113                     [env_ty, sig.resume_ty].iter(),
114                     &ret_ty,
115                     false,
116                     hir::Unsafety::Normal,
117                     rustc_target::spec::abi::Abi::Rust,
118                 ),
119                 bound_vars,
120             )
121         }
122         _ => bug!("unexpected type {:?} in Instance::fn_sig", ty),
123     }
124 }
125
126 #[inline]
127 fn conv_from_spec_abi(tcx: TyCtxt<'_>, abi: SpecAbi) -> Conv {
128     use rustc_target::spec::abi::Abi::*;
129     match tcx.sess.target.adjust_abi(abi) {
130         RustIntrinsic | PlatformIntrinsic | Rust | RustCall => Conv::Rust,
131         RustCold => Conv::RustCold,
132
133         // It's the ABI's job to select this, not ours.
134         System { .. } => bug!("system abi should be selected elsewhere"),
135         EfiApi => bug!("eficall abi should be selected elsewhere"),
136
137         Stdcall { .. } => Conv::X86Stdcall,
138         Fastcall { .. } => Conv::X86Fastcall,
139         Vectorcall { .. } => Conv::X86VectorCall,
140         Thiscall { .. } => Conv::X86ThisCall,
141         C { .. } => Conv::C,
142         Unadjusted => Conv::C,
143         Win64 { .. } => Conv::X86_64Win64,
144         SysV64 { .. } => Conv::X86_64SysV,
145         Aapcs { .. } => Conv::ArmAapcs,
146         CCmseNonSecureCall => Conv::CCmseNonSecureCall,
147         PtxKernel => Conv::PtxKernel,
148         Msp430Interrupt => Conv::Msp430Intr,
149         X86Interrupt => Conv::X86Intr,
150         AmdGpuKernel => Conv::AmdGpuKernel,
151         AvrInterrupt => Conv::AvrInterrupt,
152         AvrNonBlockingInterrupt => Conv::AvrNonBlockingInterrupt,
153         Wasm => Conv::C,
154
155         // These API constants ought to be more specific...
156         Cdecl { .. } => Conv::C,
157     }
158 }
159
160 fn fn_abi_of_fn_ptr<'tcx>(
161     tcx: TyCtxt<'tcx>,
162     query: ty::ParamEnvAnd<'tcx, (ty::PolyFnSig<'tcx>, &'tcx ty::List<Ty<'tcx>>)>,
163 ) -> Result<&'tcx FnAbi<'tcx, Ty<'tcx>>, FnAbiError<'tcx>> {
164     let (param_env, (sig, extra_args)) = query.into_parts();
165
166     let cx = LayoutCx { tcx, param_env };
167     fn_abi_new_uncached(&cx, sig, extra_args, None, None, false)
168 }
169
170 fn fn_abi_of_instance<'tcx>(
171     tcx: TyCtxt<'tcx>,
172     query: ty::ParamEnvAnd<'tcx, (ty::Instance<'tcx>, &'tcx ty::List<Ty<'tcx>>)>,
173 ) -> Result<&'tcx FnAbi<'tcx, Ty<'tcx>>, FnAbiError<'tcx>> {
174     let (param_env, (instance, extra_args)) = query.into_parts();
175
176     let sig = fn_sig_for_fn_abi(tcx, instance, param_env);
177
178     let caller_location = if instance.def.requires_caller_location(tcx) {
179         Some(tcx.caller_location_ty())
180     } else {
181         None
182     };
183
184     fn_abi_new_uncached(
185         &LayoutCx { tcx, param_env },
186         sig,
187         extra_args,
188         caller_location,
189         Some(instance.def_id()),
190         matches!(instance.def, ty::InstanceDef::Virtual(..)),
191     )
192 }
193
194 // Handle safe Rust thin and fat pointers.
195 fn adjust_for_rust_scalar<'tcx>(
196     cx: LayoutCx<'tcx, TyCtxt<'tcx>>,
197     attrs: &mut ArgAttributes,
198     scalar: Scalar,
199     layout: TyAndLayout<'tcx>,
200     offset: Size,
201     is_return: bool,
202 ) {
203     // Booleans are always a noundef i1 that needs to be zero-extended.
204     if scalar.is_bool() {
205         attrs.ext(ArgExtension::Zext);
206         attrs.set(ArgAttribute::NoUndef);
207         return;
208     }
209
210     // Scalars which have invalid values cannot be undef.
211     if !scalar.is_always_valid(&cx) {
212         attrs.set(ArgAttribute::NoUndef);
213     }
214
215     // Only pointer types handled below.
216     let Scalar::Initialized { value: Pointer, valid_range} = scalar else { return };
217
218     if !valid_range.contains(0) {
219         attrs.set(ArgAttribute::NonNull);
220     }
221
222     if let Some(pointee) = layout.pointee_info_at(&cx, offset) {
223         if let Some(kind) = pointee.safe {
224             attrs.pointee_align = Some(pointee.align);
225
226             // `Box` (`UniqueBorrowed`) are not necessarily dereferenceable
227             // for the entire duration of the function as they can be deallocated
228             // at any time. Same for shared mutable references. If LLVM had a
229             // way to say "dereferenceable on entry" we could use it here.
230             attrs.pointee_size = match kind {
231                 PointerKind::UniqueBorrowed
232                 | PointerKind::UniqueBorrowedPinned
233                 | PointerKind::Frozen => pointee.size,
234                 PointerKind::SharedMutable | PointerKind::UniqueOwned => Size::ZERO,
235             };
236
237             // `Box`, `&T`, and `&mut T` cannot be undef.
238             // Note that this only applies to the value of the pointer itself;
239             // this attribute doesn't make it UB for the pointed-to data to be undef.
240             attrs.set(ArgAttribute::NoUndef);
241
242             // The aliasing rules for `Box<T>` are still not decided, but currently we emit
243             // `noalias` for it. This can be turned off using an unstable flag.
244             // See https://github.com/rust-lang/unsafe-code-guidelines/issues/326
245             let noalias_for_box = cx.tcx.sess.opts.unstable_opts.box_noalias.unwrap_or(true);
246
247             // `&mut` pointer parameters never alias other parameters,
248             // or mutable global data
249             //
250             // `&T` where `T` contains no `UnsafeCell<U>` is immutable,
251             // and can be marked as both `readonly` and `noalias`, as
252             // LLVM's definition of `noalias` is based solely on memory
253             // dependencies rather than pointer equality
254             //
255             // Due to past miscompiles in LLVM, we apply a separate NoAliasMutRef attribute
256             // for UniqueBorrowed arguments, so that the codegen backend can decide whether
257             // or not to actually emit the attribute. It can also be controlled with the
258             // `-Zmutable-noalias` debugging option.
259             let no_alias = match kind {
260                 PointerKind::SharedMutable
261                 | PointerKind::UniqueBorrowed
262                 | PointerKind::UniqueBorrowedPinned => false,
263                 PointerKind::UniqueOwned => noalias_for_box,
264                 PointerKind::Frozen => !is_return,
265             };
266             if no_alias {
267                 attrs.set(ArgAttribute::NoAlias);
268             }
269
270             if kind == PointerKind::Frozen && !is_return {
271                 attrs.set(ArgAttribute::ReadOnly);
272             }
273
274             if kind == PointerKind::UniqueBorrowed && !is_return {
275                 attrs.set(ArgAttribute::NoAliasMutRef);
276             }
277         }
278     }
279 }
280
281 // FIXME(eddyb) perhaps group the signature/type-containing (or all of them?)
282 // arguments of this method, into a separate `struct`.
283 #[tracing::instrument(level = "debug", skip(cx, caller_location, fn_def_id, force_thin_self_ptr))]
284 fn fn_abi_new_uncached<'tcx>(
285     cx: &LayoutCx<'tcx, TyCtxt<'tcx>>,
286     sig: ty::PolyFnSig<'tcx>,
287     extra_args: &[Ty<'tcx>],
288     caller_location: Option<Ty<'tcx>>,
289     fn_def_id: Option<DefId>,
290     // FIXME(eddyb) replace this with something typed, like an `enum`.
291     force_thin_self_ptr: bool,
292 ) -> Result<&'tcx FnAbi<'tcx, Ty<'tcx>>, FnAbiError<'tcx>> {
293     let sig = cx.tcx.normalize_erasing_late_bound_regions(cx.param_env, sig);
294
295     let conv = conv_from_spec_abi(cx.tcx(), sig.abi);
296
297     let mut inputs = sig.inputs();
298     let extra_args = if sig.abi == RustCall {
299         assert!(!sig.c_variadic && extra_args.is_empty());
300
301         if let Some(input) = sig.inputs().last() {
302             if let ty::Tuple(tupled_arguments) = input.kind() {
303                 inputs = &sig.inputs()[0..sig.inputs().len() - 1];
304                 tupled_arguments
305             } else {
306                 bug!(
307                     "argument to function with \"rust-call\" ABI \
308                         is not a tuple"
309                 );
310             }
311         } else {
312             bug!(
313                 "argument to function with \"rust-call\" ABI \
314                     is not a tuple"
315             );
316         }
317     } else {
318         assert!(sig.c_variadic || extra_args.is_empty());
319         extra_args
320     };
321
322     let target = &cx.tcx.sess.target;
323     let target_env_gnu_like = matches!(&target.env[..], "gnu" | "musl" | "uclibc");
324     let win_x64_gnu = target.os == "windows" && target.arch == "x86_64" && target.env == "gnu";
325     let linux_s390x_gnu_like =
326         target.os == "linux" && target.arch == "s390x" && target_env_gnu_like;
327     let linux_sparc64_gnu_like =
328         target.os == "linux" && target.arch == "sparc64" && target_env_gnu_like;
329     let linux_powerpc_gnu_like =
330         target.os == "linux" && target.arch == "powerpc" && target_env_gnu_like;
331     use SpecAbi::*;
332     let rust_abi = matches!(sig.abi, RustIntrinsic | PlatformIntrinsic | Rust | RustCall);
333
334     let arg_of = |ty: Ty<'tcx>, arg_idx: Option<usize>| -> Result<_, FnAbiError<'tcx>> {
335         let span = tracing::debug_span!("arg_of");
336         let _entered = span.enter();
337         let is_return = arg_idx.is_none();
338
339         let layout = cx.layout_of(ty)?;
340         let layout = if force_thin_self_ptr && arg_idx == Some(0) {
341             // Don't pass the vtable, it's not an argument of the virtual fn.
342             // Instead, pass just the data pointer, but give it the type `*const/mut dyn Trait`
343             // or `&/&mut dyn Trait` because this is special-cased elsewhere in codegen
344             make_thin_self_ptr(cx, layout)
345         } else {
346             layout
347         };
348
349         let mut arg = ArgAbi::new(cx, layout, |layout, scalar, offset| {
350             let mut attrs = ArgAttributes::new();
351             adjust_for_rust_scalar(*cx, &mut attrs, scalar, *layout, offset, is_return);
352             attrs
353         });
354
355         if arg.layout.is_zst() {
356             // For some forsaken reason, x86_64-pc-windows-gnu
357             // doesn't ignore zero-sized struct arguments.
358             // The same is true for {s390x,sparc64,powerpc}-unknown-linux-{gnu,musl,uclibc}.
359             if is_return
360                 || rust_abi
361                 || (!win_x64_gnu
362                     && !linux_s390x_gnu_like
363                     && !linux_sparc64_gnu_like
364                     && !linux_powerpc_gnu_like)
365             {
366                 arg.mode = PassMode::Ignore;
367             }
368         }
369
370         Ok(arg)
371     };
372
373     let mut fn_abi = FnAbi {
374         ret: arg_of(sig.output(), None)?,
375         args: inputs
376             .iter()
377             .copied()
378             .chain(extra_args.iter().copied())
379             .chain(caller_location)
380             .enumerate()
381             .map(|(i, ty)| arg_of(ty, Some(i)))
382             .collect::<Result<_, _>>()?,
383         c_variadic: sig.c_variadic,
384         fixed_count: inputs.len() as u32,
385         conv,
386         can_unwind: fn_can_unwind(cx.tcx(), fn_def_id, sig.abi),
387     };
388     fn_abi_adjust_for_abi(cx, &mut fn_abi, sig.abi, fn_def_id)?;
389     debug!("fn_abi_new_uncached = {:?}", fn_abi);
390     Ok(cx.tcx.arena.alloc(fn_abi))
391 }
392
393 #[tracing::instrument(level = "trace", skip(cx))]
394 fn fn_abi_adjust_for_abi<'tcx>(
395     cx: &LayoutCx<'tcx, TyCtxt<'tcx>>,
396     fn_abi: &mut FnAbi<'tcx, Ty<'tcx>>,
397     abi: SpecAbi,
398     fn_def_id: Option<DefId>,
399 ) -> Result<(), FnAbiError<'tcx>> {
400     if abi == SpecAbi::Unadjusted {
401         return Ok(());
402     }
403
404     if abi == SpecAbi::Rust
405         || abi == SpecAbi::RustCall
406         || abi == SpecAbi::RustIntrinsic
407         || abi == SpecAbi::PlatformIntrinsic
408     {
409         // Look up the deduced parameter attributes for this function, if we have its def ID and
410         // we're optimizing in non-incremental mode. We'll tag its parameters with those attributes
411         // as appropriate.
412         let deduced_param_attrs = if cx.tcx.sess.opts.optimize != OptLevel::No
413             && cx.tcx.sess.opts.incremental.is_none()
414         {
415             fn_def_id.map(|fn_def_id| cx.tcx.deduced_param_attrs(fn_def_id)).unwrap_or_default()
416         } else {
417             &[]
418         };
419
420         let fixup = |arg: &mut ArgAbi<'tcx, Ty<'tcx>>, arg_idx: Option<usize>| {
421             if arg.is_ignore() {
422                 return;
423             }
424
425             match arg.layout.abi {
426                 Abi::Aggregate { .. } => {}
427
428                 // This is a fun case! The gist of what this is doing is
429                 // that we want callers and callees to always agree on the
430                 // ABI of how they pass SIMD arguments. If we were to *not*
431                 // make these arguments indirect then they'd be immediates
432                 // in LLVM, which means that they'd used whatever the
433                 // appropriate ABI is for the callee and the caller. That
434                 // means, for example, if the caller doesn't have AVX
435                 // enabled but the callee does, then passing an AVX argument
436                 // across this boundary would cause corrupt data to show up.
437                 //
438                 // This problem is fixed by unconditionally passing SIMD
439                 // arguments through memory between callers and callees
440                 // which should get them all to agree on ABI regardless of
441                 // target feature sets. Some more information about this
442                 // issue can be found in #44367.
443                 //
444                 // Note that the platform intrinsic ABI is exempt here as
445                 // that's how we connect up to LLVM and it's unstable
446                 // anyway, we control all calls to it in libstd.
447                 Abi::Vector { .. }
448                     if abi != SpecAbi::PlatformIntrinsic
449                         && cx.tcx.sess.target.simd_types_indirect =>
450                 {
451                     arg.make_indirect();
452                     return;
453                 }
454
455                 _ => return,
456             }
457
458             let size = arg.layout.size;
459             if arg.layout.is_unsized() || size > Pointer.size(cx) {
460                 arg.make_indirect();
461             } else {
462                 // We want to pass small aggregates as immediates, but using
463                 // a LLVM aggregate type for this leads to bad optimizations,
464                 // so we pick an appropriately sized integer type instead.
465                 arg.cast_to(Reg { kind: RegKind::Integer, size });
466             }
467
468             // If we deduced that this parameter was read-only, add that to the attribute list now.
469             //
470             // The `readonly` parameter only applies to pointers, so we can only do this if the
471             // argument was passed indirectly. (If the argument is passed directly, it's an SSA
472             // value, so it's implicitly immutable.)
473             if let (Some(arg_idx), &mut PassMode::Indirect { ref mut attrs, .. }) =
474                 (arg_idx, &mut arg.mode)
475             {
476                 // The `deduced_param_attrs` list could be empty if this is a type of function
477                 // we can't deduce any parameters for, so make sure the argument index is in
478                 // bounds.
479                 if let Some(deduced_param_attrs) = deduced_param_attrs.get(arg_idx) {
480                     if deduced_param_attrs.read_only {
481                         attrs.regular.insert(ArgAttribute::ReadOnly);
482                         debug!("added deduced read-only attribute");
483                     }
484                 }
485             }
486         };
487
488         fixup(&mut fn_abi.ret, None);
489         for (arg_idx, arg) in fn_abi.args.iter_mut().enumerate() {
490             fixup(arg, Some(arg_idx));
491         }
492     } else {
493         fn_abi.adjust_for_foreign_abi(cx, abi)?;
494     }
495
496     Ok(())
497 }
498
499 #[tracing::instrument(level = "debug", skip(cx))]
500 fn make_thin_self_ptr<'tcx>(
501     cx: &(impl HasTyCtxt<'tcx> + HasParamEnv<'tcx>),
502     layout: TyAndLayout<'tcx>,
503 ) -> TyAndLayout<'tcx> {
504     let tcx = cx.tcx();
505     let fat_pointer_ty = if layout.is_unsized() {
506         // unsized `self` is passed as a pointer to `self`
507         // FIXME (mikeyhew) change this to use &own if it is ever added to the language
508         tcx.mk_mut_ptr(layout.ty)
509     } else {
510         match layout.abi {
511             Abi::ScalarPair(..) | Abi::Scalar(..) => (),
512             _ => bug!("receiver type has unsupported layout: {:?}", layout),
513         }
514
515         // In the case of Rc<Self>, we need to explicitly pass a *mut RcBox<Self>
516         // with a Scalar (not ScalarPair) ABI. This is a hack that is understood
517         // elsewhere in the compiler as a method on a `dyn Trait`.
518         // To get the type `*mut RcBox<Self>`, we just keep unwrapping newtypes until we
519         // get a built-in pointer type
520         let mut fat_pointer_layout = layout;
521         'descend_newtypes: while !fat_pointer_layout.ty.is_unsafe_ptr()
522             && !fat_pointer_layout.ty.is_region_ptr()
523         {
524             for i in 0..fat_pointer_layout.fields.count() {
525                 let field_layout = fat_pointer_layout.field(cx, i);
526
527                 if !field_layout.is_zst() {
528                     fat_pointer_layout = field_layout;
529                     continue 'descend_newtypes;
530                 }
531             }
532
533             bug!("receiver has no non-zero-sized fields {:?}", fat_pointer_layout);
534         }
535
536         fat_pointer_layout.ty
537     };
538
539     // we now have a type like `*mut RcBox<dyn Trait>`
540     // change its layout to that of `*mut ()`, a thin pointer, but keep the same type
541     // this is understood as a special case elsewhere in the compiler
542     let unit_ptr_ty = tcx.mk_mut_ptr(tcx.mk_unit());
543
544     TyAndLayout {
545         ty: fat_pointer_ty,
546
547         // NOTE(eddyb) using an empty `ParamEnv`, and `unwrap`-ing the `Result`
548         // should always work because the type is always `*mut ()`.
549         ..tcx.layout_of(ty::ParamEnv::reveal_all().and(unit_ptr_ty)).unwrap()
550     }
551 }