2 use rustc_hir::def_id::DefId;
3 use rustc_hir::lang_items::FnMutTraitLangItem;
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, TypeFoldable};
8 use rustc_target::abi::VariantIdx;
10 use rustc_index::vec::{Idx, IndexVec};
13 use rustc_target::spec::abi::Abi;
18 use crate::transform::{
19 add_call_guards, add_moves_for_packed_drops, no_landing_pads, remove_noop_landing_pads,
22 use crate::util::elaborate_drops::{self, DropElaborator, DropFlagMode, DropStyle};
23 use crate::util::expand_aggregate;
24 use crate::util::patch::MirPatch;
26 pub fn provide(providers: &mut Providers) {
27 providers.mir_shims = make_shim;
30 fn make_shim<'tcx>(tcx: TyCtxt<'tcx>, instance: ty::InstanceDef<'tcx>) -> Body<'tcx> {
31 debug!("make_shim({:?})", instance);
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), None)
38 ty::InstanceDef::FnPtrShim(def_id, ty) => {
39 // FIXME(eddyb) support generating shims for a "shallow type",
40 // e.g. `Foo<_>` or `[_]` instead of requiring a fully monomorphic
41 // `Foo<Bar>` or `[String]` etc.
42 assert!(!ty.needs_subst());
44 let trait_ = tcx.trait_of_item(def_id).unwrap();
45 let adjustment = match tcx.fn_trait_kind_from_lang_item(trait_) {
46 Some(ty::ClosureKind::FnOnce) => Adjustment::Identity,
47 Some(ty::ClosureKind::FnMut | ty::ClosureKind::Fn) => Adjustment::Deref,
48 None => bug!("fn pointer {:?} is not an fn", ty),
50 // HACK: we need the "real" argument types for the MIR,
51 // but because our substs are (Self, Args), where Args
52 // is a tuple, we must include the *concrete* argument
53 // types in the MIR. They will be substituted again with
54 // the param-substs, but because they are concrete, this
55 // will not do any harm.
56 let sig = tcx.erase_late_bound_regions(&ty.fn_sig(tcx));
57 let arg_tys = sig.inputs();
59 build_call_shim(tcx, instance, Some(adjustment), CallKind::Indirect(ty), Some(arg_tys))
61 // We are generating a call back to our def-id, which the
62 // codegen backend knows to turn to an actual call, be it
63 // a virtual call, or a direct call to a function for which
64 // indirect calls must be codegen'd differently than direct ones
65 // (such as `#[track_caller]`).
66 ty::InstanceDef::ReifyShim(def_id) => {
67 build_call_shim(tcx, instance, None, CallKind::Direct(def_id), None)
69 ty::InstanceDef::ClosureOnceShim { call_once: _ } => {
70 let fn_mut = tcx.require_lang_item(FnMutTraitLangItem, None);
72 .associated_items(fn_mut)
73 .in_definition_order()
74 .find(|it| it.kind == ty::AssocKind::Fn)
81 Some(Adjustment::RefMut),
82 CallKind::Direct(call_mut),
86 ty::InstanceDef::DropGlue(def_id, ty) => {
87 // FIXME(eddyb) support generating shims for a "shallow type",
88 // e.g. `Foo<_>` or `[_]` instead of requiring a fully monomorphic
89 // `Foo<Bar>` or `[String]` etc.
90 assert!(!ty.needs_subst());
92 build_drop_shim(tcx, def_id, ty)
94 ty::InstanceDef::CloneShim(def_id, ty) => {
95 // FIXME(eddyb) support generating shims for a "shallow type",
96 // e.g. `Foo<_>` or `[_]` instead of requiring a fully monomorphic
97 // `Foo<Bar>` or `[String]` etc.
98 assert!(!ty.needs_subst());
100 build_clone_shim(tcx, def_id, ty)
102 ty::InstanceDef::Virtual(..) => {
103 bug!("InstanceDef::Virtual ({:?}) is for direct calls only", instance)
105 ty::InstanceDef::Intrinsic(_) => {
106 bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
109 debug!("make_shim({:?}) = untransformed {:?}", instance, result);
118 &add_moves_for_packed_drops::AddMovesForPackedDrops,
119 &no_landing_pads::NoLandingPads::new(tcx),
120 &remove_noop_landing_pads::RemoveNoopLandingPads,
121 &simplify::SimplifyCfg::new("make_shim"),
122 &add_call_guards::CriticalCallEdges,
126 debug!("make_shim({:?}) = {:?}", instance, result);
131 #[derive(Copy, Clone, Debug, PartialEq)]
133 /// Pass the receiver as-is.
136 /// We get passed `&[mut] self` and call the target with `*self`.
138 /// This either copies `self` (if `Self: Copy`, eg. for function items), or moves out of it
139 /// (for `VtableShim`, which effectively is passed `&own Self`).
142 /// We get passed `self: Self` and call the target with `&mut self`.
144 /// In this case we need to ensure that the `Self` is dropped after the call, as the callee
145 /// won't do it for us.
149 #[derive(Copy, Clone, Debug, PartialEq)]
150 enum CallKind<'tcx> {
151 /// Call the `FnPtr` that was passed as the receiver.
154 /// Call a known `FnDef`.
158 fn local_decls_for_sig<'tcx>(
159 sig: &ty::FnSig<'tcx>,
161 ) -> IndexVec<Local, LocalDecl<'tcx>> {
162 iter::once(LocalDecl::new(sig.output(), span))
163 .chain(sig.inputs().iter().map(|ity| LocalDecl::new(ity, span).immutable()))
167 fn build_drop_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, ty: Option<Ty<'tcx>>) -> Body<'tcx> {
168 debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
170 // Check if this is a generator, if so, return the drop glue for it
171 if let Some(&ty::TyS { kind: ty::Generator(gen_def_id, substs, _), .. }) = ty {
172 let body = &**tcx.optimized_mir(gen_def_id).generator_drop.as_ref().unwrap();
173 return body.subst(tcx, substs);
176 let substs = if let Some(ty) = ty {
177 tcx.intern_substs(&[ty.into()])
179 InternalSubsts::identity_for_item(tcx, def_id)
181 let sig = tcx.fn_sig(def_id).subst(tcx, substs);
182 let sig = tcx.erase_late_bound_regions(&sig);
183 let span = tcx.def_span(def_id);
185 let source_info = SourceInfo::outermost(span);
187 let return_block = BasicBlock::new(1);
188 let mut blocks = IndexVec::with_capacity(2);
189 let block = |blocks: &mut IndexVec<_, _>, kind| {
190 blocks.push(BasicBlockData {
192 terminator: Some(Terminator { source_info, kind }),
196 block(&mut blocks, TerminatorKind::Goto { target: return_block });
197 block(&mut blocks, TerminatorKind::Return);
199 let mut body = new_body(blocks, local_decls_for_sig(&sig, span), sig.inputs().len(), span);
201 if let Some(..) = ty {
202 // The first argument (index 0), but add 1 for the return value.
203 let dropee_ptr = Place::from(Local::new(1 + 0));
204 if tcx.sess.opts.debugging_opts.mir_emit_retag {
205 // Function arguments should be retagged, and we make this one raw.
206 body.basic_blocks_mut()[START_BLOCK].statements.insert(
210 kind: StatementKind::Retag(RetagKind::Raw, box (dropee_ptr)),
215 let param_env = tcx.param_env(def_id).with_reveal_all();
217 DropShimElaborator { body: &body, patch: MirPatch::new(&body), tcx, param_env };
218 let dropee = tcx.mk_place_deref(dropee_ptr);
219 let resume_block = elaborator.patch.resume_block();
220 elaborate_drops::elaborate_drop(
226 elaborate_drops::Unwind::To(resume_block),
231 patch.apply(&mut body);
238 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
239 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
245 IndexVec::from_elem_n(
246 SourceScopeData { span, parent_scope: None, local_data: ClearCrossCrate::Clear },
258 pub struct DropShimElaborator<'a, 'tcx> {
259 pub body: &'a Body<'tcx>,
260 pub patch: MirPatch<'tcx>,
261 pub tcx: TyCtxt<'tcx>,
262 pub param_env: ty::ParamEnv<'tcx>,
265 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
266 fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
271 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
274 fn patch(&mut self) -> &mut MirPatch<'tcx> {
277 fn body(&self) -> &'a Body<'tcx> {
280 fn tcx(&self) -> TyCtxt<'tcx> {
283 fn param_env(&self) -> ty::ParamEnv<'tcx> {
287 fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
289 DropFlagMode::Shallow => {
290 // Drops for the contained fields are "shallow" and "static" - they will simply call
291 // the field's own drop glue.
294 DropFlagMode::Deep => {
295 // The top-level drop is "deep" and "open" - it will be elaborated to a drop ladder
296 // dropping each field contained in the value.
302 fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
306 fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {}
308 fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
311 fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
314 fn downcast_subpath(&self, _path: Self::Path, _variant: VariantIdx) -> Option<Self::Path> {
317 fn array_subpath(&self, _path: Self::Path, _index: u32, _size: u32) -> Option<Self::Path> {
322 /// Builds a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`.
323 fn build_clone_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Body<'tcx> {
324 debug!("build_clone_shim(def_id={:?})", def_id);
326 let param_env = tcx.param_env(def_id);
328 let mut builder = CloneShimBuilder::new(tcx, def_id, self_ty);
329 let is_copy = self_ty.is_copy_modulo_regions(tcx.at(builder.span), param_env);
331 let dest = Place::return_place();
332 let src = tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
335 _ if is_copy => builder.copy_shim(),
336 ty::Array(ty, len) => {
337 let len = len.eval_usize(tcx, param_env);
338 builder.array_shim(dest, src, ty, len)
340 ty::Closure(_, substs) => {
341 builder.tuple_like_shim(dest, src, substs.as_closure().upvar_tys())
343 ty::Tuple(..) => builder.tuple_like_shim(dest, src, self_ty.tuple_fields()),
344 _ => bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty),
350 struct CloneShimBuilder<'tcx> {
353 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
354 blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
356 sig: ty::FnSig<'tcx>,
359 impl CloneShimBuilder<'tcx> {
360 fn new(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Self {
361 // we must subst the self_ty because it's
362 // otherwise going to be TySelf and we can't index
363 // or access fields of a Place of type TySelf.
364 let substs = tcx.mk_substs_trait(self_ty, &[]);
365 let sig = tcx.fn_sig(def_id).subst(tcx, substs);
366 let sig = tcx.erase_late_bound_regions(&sig);
367 let span = tcx.def_span(def_id);
372 local_decls: local_decls_for_sig(&sig, span),
373 blocks: IndexVec::new(),
379 fn into_mir(self) -> Body<'tcx> {
380 new_body(self.blocks, self.local_decls, self.sig.inputs().len(), self.span)
383 fn source_info(&self) -> SourceInfo {
384 SourceInfo::outermost(self.span)
389 statements: Vec<Statement<'tcx>>,
390 kind: TerminatorKind<'tcx>,
393 let source_info = self.source_info();
394 self.blocks.push(BasicBlockData {
396 terminator: Some(Terminator { source_info, kind }),
401 /// Gives the index of an upcoming BasicBlock, with an offset.
402 /// offset=0 will give you the index of the next BasicBlock,
403 /// offset=1 will give the index of the next-to-next block,
404 /// offset=-1 will give you the index of the last-created block
405 fn block_index_offset(&mut self, offset: usize) -> BasicBlock {
406 BasicBlock::new(self.blocks.len() + offset)
409 fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
410 Statement { source_info: self.source_info(), kind }
413 fn copy_shim(&mut self) {
414 let rcvr = self.tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
415 let ret_statement = self.make_statement(StatementKind::Assign(box (
416 Place::return_place(),
417 Rvalue::Use(Operand::Copy(rcvr)),
419 self.block(vec![ret_statement], TerminatorKind::Return, false);
422 fn make_place(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Place<'tcx> {
423 let span = self.span;
424 let mut local = LocalDecl::new(ty, span);
425 if mutability == Mutability::Not {
426 local = local.immutable();
428 Place::from(self.local_decls.push(local))
441 let substs = tcx.mk_substs_trait(ty, &[]);
443 // `func == Clone::clone(&ty) -> ty`
444 let func_ty = tcx.mk_fn_def(self.def_id, substs);
445 let func = Operand::Constant(box Constant {
448 literal: ty::Const::zero_sized(tcx, func_ty),
451 let ref_loc = self.make_place(
453 tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty, mutbl: hir::Mutability::Not }),
456 // `let ref_loc: &ty = &src;`
457 let statement = self.make_statement(StatementKind::Assign(box (
459 Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, src),
462 // `let loc = Clone::clone(ref_loc);`
465 TerminatorKind::Call {
467 args: vec![Operand::Move(ref_loc)],
468 destination: Some((dest, next)),
469 cleanup: Some(cleanup),
481 loop_body: BasicBlock,
482 loop_end: BasicBlock,
487 let cond = self.make_place(Mutability::Mut, tcx.types.bool);
488 let compute_cond = self.make_statement(StatementKind::Assign(box (
490 Rvalue::BinaryOp(BinOp::Ne, Operand::Copy(end), Operand::Copy(beg)),
493 // `if end != beg { goto loop_body; } else { goto loop_end; }`
496 TerminatorKind::if_(tcx, Operand::Move(cond), loop_body, loop_end),
501 fn make_usize(&self, value: u64) -> Box<Constant<'tcx>> {
505 literal: ty::Const::from_usize(self.tcx, value),
509 fn array_shim(&mut self, dest: Place<'tcx>, src: Place<'tcx>, ty: Ty<'tcx>, len: u64) {
511 let span = self.span;
513 let beg = self.local_decls.push(LocalDecl::new(tcx.types.usize, span));
514 let end = self.make_place(Mutability::Not, tcx.types.usize);
517 // `let mut beg = 0;`
521 self.make_statement(StatementKind::Assign(box (
523 Rvalue::Use(Operand::Constant(self.make_usize(0))),
525 self.make_statement(StatementKind::Assign(box (
527 Rvalue::Use(Operand::Constant(self.make_usize(len))),
530 self.block(inits, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
537 self.loop_header(Place::from(beg), end, BasicBlock::new(2), BasicBlock::new(4), false);
540 // `dest[i] = Clone::clone(src[beg])`;
541 // Goto #3 if ok, #5 if unwinding happens.
542 let dest_field = self.tcx.mk_place_index(dest, beg);
543 let src_field = self.tcx.mk_place_index(src, beg);
544 self.make_clone_call(dest_field, src_field, ty, BasicBlock::new(3), BasicBlock::new(5));
549 let statements = vec![self.make_statement(StatementKind::Assign(box (
553 Operand::Copy(Place::from(beg)),
554 Operand::Constant(self.make_usize(1)),
557 self.block(statements, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
561 self.block(vec![], TerminatorKind::Return, false);
565 // `let mut beg = 0;`
568 let beg = self.local_decls.push(LocalDecl::new(tcx.types.usize, span));
569 let init = self.make_statement(StatementKind::Assign(box (
571 Rvalue::Use(Operand::Constant(self.make_usize(0))),
573 self.block(vec![init], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
575 // BB #6 (cleanup): loop {
589 // `drop(dest[beg])`;
592 TerminatorKind::Drop {
593 place: self.tcx.mk_place_index(dest, beg),
594 target: BasicBlock::new(8),
603 let statement = self.make_statement(StatementKind::Assign(box (
607 Operand::Copy(Place::from(beg)),
608 Operand::Constant(self.make_usize(1)),
611 self.block(vec![statement], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
614 self.block(vec![], TerminatorKind::Resume, true);
617 fn tuple_like_shim<I>(&mut self, dest: Place<'tcx>, src: Place<'tcx>, tys: I)
619 I: Iterator<Item = Ty<'tcx>>,
621 let mut previous_field = None;
622 for (i, ity) in tys.enumerate() {
623 let field = Field::new(i);
624 let src_field = self.tcx.mk_place_field(src, field, ity);
626 let dest_field = self.tcx.mk_place_field(dest, field, ity);
628 // #(2i + 1) is the cleanup block for the previous clone operation
629 let cleanup_block = self.block_index_offset(1);
630 // #(2i + 2) is the next cloning block
631 // (or the Return terminator if this is the last block)
632 let next_block = self.block_index_offset(2);
635 // `dest.i = Clone::clone(&src.i);`
636 // Goto #(2i + 2) if ok, #(2i + 1) if unwinding happens.
637 self.make_clone_call(dest_field, src_field, ity, next_block, cleanup_block);
639 // BB #(2i + 1) (cleanup)
640 if let Some((previous_field, previous_cleanup)) = previous_field.take() {
641 // Drop previous field and goto previous cleanup block.
644 TerminatorKind::Drop {
645 place: previous_field,
646 target: previous_cleanup,
652 // Nothing to drop, just resume.
653 self.block(vec![], TerminatorKind::Resume, true);
656 previous_field = Some((dest_field, cleanup_block));
659 self.block(vec![], TerminatorKind::Return, false);
663 /// Builds a "call" shim for `instance`. The shim calls the
664 /// function specified by `call_kind`, first adjusting its first
665 /// argument according to `rcvr_adjustment`.
667 /// If `untuple_args` is a vec of types, the second argument of the
668 /// function will be untupled as these types.
669 fn build_call_shim<'tcx>(
671 instance: ty::InstanceDef<'tcx>,
672 rcvr_adjustment: Option<Adjustment>,
673 call_kind: CallKind<'tcx>,
674 untuple_args: Option<&[Ty<'tcx>]>,
677 "build_call_shim(instance={:?}, rcvr_adjustment={:?}, \
678 call_kind={:?}, untuple_args={:?})",
679 instance, rcvr_adjustment, call_kind, untuple_args
682 let def_id = instance.def_id();
683 let sig = tcx.fn_sig(def_id);
684 let mut sig = tcx.erase_late_bound_regions(&sig);
686 if let CallKind::Indirect(fnty) = call_kind {
687 // `sig` determines our local decls, and thus the callee type in the `Call` terminator. This
688 // can only be an `FnDef` or `FnPtr`, but currently will be `Self` since the types come from
689 // the implemented `FnX` trait.
691 // Apply the opposite adjustment to the MIR input.
692 let mut inputs_and_output = sig.inputs_and_output.to_vec();
694 // Initial signature is `fn(&? Self, Args) -> Self::Output` where `Args` is a tuple of the
695 // fn arguments. `Self` may be passed via (im)mutable reference or by-value.
696 assert_eq!(inputs_and_output.len(), 3);
698 // `Self` is always the original fn type `ty`. The MIR call terminator is only defined for
699 // `FnDef` and `FnPtr` callees, not the `Self` type param.
700 let self_arg = &mut inputs_and_output[0];
701 *self_arg = match rcvr_adjustment.unwrap() {
702 Adjustment::Identity => fnty,
703 Adjustment::Deref => tcx.mk_imm_ptr(fnty),
704 Adjustment::RefMut => tcx.mk_mut_ptr(fnty),
706 sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
709 // FIXME(eddyb) avoid having this snippet both here and in
710 // `Instance::fn_sig` (introduce `InstanceDef::fn_sig`?).
711 if let ty::InstanceDef::VtableShim(..) = instance {
712 // Modify fn(self, ...) to fn(self: *mut Self, ...)
713 let mut inputs_and_output = sig.inputs_and_output.to_vec();
714 let self_arg = &mut inputs_and_output[0];
715 debug_assert!(tcx.generics_of(def_id).has_self && *self_arg == tcx.types.self_param);
716 *self_arg = tcx.mk_mut_ptr(*self_arg);
717 sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
720 let span = tcx.def_span(def_id);
722 debug!("build_call_shim: sig={:?}", sig);
724 let mut local_decls = local_decls_for_sig(&sig, span);
725 let source_info = SourceInfo::outermost(span);
727 let rcvr_place = || {
728 assert!(rcvr_adjustment.is_some());
729 Place::from(Local::new(1 + 0))
731 let mut statements = vec![];
733 let rcvr = rcvr_adjustment.map(|rcvr_adjustment| match rcvr_adjustment {
734 Adjustment::Identity => Operand::Move(rcvr_place()),
735 Adjustment::Deref => Operand::Move(tcx.mk_place_deref(rcvr_place())),
736 Adjustment::RefMut => {
737 // let rcvr = &mut rcvr;
738 let ref_rcvr = local_decls.push(
741 tcx.lifetimes.re_erased,
742 ty::TypeAndMut { ty: sig.inputs()[0], mutbl: hir::Mutability::Mut },
748 let borrow_kind = BorrowKind::Mut { allow_two_phase_borrow: false };
749 statements.push(Statement {
751 kind: StatementKind::Assign(box (
752 Place::from(ref_rcvr),
753 Rvalue::Ref(tcx.lifetimes.re_erased, borrow_kind, rcvr_place()),
756 Operand::Move(Place::from(ref_rcvr))
760 let (callee, mut args) = match call_kind {
761 // `FnPtr` call has no receiver. Args are untupled below.
762 CallKind::Indirect(_) => (rcvr.unwrap(), vec![]),
764 // `FnDef` call with optional receiver.
765 CallKind::Direct(def_id) => {
766 let ty = tcx.type_of(def_id);
768 Operand::Constant(box Constant {
771 literal: ty::Const::zero_sized(tcx, ty),
773 rcvr.into_iter().collect::<Vec<_>>(),
778 let mut arg_range = 0..sig.inputs().len();
780 // Take the `self` ("receiver") argument out of the range (it's adjusted above).
781 if rcvr_adjustment.is_some() {
782 arg_range.start += 1;
785 // Take the last argument, if we need to untuple it (handled below).
786 if untuple_args.is_some() {
790 // Pass all of the non-special arguments directly.
791 args.extend(arg_range.map(|i| Operand::Move(Place::from(Local::new(1 + i)))));
793 // Untuple the last argument, if we have to.
794 if let Some(untuple_args) = untuple_args {
795 let tuple_arg = Local::new(1 + (sig.inputs().len() - 1));
796 args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
797 Operand::Move(tcx.mk_place_field(Place::from(tuple_arg), Field::new(i), *ity))
801 let n_blocks = if let Some(Adjustment::RefMut) = rcvr_adjustment { 5 } else { 2 };
802 let mut blocks = IndexVec::with_capacity(n_blocks);
803 let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
804 blocks.push(BasicBlockData {
806 terminator: Some(Terminator { source_info, kind }),
815 TerminatorKind::Call {
818 destination: Some((Place::return_place(), BasicBlock::new(1))),
819 cleanup: if let Some(Adjustment::RefMut) = rcvr_adjustment {
820 Some(BasicBlock::new(3))
830 if let Some(Adjustment::RefMut) = rcvr_adjustment {
831 // BB #1 - drop for Self
835 TerminatorKind::Drop { place: rcvr_place(), target: BasicBlock::new(2), unwind: None },
840 block(&mut blocks, vec![], TerminatorKind::Return, false);
841 if let Some(Adjustment::RefMut) = rcvr_adjustment {
842 // BB #3 - drop if closure panics
846 TerminatorKind::Drop { place: rcvr_place(), target: BasicBlock::new(4), unwind: None },
851 block(&mut blocks, vec![], TerminatorKind::Resume, true);
854 let mut body = new_body(blocks, local_decls, sig.inputs().len(), span);
856 if let Abi::RustCall = sig.abi {
857 body.spread_arg = Some(Local::new(sig.inputs().len()));
863 pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> {
864 debug_assert!(tcx.is_constructor(ctor_id));
867 tcx.hir().span_if_local(ctor_id).unwrap_or_else(|| bug!("no span for ctor {:?}", ctor_id));
869 let param_env = tcx.param_env(ctor_id);
871 // Normalize the sig.
872 let sig = tcx.fn_sig(ctor_id).no_bound_vars().expect("LBR in ADT constructor signature");
873 let sig = tcx.normalize_erasing_regions(param_env, sig);
875 let (adt_def, substs) = match sig.output().kind {
876 ty::Adt(adt_def, substs) => (adt_def, substs),
877 _ => bug!("unexpected type for ADT ctor {:?}", sig.output()),
880 debug!("build_ctor: ctor_id={:?} sig={:?}", ctor_id, sig);
882 let local_decls = local_decls_for_sig(&sig, span);
884 let source_info = SourceInfo::outermost(span);
886 let variant_index = if adt_def.is_enum() {
887 adt_def.variant_index_with_ctor_id(ctor_id)
892 // Generate the following MIR:
894 // (return as Variant).field0 = arg0;
895 // (return as Variant).field1 = arg1;
898 debug!("build_ctor: variant_index={:?}", variant_index);
900 let statements = expand_aggregate(
901 Place::return_place(),
902 adt_def.variants[variant_index].fields.iter().enumerate().map(|(idx, field_def)| {
903 (Operand::Move(Place::from(Local::new(idx + 1))), field_def.ty(tcx, substs))
905 AggregateKind::Adt(adt_def, variant_index, substs, None, None),
911 let start_block = BasicBlockData {
913 terminator: Some(Terminator { source_info, kind: TerminatorKind::Return }),
918 new_body(IndexVec::from_elem_n(start_block, 1), local_decls, sig.inputs().len(), span);
920 crate::util::dump_mir(
925 crate::transform::MirSource::item(ctor_id),