]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/shim.rs
Rollup merge of #103588 - weihanglo:rustdoc/url-redirect, r=notriddle
[rust.git] / compiler / rustc_mir_transform / src / shim.rs
1 use rustc_hir as hir;
2 use rustc_hir::def_id::DefId;
3 use rustc_hir::lang_items::LangItem;
4 use rustc_middle::mir::*;
5 use rustc_middle::ty::query::Providers;
6 use rustc_middle::ty::InternalSubsts;
7 use rustc_middle::ty::{self, EarlyBinder, GeneratorSubsts, Ty, TyCtxt};
8 use rustc_target::abi::VariantIdx;
9
10 use rustc_index::vec::{Idx, IndexVec};
11
12 use rustc_span::Span;
13 use rustc_target::spec::abi::Abi;
14
15 use std::fmt;
16 use std::iter;
17
18 use crate::util::expand_aggregate;
19 use crate::{
20     abort_unwinding_calls, add_call_guards, add_moves_for_packed_drops, deref_separator,
21     pass_manager as pm, remove_noop_landing_pads, simplify,
22 };
23 use rustc_middle::mir::patch::MirPatch;
24 use rustc_mir_dataflow::elaborate_drops::{self, DropElaborator, DropFlagMode, DropStyle};
25
26 pub fn provide(providers: &mut Providers) {
27     providers.mir_shims = make_shim;
28 }
29
30 fn make_shim<'tcx>(tcx: TyCtxt<'tcx>, instance: ty::InstanceDef<'tcx>) -> Body<'tcx> {
31     debug!("make_shim({:?})", instance);
32
33     let mut result = match instance {
34         ty::InstanceDef::Item(..) => bug!("item {:?} passed to make_shim", instance),
35         ty::InstanceDef::VTableShim(def_id) => {
36             build_call_shim(tcx, instance, Some(Adjustment::Deref), CallKind::Direct(def_id))
37         }
38         ty::InstanceDef::FnPtrShim(def_id, ty) => {
39             let trait_ = tcx.trait_of_item(def_id).unwrap();
40             let adjustment = match tcx.fn_trait_kind_from_lang_item(trait_) {
41                 Some(ty::ClosureKind::FnOnce) => Adjustment::Identity,
42                 Some(ty::ClosureKind::FnMut | ty::ClosureKind::Fn) => Adjustment::Deref,
43                 None => bug!("fn pointer {:?} is not an fn", ty),
44             };
45
46             build_call_shim(tcx, instance, Some(adjustment), CallKind::Indirect(ty))
47         }
48         // We are generating a call back to our def-id, which the
49         // codegen backend knows to turn to an actual call, be it
50         // a virtual call, or a direct call to a function for which
51         // indirect calls must be codegen'd differently than direct ones
52         // (such as `#[track_caller]`).
53         ty::InstanceDef::ReifyShim(def_id) => {
54             build_call_shim(tcx, instance, None, CallKind::Direct(def_id))
55         }
56         ty::InstanceDef::ClosureOnceShim { call_once: _, track_caller: _ } => {
57             let fn_mut = tcx.require_lang_item(LangItem::FnMut, None);
58             let call_mut = tcx
59                 .associated_items(fn_mut)
60                 .in_definition_order()
61                 .find(|it| it.kind == ty::AssocKind::Fn)
62                 .unwrap()
63                 .def_id;
64
65             build_call_shim(tcx, instance, Some(Adjustment::RefMut), CallKind::Direct(call_mut))
66         }
67
68         ty::InstanceDef::DropGlue(def_id, ty) => {
69             // FIXME(#91576): Drop shims for generators aren't subject to the MIR passes at the end
70             // of this function. Is this intentional?
71             if let Some(ty::Generator(gen_def_id, substs, _)) = ty.map(Ty::kind) {
72                 let body = tcx.optimized_mir(*gen_def_id).generator_drop().unwrap();
73                 let body = EarlyBinder(body.clone()).subst(tcx, substs);
74                 debug!("make_shim({:?}) = {:?}", instance, body);
75                 return body;
76             }
77
78             build_drop_shim(tcx, def_id, ty)
79         }
80         ty::InstanceDef::CloneShim(def_id, ty) => build_clone_shim(tcx, def_id, ty),
81         ty::InstanceDef::Virtual(..) => {
82             bug!("InstanceDef::Virtual ({:?}) is for direct calls only", instance)
83         }
84         ty::InstanceDef::Intrinsic(_) => {
85             bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
86         }
87     };
88     debug!("make_shim({:?}) = untransformed {:?}", instance, result);
89
90     pm::run_passes(
91         tcx,
92         &mut result,
93         &[
94             &add_moves_for_packed_drops::AddMovesForPackedDrops,
95             &deref_separator::Derefer,
96             &remove_noop_landing_pads::RemoveNoopLandingPads,
97             &simplify::SimplifyCfg::new("make_shim"),
98             &add_call_guards::CriticalCallEdges,
99             &abort_unwinding_calls::AbortUnwindingCalls,
100         ],
101         Some(MirPhase::Runtime(RuntimePhase::Optimized)),
102     );
103
104     debug!("make_shim({:?}) = {:?}", instance, result);
105
106     result
107 }
108
109 #[derive(Copy, Clone, Debug, PartialEq)]
110 enum Adjustment {
111     /// Pass the receiver as-is.
112     Identity,
113
114     /// We get passed `&[mut] self` and call the target with `*self`.
115     ///
116     /// This either copies `self` (if `Self: Copy`, eg. for function items), or moves out of it
117     /// (for `VTableShim`, which effectively is passed `&own Self`).
118     Deref,
119
120     /// We get passed `self: Self` and call the target with `&mut self`.
121     ///
122     /// In this case we need to ensure that the `Self` is dropped after the call, as the callee
123     /// won't do it for us.
124     RefMut,
125 }
126
127 #[derive(Copy, Clone, Debug, PartialEq)]
128 enum CallKind<'tcx> {
129     /// Call the `FnPtr` that was passed as the receiver.
130     Indirect(Ty<'tcx>),
131
132     /// Call a known `FnDef`.
133     Direct(DefId),
134 }
135
136 fn local_decls_for_sig<'tcx>(
137     sig: &ty::FnSig<'tcx>,
138     span: Span,
139 ) -> IndexVec<Local, LocalDecl<'tcx>> {
140     iter::once(LocalDecl::new(sig.output(), span))
141         .chain(sig.inputs().iter().map(|ity| LocalDecl::new(*ity, span).immutable()))
142         .collect()
143 }
144
145 fn build_drop_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, ty: Option<Ty<'tcx>>) -> Body<'tcx> {
146     debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
147
148     assert!(!matches!(ty, Some(ty) if ty.is_generator()));
149
150     let substs = if let Some(ty) = ty {
151         tcx.intern_substs(&[ty.into()])
152     } else {
153         InternalSubsts::identity_for_item(tcx, def_id)
154     };
155     let sig = tcx.bound_fn_sig(def_id).subst(tcx, substs);
156     let sig = tcx.erase_late_bound_regions(sig);
157     let span = tcx.def_span(def_id);
158
159     let source_info = SourceInfo::outermost(span);
160
161     let return_block = BasicBlock::new(1);
162     let mut blocks = IndexVec::with_capacity(2);
163     let block = |blocks: &mut IndexVec<_, _>, kind| {
164         blocks.push(BasicBlockData {
165             statements: vec![],
166             terminator: Some(Terminator { source_info, kind }),
167             is_cleanup: false,
168         })
169     };
170     block(&mut blocks, TerminatorKind::Goto { target: return_block });
171     block(&mut blocks, TerminatorKind::Return);
172
173     let source = MirSource::from_instance(ty::InstanceDef::DropGlue(def_id, ty));
174     let mut body =
175         new_body(source, blocks, local_decls_for_sig(&sig, span), sig.inputs().len(), span);
176
177     if ty.is_some() {
178         // The first argument (index 0), but add 1 for the return value.
179         let dropee_ptr = Place::from(Local::new(1 + 0));
180         if tcx.sess.opts.unstable_opts.mir_emit_retag {
181             // Function arguments should be retagged, and we make this one raw.
182             body.basic_blocks_mut()[START_BLOCK].statements.insert(
183                 0,
184                 Statement {
185                     source_info,
186                     kind: StatementKind::Retag(RetagKind::Raw, Box::new(dropee_ptr)),
187                 },
188             );
189         }
190         let patch = {
191             let param_env = tcx.param_env_reveal_all_normalized(def_id);
192             let mut elaborator =
193                 DropShimElaborator { body: &body, patch: MirPatch::new(&body), tcx, param_env };
194             let dropee = tcx.mk_place_deref(dropee_ptr);
195             let resume_block = elaborator.patch.resume_block();
196             elaborate_drops::elaborate_drop(
197                 &mut elaborator,
198                 source_info,
199                 dropee,
200                 (),
201                 return_block,
202                 elaborate_drops::Unwind::To(resume_block),
203                 START_BLOCK,
204             );
205             elaborator.patch
206         };
207         patch.apply(&mut body);
208     }
209
210     body
211 }
212
213 fn new_body<'tcx>(
214     source: MirSource<'tcx>,
215     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
216     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
217     arg_count: usize,
218     span: Span,
219 ) -> Body<'tcx> {
220     Body::new(
221         source,
222         basic_blocks,
223         IndexVec::from_elem_n(
224             SourceScopeData {
225                 span,
226                 parent_scope: None,
227                 inlined: None,
228                 inlined_parent_scope: None,
229                 local_data: ClearCrossCrate::Clear,
230             },
231             1,
232         ),
233         local_decls,
234         IndexVec::new(),
235         arg_count,
236         vec![],
237         span,
238         None,
239         // FIXME(compiler-errors): is this correct?
240         None,
241     )
242 }
243
244 pub struct DropShimElaborator<'a, 'tcx> {
245     pub body: &'a Body<'tcx>,
246     pub patch: MirPatch<'tcx>,
247     pub tcx: TyCtxt<'tcx>,
248     pub param_env: ty::ParamEnv<'tcx>,
249 }
250
251 impl fmt::Debug for DropShimElaborator<'_, '_> {
252     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
253         Ok(())
254     }
255 }
256
257 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
258     type Path = ();
259
260     fn patch(&mut self) -> &mut MirPatch<'tcx> {
261         &mut self.patch
262     }
263     fn body(&self) -> &'a Body<'tcx> {
264         self.body
265     }
266     fn tcx(&self) -> TyCtxt<'tcx> {
267         self.tcx
268     }
269     fn param_env(&self) -> ty::ParamEnv<'tcx> {
270         self.param_env
271     }
272
273     fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
274         match mode {
275             DropFlagMode::Shallow => {
276                 // Drops for the contained fields are "shallow" and "static" - they will simply call
277                 // the field's own drop glue.
278                 DropStyle::Static
279             }
280             DropFlagMode::Deep => {
281                 // The top-level drop is "deep" and "open" - it will be elaborated to a drop ladder
282                 // dropping each field contained in the value.
283                 DropStyle::Open
284             }
285         }
286     }
287
288     fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
289         None
290     }
291
292     fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {}
293
294     fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
295         None
296     }
297     fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
298         None
299     }
300     fn downcast_subpath(&self, _path: Self::Path, _variant: VariantIdx) -> Option<Self::Path> {
301         Some(())
302     }
303     fn array_subpath(&self, _path: Self::Path, _index: u64, _size: u64) -> Option<Self::Path> {
304         None
305     }
306 }
307
308 /// Builds a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`.
309 fn build_clone_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Body<'tcx> {
310     debug!("build_clone_shim(def_id={:?})", def_id);
311
312     let param_env = tcx.param_env(def_id);
313
314     let mut builder = CloneShimBuilder::new(tcx, def_id, self_ty);
315     let is_copy = self_ty.is_copy_modulo_regions(tcx, param_env);
316
317     let dest = Place::return_place();
318     let src = tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
319
320     match self_ty.kind() {
321         _ if is_copy => builder.copy_shim(),
322         ty::Closure(_, substs) => {
323             builder.tuple_like_shim(dest, src, substs.as_closure().upvar_tys())
324         }
325         ty::Tuple(..) => builder.tuple_like_shim(dest, src, self_ty.tuple_fields()),
326         ty::Generator(gen_def_id, substs, hir::Movability::Movable) => {
327             builder.generator_shim(dest, src, *gen_def_id, substs.as_generator())
328         }
329         _ => bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty),
330     };
331
332     builder.into_mir()
333 }
334
335 struct CloneShimBuilder<'tcx> {
336     tcx: TyCtxt<'tcx>,
337     def_id: DefId,
338     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
339     blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
340     span: Span,
341     sig: ty::FnSig<'tcx>,
342 }
343
344 impl<'tcx> CloneShimBuilder<'tcx> {
345     fn new(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Self {
346         // we must subst the self_ty because it's
347         // otherwise going to be TySelf and we can't index
348         // or access fields of a Place of type TySelf.
349         let substs = tcx.mk_substs_trait(self_ty, &[]);
350         let sig = tcx.bound_fn_sig(def_id).subst(tcx, substs);
351         let sig = tcx.erase_late_bound_regions(sig);
352         let span = tcx.def_span(def_id);
353
354         CloneShimBuilder {
355             tcx,
356             def_id,
357             local_decls: local_decls_for_sig(&sig, span),
358             blocks: IndexVec::new(),
359             span,
360             sig,
361         }
362     }
363
364     fn into_mir(self) -> Body<'tcx> {
365         let source = MirSource::from_instance(ty::InstanceDef::CloneShim(
366             self.def_id,
367             self.sig.inputs_and_output[0],
368         ));
369         new_body(source, self.blocks, self.local_decls, self.sig.inputs().len(), self.span)
370     }
371
372     fn source_info(&self) -> SourceInfo {
373         SourceInfo::outermost(self.span)
374     }
375
376     fn block(
377         &mut self,
378         statements: Vec<Statement<'tcx>>,
379         kind: TerminatorKind<'tcx>,
380         is_cleanup: bool,
381     ) -> BasicBlock {
382         let source_info = self.source_info();
383         self.blocks.push(BasicBlockData {
384             statements,
385             terminator: Some(Terminator { source_info, kind }),
386             is_cleanup,
387         })
388     }
389
390     /// Gives the index of an upcoming BasicBlock, with an offset.
391     /// offset=0 will give you the index of the next BasicBlock,
392     /// offset=1 will give the index of the next-to-next block,
393     /// offset=-1 will give you the index of the last-created block
394     fn block_index_offset(&self, offset: usize) -> BasicBlock {
395         BasicBlock::new(self.blocks.len() + offset)
396     }
397
398     fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
399         Statement { source_info: self.source_info(), kind }
400     }
401
402     fn copy_shim(&mut self) {
403         let rcvr = self.tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
404         let ret_statement = self.make_statement(StatementKind::Assign(Box::new((
405             Place::return_place(),
406             Rvalue::Use(Operand::Copy(rcvr)),
407         ))));
408         self.block(vec![ret_statement], TerminatorKind::Return, false);
409     }
410
411     fn make_place(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Place<'tcx> {
412         let span = self.span;
413         let mut local = LocalDecl::new(ty, span);
414         if mutability == Mutability::Not {
415             local = local.immutable();
416         }
417         Place::from(self.local_decls.push(local))
418     }
419
420     fn make_clone_call(
421         &mut self,
422         dest: Place<'tcx>,
423         src: Place<'tcx>,
424         ty: Ty<'tcx>,
425         next: BasicBlock,
426         cleanup: BasicBlock,
427     ) {
428         let tcx = self.tcx;
429
430         let substs = tcx.mk_substs_trait(ty, &[]);
431
432         // `func == Clone::clone(&ty) -> ty`
433         let func_ty = tcx.mk_fn_def(self.def_id, substs);
434         let func = Operand::Constant(Box::new(Constant {
435             span: self.span,
436             user_ty: None,
437             literal: ConstantKind::zero_sized(func_ty),
438         }));
439
440         let ref_loc = self.make_place(
441             Mutability::Not,
442             tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty, mutbl: hir::Mutability::Not }),
443         );
444
445         // `let ref_loc: &ty = &src;`
446         let statement = self.make_statement(StatementKind::Assign(Box::new((
447             ref_loc,
448             Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, src),
449         ))));
450
451         // `let loc = Clone::clone(ref_loc);`
452         self.block(
453             vec![statement],
454             TerminatorKind::Call {
455                 func,
456                 args: vec![Operand::Move(ref_loc)],
457                 destination: dest,
458                 target: Some(next),
459                 cleanup: Some(cleanup),
460                 from_hir_call: true,
461                 fn_span: self.span,
462             },
463             false,
464         );
465     }
466
467     fn clone_fields<I>(
468         &mut self,
469         dest: Place<'tcx>,
470         src: Place<'tcx>,
471         target: BasicBlock,
472         mut unwind: BasicBlock,
473         tys: I,
474     ) -> BasicBlock
475     where
476         I: IntoIterator<Item = Ty<'tcx>>,
477     {
478         // For an iterator of length n, create 2*n + 1 blocks.
479         for (i, ity) in tys.into_iter().enumerate() {
480             // Each iteration creates two blocks, referred to here as block 2*i and block 2*i + 1.
481             //
482             // Block 2*i attempts to clone the field. If successful it branches to 2*i + 2 (the
483             // next clone block). If unsuccessful it branches to the previous unwind block, which
484             // is initially the `unwind` argument passed to this function.
485             //
486             // Block 2*i + 1 is the unwind block for this iteration. It drops the cloned value
487             // created by block 2*i. We store this block in `unwind` so that the next clone block
488             // will unwind to it if cloning fails.
489
490             let field = Field::new(i);
491             let src_field = self.tcx.mk_place_field(src, field, ity);
492
493             let dest_field = self.tcx.mk_place_field(dest, field, ity);
494
495             let next_unwind = self.block_index_offset(1);
496             let next_block = self.block_index_offset(2);
497             self.make_clone_call(dest_field, src_field, ity, next_block, unwind);
498             self.block(
499                 vec![],
500                 TerminatorKind::Drop { place: dest_field, target: unwind, unwind: None },
501                 true,
502             );
503             unwind = next_unwind;
504         }
505         // If all clones succeed then we end up here.
506         self.block(vec![], TerminatorKind::Goto { target }, false);
507         unwind
508     }
509
510     fn tuple_like_shim<I>(&mut self, dest: Place<'tcx>, src: Place<'tcx>, tys: I)
511     where
512         I: IntoIterator<Item = Ty<'tcx>>,
513     {
514         self.block(vec![], TerminatorKind::Goto { target: self.block_index_offset(3) }, false);
515         let unwind = self.block(vec![], TerminatorKind::Resume, true);
516         let target = self.block(vec![], TerminatorKind::Return, false);
517
518         let _final_cleanup_block = self.clone_fields(dest, src, target, unwind, tys);
519     }
520
521     fn generator_shim(
522         &mut self,
523         dest: Place<'tcx>,
524         src: Place<'tcx>,
525         gen_def_id: DefId,
526         substs: GeneratorSubsts<'tcx>,
527     ) {
528         self.block(vec![], TerminatorKind::Goto { target: self.block_index_offset(3) }, false);
529         let unwind = self.block(vec![], TerminatorKind::Resume, true);
530         // This will get overwritten with a switch once we know the target blocks
531         let switch = self.block(vec![], TerminatorKind::Unreachable, false);
532         let unwind = self.clone_fields(dest, src, switch, unwind, substs.upvar_tys());
533         let target = self.block(vec![], TerminatorKind::Return, false);
534         let unreachable = self.block(vec![], TerminatorKind::Unreachable, false);
535         let mut cases = Vec::with_capacity(substs.state_tys(gen_def_id, self.tcx).count());
536         for (index, state_tys) in substs.state_tys(gen_def_id, self.tcx).enumerate() {
537             let variant_index = VariantIdx::new(index);
538             let dest = self.tcx.mk_place_downcast_unnamed(dest, variant_index);
539             let src = self.tcx.mk_place_downcast_unnamed(src, variant_index);
540             let clone_block = self.block_index_offset(1);
541             let start_block = self.block(
542                 vec![self.make_statement(StatementKind::SetDiscriminant {
543                     place: Box::new(Place::return_place()),
544                     variant_index,
545                 })],
546                 TerminatorKind::Goto { target: clone_block },
547                 false,
548             );
549             cases.push((index as u128, start_block));
550             let _final_cleanup_block = self.clone_fields(dest, src, target, unwind, state_tys);
551         }
552         let discr_ty = substs.discr_ty(self.tcx);
553         let temp = self.make_place(Mutability::Mut, discr_ty);
554         let rvalue = Rvalue::Discriminant(src);
555         let statement = self.make_statement(StatementKind::Assign(Box::new((temp, rvalue))));
556         match &mut self.blocks[switch] {
557             BasicBlockData { statements, terminator: Some(Terminator { kind, .. }), .. } => {
558                 statements.push(statement);
559                 *kind = TerminatorKind::SwitchInt {
560                     discr: Operand::Move(temp),
561                     switch_ty: discr_ty,
562                     targets: SwitchTargets::new(cases.into_iter(), unreachable),
563                 };
564             }
565             BasicBlockData { terminator: None, .. } => unreachable!(),
566         }
567     }
568 }
569
570 /// Builds a "call" shim for `instance`. The shim calls the function specified by `call_kind`,
571 /// first adjusting its first argument according to `rcvr_adjustment`.
572 fn build_call_shim<'tcx>(
573     tcx: TyCtxt<'tcx>,
574     instance: ty::InstanceDef<'tcx>,
575     rcvr_adjustment: Option<Adjustment>,
576     call_kind: CallKind<'tcx>,
577 ) -> Body<'tcx> {
578     debug!(
579         "build_call_shim(instance={:?}, rcvr_adjustment={:?}, call_kind={:?})",
580         instance, rcvr_adjustment, call_kind
581     );
582
583     // `FnPtrShim` contains the fn pointer type that a call shim is being built for - this is used
584     // to substitute into the signature of the shim. It is not necessary for users of this
585     // MIR body to perform further substitutions (see `InstanceDef::has_polymorphic_mir_body`).
586     let (sig_substs, untuple_args) = if let ty::InstanceDef::FnPtrShim(_, ty) = instance {
587         let sig = tcx.erase_late_bound_regions(ty.fn_sig(tcx));
588
589         let untuple_args = sig.inputs();
590
591         // Create substitutions for the `Self` and `Args` generic parameters of the shim body.
592         let arg_tup = tcx.mk_tup(untuple_args.iter());
593         let sig_substs = tcx.mk_substs_trait(ty, &[ty::subst::GenericArg::from(arg_tup)]);
594
595         (Some(sig_substs), Some(untuple_args))
596     } else {
597         (None, None)
598     };
599
600     let def_id = instance.def_id();
601     let sig = tcx.bound_fn_sig(def_id);
602     let sig = sig.map_bound(|sig| tcx.erase_late_bound_regions(sig));
603
604     assert_eq!(sig_substs.is_some(), !instance.has_polymorphic_mir_body());
605     let mut sig =
606         if let Some(sig_substs) = sig_substs { sig.subst(tcx, sig_substs) } else { sig.0 };
607
608     if let CallKind::Indirect(fnty) = call_kind {
609         // `sig` determines our local decls, and thus the callee type in the `Call` terminator. This
610         // can only be an `FnDef` or `FnPtr`, but currently will be `Self` since the types come from
611         // the implemented `FnX` trait.
612
613         // Apply the opposite adjustment to the MIR input.
614         let mut inputs_and_output = sig.inputs_and_output.to_vec();
615
616         // Initial signature is `fn(&? Self, Args) -> Self::Output` where `Args` is a tuple of the
617         // fn arguments. `Self` may be passed via (im)mutable reference or by-value.
618         assert_eq!(inputs_and_output.len(), 3);
619
620         // `Self` is always the original fn type `ty`. The MIR call terminator is only defined for
621         // `FnDef` and `FnPtr` callees, not the `Self` type param.
622         let self_arg = &mut inputs_and_output[0];
623         *self_arg = match rcvr_adjustment.unwrap() {
624             Adjustment::Identity => fnty,
625             Adjustment::Deref => tcx.mk_imm_ptr(fnty),
626             Adjustment::RefMut => tcx.mk_mut_ptr(fnty),
627         };
628         sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
629     }
630
631     // FIXME(eddyb) avoid having this snippet both here and in
632     // `Instance::fn_sig` (introduce `InstanceDef::fn_sig`?).
633     if let ty::InstanceDef::VTableShim(..) = instance {
634         // Modify fn(self, ...) to fn(self: *mut Self, ...)
635         let mut inputs_and_output = sig.inputs_and_output.to_vec();
636         let self_arg = &mut inputs_and_output[0];
637         debug_assert!(tcx.generics_of(def_id).has_self && *self_arg == tcx.types.self_param);
638         *self_arg = tcx.mk_mut_ptr(*self_arg);
639         sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
640     }
641
642     let span = tcx.def_span(def_id);
643
644     debug!("build_call_shim: sig={:?}", sig);
645
646     let mut local_decls = local_decls_for_sig(&sig, span);
647     let source_info = SourceInfo::outermost(span);
648
649     let rcvr_place = || {
650         assert!(rcvr_adjustment.is_some());
651         Place::from(Local::new(1 + 0))
652     };
653     let mut statements = vec![];
654
655     let rcvr = rcvr_adjustment.map(|rcvr_adjustment| match rcvr_adjustment {
656         Adjustment::Identity => Operand::Move(rcvr_place()),
657         Adjustment::Deref => Operand::Move(tcx.mk_place_deref(rcvr_place())),
658         Adjustment::RefMut => {
659             // let rcvr = &mut rcvr;
660             let ref_rcvr = local_decls.push(
661                 LocalDecl::new(
662                     tcx.mk_ref(
663                         tcx.lifetimes.re_erased,
664                         ty::TypeAndMut { ty: sig.inputs()[0], mutbl: hir::Mutability::Mut },
665                     ),
666                     span,
667                 )
668                 .immutable(),
669             );
670             let borrow_kind = BorrowKind::Mut { allow_two_phase_borrow: false };
671             statements.push(Statement {
672                 source_info,
673                 kind: StatementKind::Assign(Box::new((
674                     Place::from(ref_rcvr),
675                     Rvalue::Ref(tcx.lifetimes.re_erased, borrow_kind, rcvr_place()),
676                 ))),
677             });
678             Operand::Move(Place::from(ref_rcvr))
679         }
680     });
681
682     let (callee, mut args) = match call_kind {
683         // `FnPtr` call has no receiver. Args are untupled below.
684         CallKind::Indirect(_) => (rcvr.unwrap(), vec![]),
685
686         // `FnDef` call with optional receiver.
687         CallKind::Direct(def_id) => {
688             let ty = tcx.type_of(def_id);
689             (
690                 Operand::Constant(Box::new(Constant {
691                     span,
692                     user_ty: None,
693                     literal: ConstantKind::zero_sized(ty),
694                 })),
695                 rcvr.into_iter().collect::<Vec<_>>(),
696             )
697         }
698     };
699
700     let mut arg_range = 0..sig.inputs().len();
701
702     // Take the `self` ("receiver") argument out of the range (it's adjusted above).
703     if rcvr_adjustment.is_some() {
704         arg_range.start += 1;
705     }
706
707     // Take the last argument, if we need to untuple it (handled below).
708     if untuple_args.is_some() {
709         arg_range.end -= 1;
710     }
711
712     // Pass all of the non-special arguments directly.
713     args.extend(arg_range.map(|i| Operand::Move(Place::from(Local::new(1 + i)))));
714
715     // Untuple the last argument, if we have to.
716     if let Some(untuple_args) = untuple_args {
717         let tuple_arg = Local::new(1 + (sig.inputs().len() - 1));
718         args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
719             Operand::Move(tcx.mk_place_field(Place::from(tuple_arg), Field::new(i), *ity))
720         }));
721     }
722
723     let n_blocks = if let Some(Adjustment::RefMut) = rcvr_adjustment { 5 } else { 2 };
724     let mut blocks = IndexVec::with_capacity(n_blocks);
725     let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
726         blocks.push(BasicBlockData {
727             statements,
728             terminator: Some(Terminator { source_info, kind }),
729             is_cleanup,
730         })
731     };
732
733     // BB #0
734     block(
735         &mut blocks,
736         statements,
737         TerminatorKind::Call {
738             func: callee,
739             args,
740             destination: Place::return_place(),
741             target: Some(BasicBlock::new(1)),
742             cleanup: if let Some(Adjustment::RefMut) = rcvr_adjustment {
743                 Some(BasicBlock::new(3))
744             } else {
745                 None
746             },
747             from_hir_call: true,
748             fn_span: span,
749         },
750         false,
751     );
752
753     if let Some(Adjustment::RefMut) = rcvr_adjustment {
754         // BB #1 - drop for Self
755         block(
756             &mut blocks,
757             vec![],
758             TerminatorKind::Drop { place: rcvr_place(), target: BasicBlock::new(2), unwind: None },
759             false,
760         );
761     }
762     // BB #1/#2 - return
763     block(&mut blocks, vec![], TerminatorKind::Return, false);
764     if let Some(Adjustment::RefMut) = rcvr_adjustment {
765         // BB #3 - drop if closure panics
766         block(
767             &mut blocks,
768             vec![],
769             TerminatorKind::Drop { place: rcvr_place(), target: BasicBlock::new(4), unwind: None },
770             true,
771         );
772
773         // BB #4 - resume
774         block(&mut blocks, vec![], TerminatorKind::Resume, true);
775     }
776
777     let mut body =
778         new_body(MirSource::from_instance(instance), blocks, local_decls, sig.inputs().len(), span);
779
780     if let Abi::RustCall = sig.abi {
781         body.spread_arg = Some(Local::new(sig.inputs().len()));
782     }
783
784     body
785 }
786
787 pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> {
788     debug_assert!(tcx.is_constructor(ctor_id));
789
790     let param_env = tcx.param_env(ctor_id);
791
792     // Normalize the sig.
793     let sig = tcx.fn_sig(ctor_id).no_bound_vars().expect("LBR in ADT constructor signature");
794     let sig = tcx.normalize_erasing_regions(param_env, sig);
795
796     let ty::Adt(adt_def, substs) = sig.output().kind() else {
797         bug!("unexpected type for ADT ctor {:?}", sig.output());
798     };
799
800     debug!("build_ctor: ctor_id={:?} sig={:?}", ctor_id, sig);
801
802     let span = tcx.def_span(ctor_id);
803
804     let local_decls = local_decls_for_sig(&sig, span);
805
806     let source_info = SourceInfo::outermost(span);
807
808     let variant_index = if adt_def.is_enum() {
809         adt_def.variant_index_with_ctor_id(ctor_id)
810     } else {
811         VariantIdx::new(0)
812     };
813
814     // Generate the following MIR:
815     //
816     // (return as Variant).field0 = arg0;
817     // (return as Variant).field1 = arg1;
818     //
819     // return;
820     debug!("build_ctor: variant_index={:?}", variant_index);
821
822     let statements = expand_aggregate(
823         Place::return_place(),
824         adt_def.variant(variant_index).fields.iter().enumerate().map(|(idx, field_def)| {
825             (Operand::Move(Place::from(Local::new(idx + 1))), field_def.ty(tcx, substs))
826         }),
827         AggregateKind::Adt(adt_def.did(), variant_index, substs, None, None),
828         source_info,
829         tcx,
830     )
831     .collect();
832
833     let start_block = BasicBlockData {
834         statements,
835         terminator: Some(Terminator { source_info, kind: TerminatorKind::Return }),
836         is_cleanup: false,
837     };
838
839     let source = MirSource::item(ctor_id);
840     let body = new_body(
841         source,
842         IndexVec::from_elem_n(start_block, 1),
843         local_decls,
844         sig.inputs().len(),
845         span,
846     );
847
848     rustc_middle::mir::dump_mir(tcx, None, "mir_map", &0, &body, |_, _| Ok(()));
849
850     body
851 }