]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/shim.rs
Bless nll tests.
[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::subst::{InternalSubsts, Subst};
7 use rustc_middle::ty::{self, 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, marker, pass_manager as pm,
21     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::TyS::kind) {
72                 let body = tcx.optimized_mir(*gen_def_id).generator_drop().unwrap();
73                 let body = 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             &remove_noop_landing_pads::RemoveNoopLandingPads,
96             &simplify::SimplifyCfg::new("make_shim"),
97             &add_call_guards::CriticalCallEdges,
98             &abort_unwinding_calls::AbortUnwindingCalls,
99             &marker::PhaseChange(MirPhase::Const),
100         ],
101     );
102
103     debug!("make_shim({:?}) = {:?}", instance, result);
104
105     result
106 }
107
108 #[derive(Copy, Clone, Debug, PartialEq)]
109 enum Adjustment {
110     /// Pass the receiver as-is.
111     Identity,
112
113     /// We get passed `&[mut] self` and call the target with `*self`.
114     ///
115     /// This either copies `self` (if `Self: Copy`, eg. for function items), or moves out of it
116     /// (for `VtableShim`, which effectively is passed `&own Self`).
117     Deref,
118
119     /// We get passed `self: Self` and call the target with `&mut self`.
120     ///
121     /// In this case we need to ensure that the `Self` is dropped after the call, as the callee
122     /// won't do it for us.
123     RefMut,
124 }
125
126 #[derive(Copy, Clone, Debug, PartialEq)]
127 enum CallKind<'tcx> {
128     /// Call the `FnPtr` that was passed as the receiver.
129     Indirect(Ty<'tcx>),
130
131     /// Call a known `FnDef`.
132     Direct(DefId),
133 }
134
135 fn local_decls_for_sig<'tcx>(
136     sig: &ty::FnSig<'tcx>,
137     span: Span,
138 ) -> IndexVec<Local, LocalDecl<'tcx>> {
139     iter::once(LocalDecl::new(sig.output(), span))
140         .chain(sig.inputs().iter().map(|ity| LocalDecl::new(ity, span).immutable()))
141         .collect()
142 }
143
144 fn build_drop_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, ty: Option<Ty<'tcx>>) -> Body<'tcx> {
145     debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
146
147     assert!(!matches!(ty, Some(ty) if ty.is_generator()));
148
149     let substs = if let Some(ty) = ty {
150         tcx.intern_substs(&[ty.into()])
151     } else {
152         InternalSubsts::identity_for_item(tcx, def_id)
153     };
154     let sig = tcx.fn_sig(def_id).subst(tcx, substs);
155     let sig = tcx.erase_late_bound_regions(sig);
156     let span = tcx.def_span(def_id);
157
158     let source_info = SourceInfo::outermost(span);
159
160     let return_block = BasicBlock::new(1);
161     let mut blocks = IndexVec::with_capacity(2);
162     let block = |blocks: &mut IndexVec<_, _>, kind| {
163         blocks.push(BasicBlockData {
164             statements: vec![],
165             terminator: Some(Terminator { source_info, kind }),
166             is_cleanup: false,
167         })
168     };
169     block(&mut blocks, TerminatorKind::Goto { target: return_block });
170     block(&mut blocks, TerminatorKind::Return);
171
172     let source = MirSource::from_instance(ty::InstanceDef::DropGlue(def_id, ty));
173     let mut body =
174         new_body(source, blocks, local_decls_for_sig(&sig, span), sig.inputs().len(), span);
175
176     if ty.is_some() {
177         // The first argument (index 0), but add 1 for the return value.
178         let dropee_ptr = Place::from(Local::new(1 + 0));
179         if tcx.sess.opts.debugging_opts.mir_emit_retag {
180             // Function arguments should be retagged, and we make this one raw.
181             body.basic_blocks_mut()[START_BLOCK].statements.insert(
182                 0,
183                 Statement {
184                     source_info,
185                     kind: StatementKind::Retag(RetagKind::Raw, Box::new(dropee_ptr)),
186                 },
187             );
188         }
189         let patch = {
190             let param_env = tcx.param_env_reveal_all_normalized(def_id);
191             let mut elaborator =
192                 DropShimElaborator { body: &body, patch: MirPatch::new(&body), tcx, param_env };
193             let dropee = tcx.mk_place_deref(dropee_ptr);
194             let resume_block = elaborator.patch.resume_block();
195             elaborate_drops::elaborate_drop(
196                 &mut elaborator,
197                 source_info,
198                 dropee,
199                 (),
200                 return_block,
201                 elaborate_drops::Unwind::To(resume_block),
202                 START_BLOCK,
203             );
204             elaborator.patch
205         };
206         patch.apply(&mut body);
207     }
208
209     body
210 }
211
212 fn new_body<'tcx>(
213     source: MirSource<'tcx>,
214     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
215     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
216     arg_count: usize,
217     span: Span,
218 ) -> Body<'tcx> {
219     Body::new(
220         source,
221         basic_blocks,
222         IndexVec::from_elem_n(
223             SourceScopeData {
224                 span,
225                 parent_scope: None,
226                 inlined: None,
227                 inlined_parent_scope: None,
228                 local_data: ClearCrossCrate::Clear,
229             },
230             1,
231         ),
232         local_decls,
233         IndexVec::new(),
234         arg_count,
235         vec![],
236         span,
237         None,
238     )
239 }
240
241 pub struct DropShimElaborator<'a, 'tcx> {
242     pub body: &'a Body<'tcx>,
243     pub patch: MirPatch<'tcx>,
244     pub tcx: TyCtxt<'tcx>,
245     pub param_env: ty::ParamEnv<'tcx>,
246 }
247
248 impl fmt::Debug for DropShimElaborator<'_, '_> {
249     fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
250         Ok(())
251     }
252 }
253
254 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
255     type Path = ();
256
257     fn patch(&mut self) -> &mut MirPatch<'tcx> {
258         &mut self.patch
259     }
260     fn body(&self) -> &'a Body<'tcx> {
261         self.body
262     }
263     fn tcx(&self) -> TyCtxt<'tcx> {
264         self.tcx
265     }
266     fn param_env(&self) -> ty::ParamEnv<'tcx> {
267         self.param_env
268     }
269
270     fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
271         match mode {
272             DropFlagMode::Shallow => {
273                 // Drops for the contained fields are "shallow" and "static" - they will simply call
274                 // the field's own drop glue.
275                 DropStyle::Static
276             }
277             DropFlagMode::Deep => {
278                 // The top-level drop is "deep" and "open" - it will be elaborated to a drop ladder
279                 // dropping each field contained in the value.
280                 DropStyle::Open
281             }
282         }
283     }
284
285     fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
286         None
287     }
288
289     fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {}
290
291     fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
292         None
293     }
294     fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
295         None
296     }
297     fn downcast_subpath(&self, _path: Self::Path, _variant: VariantIdx) -> Option<Self::Path> {
298         Some(())
299     }
300     fn array_subpath(&self, _path: Self::Path, _index: u64, _size: u64) -> Option<Self::Path> {
301         None
302     }
303 }
304
305 /// Builds a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`.
306 fn build_clone_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Body<'tcx> {
307     debug!("build_clone_shim(def_id={:?})", def_id);
308
309     let param_env = tcx.param_env(def_id);
310
311     let mut builder = CloneShimBuilder::new(tcx, def_id, self_ty);
312     let is_copy = self_ty.is_copy_modulo_regions(tcx.at(builder.span), param_env);
313
314     let dest = Place::return_place();
315     let src = tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
316
317     match self_ty.kind() {
318         _ if is_copy => builder.copy_shim(),
319         ty::Closure(_, substs) => {
320             builder.tuple_like_shim(dest, src, substs.as_closure().upvar_tys())
321         }
322         ty::Tuple(..) => builder.tuple_like_shim(dest, src, self_ty.tuple_fields()),
323         _ => bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty),
324     };
325
326     builder.into_mir()
327 }
328
329 struct CloneShimBuilder<'tcx> {
330     tcx: TyCtxt<'tcx>,
331     def_id: DefId,
332     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
333     blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
334     span: Span,
335     sig: ty::FnSig<'tcx>,
336 }
337
338 impl<'tcx> CloneShimBuilder<'tcx> {
339     fn new(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Self {
340         // we must subst the self_ty because it's
341         // otherwise going to be TySelf and we can't index
342         // or access fields of a Place of type TySelf.
343         let substs = tcx.mk_substs_trait(self_ty, &[]);
344         let sig = tcx.fn_sig(def_id).subst(tcx, substs);
345         let sig = tcx.erase_late_bound_regions(sig);
346         let span = tcx.def_span(def_id);
347
348         CloneShimBuilder {
349             tcx,
350             def_id,
351             local_decls: local_decls_for_sig(&sig, span),
352             blocks: IndexVec::new(),
353             span,
354             sig,
355         }
356     }
357
358     fn into_mir(self) -> Body<'tcx> {
359         let source = MirSource::from_instance(ty::InstanceDef::CloneShim(
360             self.def_id,
361             self.sig.inputs_and_output[0],
362         ));
363         new_body(source, self.blocks, self.local_decls, self.sig.inputs().len(), self.span)
364     }
365
366     fn source_info(&self) -> SourceInfo {
367         SourceInfo::outermost(self.span)
368     }
369
370     fn block(
371         &mut self,
372         statements: Vec<Statement<'tcx>>,
373         kind: TerminatorKind<'tcx>,
374         is_cleanup: bool,
375     ) -> BasicBlock {
376         let source_info = self.source_info();
377         self.blocks.push(BasicBlockData {
378             statements,
379             terminator: Some(Terminator { source_info, kind }),
380             is_cleanup,
381         })
382     }
383
384     /// Gives the index of an upcoming BasicBlock, with an offset.
385     /// offset=0 will give you the index of the next BasicBlock,
386     /// offset=1 will give the index of the next-to-next block,
387     /// offset=-1 will give you the index of the last-created block
388     fn block_index_offset(&mut self, offset: usize) -> BasicBlock {
389         BasicBlock::new(self.blocks.len() + offset)
390     }
391
392     fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
393         Statement { source_info: self.source_info(), kind }
394     }
395
396     fn copy_shim(&mut self) {
397         let rcvr = self.tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
398         let ret_statement = self.make_statement(StatementKind::Assign(Box::new((
399             Place::return_place(),
400             Rvalue::Use(Operand::Copy(rcvr)),
401         ))));
402         self.block(vec![ret_statement], TerminatorKind::Return, false);
403     }
404
405     fn make_place(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Place<'tcx> {
406         let span = self.span;
407         let mut local = LocalDecl::new(ty, span);
408         if mutability == Mutability::Not {
409             local = local.immutable();
410         }
411         Place::from(self.local_decls.push(local))
412     }
413
414     fn make_clone_call(
415         &mut self,
416         dest: Place<'tcx>,
417         src: Place<'tcx>,
418         ty: Ty<'tcx>,
419         next: BasicBlock,
420         cleanup: BasicBlock,
421     ) {
422         let tcx = self.tcx;
423
424         let substs = tcx.mk_substs_trait(ty, &[]);
425
426         // `func == Clone::clone(&ty) -> ty`
427         let func_ty = tcx.mk_fn_def(self.def_id, substs);
428         let func = Operand::Constant(Box::new(Constant {
429             span: self.span,
430             user_ty: None,
431             literal: ty::Const::zero_sized(tcx, func_ty).into(),
432         }));
433
434         let ref_loc = self.make_place(
435             Mutability::Not,
436             tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty, mutbl: hir::Mutability::Not }),
437         );
438
439         // `let ref_loc: &ty = &src;`
440         let statement = self.make_statement(StatementKind::Assign(Box::new((
441             ref_loc,
442             Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, src),
443         ))));
444
445         // `let loc = Clone::clone(ref_loc);`
446         self.block(
447             vec![statement],
448             TerminatorKind::Call {
449                 func,
450                 args: vec![Operand::Move(ref_loc)],
451                 destination: Some((dest, next)),
452                 cleanup: Some(cleanup),
453                 from_hir_call: true,
454                 fn_span: self.span,
455             },
456             false,
457         );
458     }
459
460     fn tuple_like_shim<I>(&mut self, dest: Place<'tcx>, src: Place<'tcx>, tys: I)
461     where
462         I: Iterator<Item = Ty<'tcx>>,
463     {
464         let mut previous_field = None;
465         for (i, ity) in tys.enumerate() {
466             let field = Field::new(i);
467             let src_field = self.tcx.mk_place_field(src, field, ity);
468
469             let dest_field = self.tcx.mk_place_field(dest, field, ity);
470
471             // #(2i + 1) is the cleanup block for the previous clone operation
472             let cleanup_block = self.block_index_offset(1);
473             // #(2i + 2) is the next cloning block
474             // (or the Return terminator if this is the last block)
475             let next_block = self.block_index_offset(2);
476
477             // BB #(2i)
478             // `dest.i = Clone::clone(&src.i);`
479             // Goto #(2i + 2) if ok, #(2i + 1) if unwinding happens.
480             self.make_clone_call(dest_field, src_field, ity, next_block, cleanup_block);
481
482             // BB #(2i + 1) (cleanup)
483             if let Some((previous_field, previous_cleanup)) = previous_field.take() {
484                 // Drop previous field and goto previous cleanup block.
485                 self.block(
486                     vec![],
487                     TerminatorKind::Drop {
488                         place: previous_field,
489                         target: previous_cleanup,
490                         unwind: None,
491                     },
492                     true,
493                 );
494             } else {
495                 // Nothing to drop, just resume.
496                 self.block(vec![], TerminatorKind::Resume, true);
497             }
498
499             previous_field = Some((dest_field, cleanup_block));
500         }
501
502         self.block(vec![], TerminatorKind::Return, false);
503     }
504 }
505
506 /// Builds a "call" shim for `instance`. The shim calls the function specified by `call_kind`,
507 /// first adjusting its first argument according to `rcvr_adjustment`.
508 fn build_call_shim<'tcx>(
509     tcx: TyCtxt<'tcx>,
510     instance: ty::InstanceDef<'tcx>,
511     rcvr_adjustment: Option<Adjustment>,
512     call_kind: CallKind<'tcx>,
513 ) -> Body<'tcx> {
514     debug!(
515         "build_call_shim(instance={:?}, rcvr_adjustment={:?}, call_kind={:?})",
516         instance, rcvr_adjustment, call_kind
517     );
518
519     // `FnPtrShim` contains the fn pointer type that a call shim is being built for - this is used
520     // to substitute into the signature of the shim. It is not necessary for users of this
521     // MIR body to perform further substitutions (see `InstanceDef::has_polymorphic_mir_body`).
522     let (sig_substs, untuple_args) = if let ty::InstanceDef::FnPtrShim(_, ty) = instance {
523         let sig = tcx.erase_late_bound_regions(ty.fn_sig(tcx));
524
525         let untuple_args = sig.inputs();
526
527         // Create substitutions for the `Self` and `Args` generic parameters of the shim body.
528         let arg_tup = tcx.mk_tup(untuple_args.iter());
529         let sig_substs = tcx.mk_substs_trait(ty, &[ty::subst::GenericArg::from(arg_tup)]);
530
531         (Some(sig_substs), Some(untuple_args))
532     } else {
533         (None, None)
534     };
535
536     let def_id = instance.def_id();
537     let sig = tcx.fn_sig(def_id);
538     let mut sig = tcx.erase_late_bound_regions(sig);
539
540     assert_eq!(sig_substs.is_some(), !instance.has_polymorphic_mir_body());
541     if let Some(sig_substs) = sig_substs {
542         sig = sig.subst(tcx, sig_substs);
543     }
544
545     if let CallKind::Indirect(fnty) = call_kind {
546         // `sig` determines our local decls, and thus the callee type in the `Call` terminator. This
547         // can only be an `FnDef` or `FnPtr`, but currently will be `Self` since the types come from
548         // the implemented `FnX` trait.
549
550         // Apply the opposite adjustment to the MIR input.
551         let mut inputs_and_output = sig.inputs_and_output.to_vec();
552
553         // Initial signature is `fn(&? Self, Args) -> Self::Output` where `Args` is a tuple of the
554         // fn arguments. `Self` may be passed via (im)mutable reference or by-value.
555         assert_eq!(inputs_and_output.len(), 3);
556
557         // `Self` is always the original fn type `ty`. The MIR call terminator is only defined for
558         // `FnDef` and `FnPtr` callees, not the `Self` type param.
559         let self_arg = &mut inputs_and_output[0];
560         *self_arg = match rcvr_adjustment.unwrap() {
561             Adjustment::Identity => fnty,
562             Adjustment::Deref => tcx.mk_imm_ptr(fnty),
563             Adjustment::RefMut => tcx.mk_mut_ptr(fnty),
564         };
565         sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
566     }
567
568     // FIXME(eddyb) avoid having this snippet both here and in
569     // `Instance::fn_sig` (introduce `InstanceDef::fn_sig`?).
570     if let ty::InstanceDef::VtableShim(..) = instance {
571         // Modify fn(self, ...) to fn(self: *mut Self, ...)
572         let mut inputs_and_output = sig.inputs_and_output.to_vec();
573         let self_arg = &mut inputs_and_output[0];
574         debug_assert!(tcx.generics_of(def_id).has_self && *self_arg == tcx.types.self_param);
575         *self_arg = tcx.mk_mut_ptr(*self_arg);
576         sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
577     }
578
579     let span = tcx.def_span(def_id);
580
581     debug!("build_call_shim: sig={:?}", sig);
582
583     let mut local_decls = local_decls_for_sig(&sig, span);
584     let source_info = SourceInfo::outermost(span);
585
586     let rcvr_place = || {
587         assert!(rcvr_adjustment.is_some());
588         Place::from(Local::new(1 + 0))
589     };
590     let mut statements = vec![];
591
592     let rcvr = rcvr_adjustment.map(|rcvr_adjustment| match rcvr_adjustment {
593         Adjustment::Identity => Operand::Move(rcvr_place()),
594         Adjustment::Deref => Operand::Move(tcx.mk_place_deref(rcvr_place())),
595         Adjustment::RefMut => {
596             // let rcvr = &mut rcvr;
597             let ref_rcvr = local_decls.push(
598                 LocalDecl::new(
599                     tcx.mk_ref(
600                         tcx.lifetimes.re_erased,
601                         ty::TypeAndMut { ty: sig.inputs()[0], mutbl: hir::Mutability::Mut },
602                     ),
603                     span,
604                 )
605                 .immutable(),
606             );
607             let borrow_kind = BorrowKind::Mut { allow_two_phase_borrow: false };
608             statements.push(Statement {
609                 source_info,
610                 kind: StatementKind::Assign(Box::new((
611                     Place::from(ref_rcvr),
612                     Rvalue::Ref(tcx.lifetimes.re_erased, borrow_kind, rcvr_place()),
613                 ))),
614             });
615             Operand::Move(Place::from(ref_rcvr))
616         }
617     });
618
619     let (callee, mut args) = match call_kind {
620         // `FnPtr` call has no receiver. Args are untupled below.
621         CallKind::Indirect(_) => (rcvr.unwrap(), vec![]),
622
623         // `FnDef` call with optional receiver.
624         CallKind::Direct(def_id) => {
625             let ty = tcx.type_of(def_id);
626             (
627                 Operand::Constant(Box::new(Constant {
628                     span,
629                     user_ty: None,
630                     literal: ty::Const::zero_sized(tcx, ty).into(),
631                 })),
632                 rcvr.into_iter().collect::<Vec<_>>(),
633             )
634         }
635     };
636
637     let mut arg_range = 0..sig.inputs().len();
638
639     // Take the `self` ("receiver") argument out of the range (it's adjusted above).
640     if rcvr_adjustment.is_some() {
641         arg_range.start += 1;
642     }
643
644     // Take the last argument, if we need to untuple it (handled below).
645     if untuple_args.is_some() {
646         arg_range.end -= 1;
647     }
648
649     // Pass all of the non-special arguments directly.
650     args.extend(arg_range.map(|i| Operand::Move(Place::from(Local::new(1 + i)))));
651
652     // Untuple the last argument, if we have to.
653     if let Some(untuple_args) = untuple_args {
654         let tuple_arg = Local::new(1 + (sig.inputs().len() - 1));
655         args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
656             Operand::Move(tcx.mk_place_field(Place::from(tuple_arg), Field::new(i), *ity))
657         }));
658     }
659
660     let n_blocks = if let Some(Adjustment::RefMut) = rcvr_adjustment { 5 } else { 2 };
661     let mut blocks = IndexVec::with_capacity(n_blocks);
662     let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
663         blocks.push(BasicBlockData {
664             statements,
665             terminator: Some(Terminator { source_info, kind }),
666             is_cleanup,
667         })
668     };
669
670     // BB #0
671     block(
672         &mut blocks,
673         statements,
674         TerminatorKind::Call {
675             func: callee,
676             args,
677             destination: Some((Place::return_place(), BasicBlock::new(1))),
678             cleanup: if let Some(Adjustment::RefMut) = rcvr_adjustment {
679                 Some(BasicBlock::new(3))
680             } else {
681                 None
682             },
683             from_hir_call: true,
684             fn_span: span,
685         },
686         false,
687     );
688
689     if let Some(Adjustment::RefMut) = rcvr_adjustment {
690         // BB #1 - drop for Self
691         block(
692             &mut blocks,
693             vec![],
694             TerminatorKind::Drop { place: rcvr_place(), target: BasicBlock::new(2), unwind: None },
695             false,
696         );
697     }
698     // BB #1/#2 - return
699     block(&mut blocks, vec![], TerminatorKind::Return, false);
700     if let Some(Adjustment::RefMut) = rcvr_adjustment {
701         // BB #3 - drop if closure panics
702         block(
703             &mut blocks,
704             vec![],
705             TerminatorKind::Drop { place: rcvr_place(), target: BasicBlock::new(4), unwind: None },
706             true,
707         );
708
709         // BB #4 - resume
710         block(&mut blocks, vec![], TerminatorKind::Resume, true);
711     }
712
713     let mut body =
714         new_body(MirSource::from_instance(instance), blocks, local_decls, sig.inputs().len(), span);
715
716     if let Abi::RustCall = sig.abi {
717         body.spread_arg = Some(Local::new(sig.inputs().len()));
718     }
719
720     body
721 }
722
723 pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> {
724     debug_assert!(tcx.is_constructor(ctor_id));
725
726     let span =
727         tcx.hir().span_if_local(ctor_id).unwrap_or_else(|| bug!("no span for ctor {:?}", ctor_id));
728
729     let param_env = tcx.param_env(ctor_id);
730
731     // Normalize the sig.
732     let sig = tcx.fn_sig(ctor_id).no_bound_vars().expect("LBR in ADT constructor signature");
733     let sig = tcx.normalize_erasing_regions(param_env, sig);
734
735     let (adt_def, substs) = match sig.output().kind() {
736         ty::Adt(adt_def, substs) => (adt_def, substs),
737         _ => bug!("unexpected type for ADT ctor {:?}", sig.output()),
738     };
739
740     debug!("build_ctor: ctor_id={:?} sig={:?}", ctor_id, sig);
741
742     let local_decls = local_decls_for_sig(&sig, span);
743
744     let source_info = SourceInfo::outermost(span);
745
746     let variant_index = if adt_def.is_enum() {
747         adt_def.variant_index_with_ctor_id(ctor_id)
748     } else {
749         VariantIdx::new(0)
750     };
751
752     // Generate the following MIR:
753     //
754     // (return as Variant).field0 = arg0;
755     // (return as Variant).field1 = arg1;
756     //
757     // return;
758     debug!("build_ctor: variant_index={:?}", variant_index);
759
760     let statements = expand_aggregate(
761         Place::return_place(),
762         adt_def.variants[variant_index].fields.iter().enumerate().map(|(idx, field_def)| {
763             (Operand::Move(Place::from(Local::new(idx + 1))), field_def.ty(tcx, substs))
764         }),
765         AggregateKind::Adt(adt_def.did, variant_index, substs, None, None),
766         source_info,
767         tcx,
768     )
769     .collect();
770
771     let start_block = BasicBlockData {
772         statements,
773         terminator: Some(Terminator { source_info, kind: TerminatorKind::Return }),
774         is_cleanup: false,
775     };
776
777     let source = MirSource::item(ctor_id);
778     let body = new_body(
779         source,
780         IndexVec::from_elem_n(start_block, 1),
781         local_decls,
782         sig.inputs().len(),
783         span,
784     );
785
786     rustc_middle::mir::dump_mir(tcx, None, "mir_map", &0, &body, |_, _| Ok(()));
787
788     body
789 }