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 },
259 pub struct DropShimElaborator<'a, 'tcx> {
260 pub body: &'a Body<'tcx>,
261 pub patch: MirPatch<'tcx>,
262 pub tcx: TyCtxt<'tcx>,
263 pub param_env: ty::ParamEnv<'tcx>,
266 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
267 fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
272 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
275 fn patch(&mut self) -> &mut MirPatch<'tcx> {
278 fn body(&self) -> &'a Body<'tcx> {
281 fn tcx(&self) -> TyCtxt<'tcx> {
284 fn param_env(&self) -> ty::ParamEnv<'tcx> {
288 fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
290 DropFlagMode::Shallow => {
291 // Drops for the contained fields are "shallow" and "static" - they will simply call
292 // the field's own drop glue.
295 DropFlagMode::Deep => {
296 // The top-level drop is "deep" and "open" - it will be elaborated to a drop ladder
297 // dropping each field contained in the value.
303 fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
307 fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {}
309 fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
312 fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
315 fn downcast_subpath(&self, _path: Self::Path, _variant: VariantIdx) -> Option<Self::Path> {
318 fn array_subpath(&self, _path: Self::Path, _index: u32, _size: u32) -> Option<Self::Path> {
323 /// Builds a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`.
324 fn build_clone_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Body<'tcx> {
325 debug!("build_clone_shim(def_id={:?})", def_id);
327 let param_env = tcx.param_env(def_id);
329 let mut builder = CloneShimBuilder::new(tcx, def_id, self_ty);
330 let is_copy = self_ty.is_copy_modulo_regions(tcx.at(builder.span), param_env);
332 let dest = Place::return_place();
333 let src = tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
336 _ if is_copy => builder.copy_shim(),
337 ty::Array(ty, len) => {
338 let len = len.eval_usize(tcx, param_env);
339 builder.array_shim(dest, src, ty, len)
341 ty::Closure(_, substs) => {
342 builder.tuple_like_shim(dest, src, substs.as_closure().upvar_tys())
344 ty::Tuple(..) => builder.tuple_like_shim(dest, src, self_ty.tuple_fields()),
345 _ => bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty),
351 struct CloneShimBuilder<'tcx> {
354 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
355 blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
357 sig: ty::FnSig<'tcx>,
360 impl CloneShimBuilder<'tcx> {
361 fn new(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Self {
362 // we must subst the self_ty because it's
363 // otherwise going to be TySelf and we can't index
364 // or access fields of a Place of type TySelf.
365 let substs = tcx.mk_substs_trait(self_ty, &[]);
366 let sig = tcx.fn_sig(def_id).subst(tcx, substs);
367 let sig = tcx.erase_late_bound_regions(&sig);
368 let span = tcx.def_span(def_id);
373 local_decls: local_decls_for_sig(&sig, span),
374 blocks: IndexVec::new(),
380 fn into_mir(self) -> Body<'tcx> {
381 new_body(self.blocks, self.local_decls, self.sig.inputs().len(), self.span)
384 fn source_info(&self) -> SourceInfo {
385 SourceInfo::outermost(self.span)
390 statements: Vec<Statement<'tcx>>,
391 kind: TerminatorKind<'tcx>,
394 let source_info = self.source_info();
395 self.blocks.push(BasicBlockData {
397 terminator: Some(Terminator { source_info, kind }),
402 /// Gives the index of an upcoming BasicBlock, with an offset.
403 /// offset=0 will give you the index of the next BasicBlock,
404 /// offset=1 will give the index of the next-to-next block,
405 /// offset=-1 will give you the index of the last-created block
406 fn block_index_offset(&mut self, offset: usize) -> BasicBlock {
407 BasicBlock::new(self.blocks.len() + offset)
410 fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
411 Statement { source_info: self.source_info(), kind }
414 fn copy_shim(&mut self) {
415 let rcvr = self.tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
416 let ret_statement = self.make_statement(StatementKind::Assign(box (
417 Place::return_place(),
418 Rvalue::Use(Operand::Copy(rcvr)),
420 self.block(vec![ret_statement], TerminatorKind::Return, false);
423 fn make_place(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Place<'tcx> {
424 let span = self.span;
425 let mut local = LocalDecl::new(ty, span);
426 if mutability == Mutability::Not {
427 local = local.immutable();
429 Place::from(self.local_decls.push(local))
442 let substs = tcx.mk_substs_trait(ty, &[]);
444 // `func == Clone::clone(&ty) -> ty`
445 let func_ty = tcx.mk_fn_def(self.def_id, substs);
446 let func = Operand::Constant(box Constant {
449 literal: ty::Const::zero_sized(tcx, func_ty),
452 let ref_loc = self.make_place(
454 tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty, mutbl: hir::Mutability::Not }),
457 // `let ref_loc: &ty = &src;`
458 let statement = self.make_statement(StatementKind::Assign(box (
460 Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, src),
463 // `let loc = Clone::clone(ref_loc);`
466 TerminatorKind::Call {
468 args: vec![Operand::Move(ref_loc)],
469 destination: Some((dest, next)),
470 cleanup: Some(cleanup),
482 loop_body: BasicBlock,
483 loop_end: BasicBlock,
488 let cond = self.make_place(Mutability::Mut, tcx.types.bool);
489 let compute_cond = self.make_statement(StatementKind::Assign(box (
491 Rvalue::BinaryOp(BinOp::Ne, Operand::Copy(end), Operand::Copy(beg)),
494 // `if end != beg { goto loop_body; } else { goto loop_end; }`
497 TerminatorKind::if_(tcx, Operand::Move(cond), loop_body, loop_end),
502 fn make_usize(&self, value: u64) -> Box<Constant<'tcx>> {
506 literal: ty::Const::from_usize(self.tcx, value),
510 fn array_shim(&mut self, dest: Place<'tcx>, src: Place<'tcx>, ty: Ty<'tcx>, len: u64) {
512 let span = self.span;
514 let beg = self.local_decls.push(LocalDecl::new(tcx.types.usize, span));
515 let end = self.make_place(Mutability::Not, tcx.types.usize);
518 // `let mut beg = 0;`
522 self.make_statement(StatementKind::Assign(box (
524 Rvalue::Use(Operand::Constant(self.make_usize(0))),
526 self.make_statement(StatementKind::Assign(box (
528 Rvalue::Use(Operand::Constant(self.make_usize(len))),
531 self.block(inits, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
538 self.loop_header(Place::from(beg), end, BasicBlock::new(2), BasicBlock::new(4), false);
541 // `dest[i] = Clone::clone(src[beg])`;
542 // Goto #3 if ok, #5 if unwinding happens.
543 let dest_field = self.tcx.mk_place_index(dest, beg);
544 let src_field = self.tcx.mk_place_index(src, beg);
545 self.make_clone_call(dest_field, src_field, ty, BasicBlock::new(3), BasicBlock::new(5));
550 let statements = vec![self.make_statement(StatementKind::Assign(box (
554 Operand::Copy(Place::from(beg)),
555 Operand::Constant(self.make_usize(1)),
558 self.block(statements, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
562 self.block(vec![], TerminatorKind::Return, false);
566 // `let mut beg = 0;`
569 let beg = self.local_decls.push(LocalDecl::new(tcx.types.usize, span));
570 let init = self.make_statement(StatementKind::Assign(box (
572 Rvalue::Use(Operand::Constant(self.make_usize(0))),
574 self.block(vec![init], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
576 // BB #6 (cleanup): loop {
590 // `drop(dest[beg])`;
593 TerminatorKind::Drop {
594 place: self.tcx.mk_place_index(dest, beg),
595 target: BasicBlock::new(8),
604 let statement = self.make_statement(StatementKind::Assign(box (
608 Operand::Copy(Place::from(beg)),
609 Operand::Constant(self.make_usize(1)),
612 self.block(vec![statement], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
615 self.block(vec![], TerminatorKind::Resume, true);
618 fn tuple_like_shim<I>(&mut self, dest: Place<'tcx>, src: Place<'tcx>, tys: I)
620 I: Iterator<Item = Ty<'tcx>>,
622 let mut previous_field = None;
623 for (i, ity) in tys.enumerate() {
624 let field = Field::new(i);
625 let src_field = self.tcx.mk_place_field(src, field, ity);
627 let dest_field = self.tcx.mk_place_field(dest, field, ity);
629 // #(2i + 1) is the cleanup block for the previous clone operation
630 let cleanup_block = self.block_index_offset(1);
631 // #(2i + 2) is the next cloning block
632 // (or the Return terminator if this is the last block)
633 let next_block = self.block_index_offset(2);
636 // `dest.i = Clone::clone(&src.i);`
637 // Goto #(2i + 2) if ok, #(2i + 1) if unwinding happens.
638 self.make_clone_call(dest_field, src_field, ity, next_block, cleanup_block);
640 // BB #(2i + 1) (cleanup)
641 if let Some((previous_field, previous_cleanup)) = previous_field.take() {
642 // Drop previous field and goto previous cleanup block.
645 TerminatorKind::Drop {
646 place: previous_field,
647 target: previous_cleanup,
653 // Nothing to drop, just resume.
654 self.block(vec![], TerminatorKind::Resume, true);
657 previous_field = Some((dest_field, cleanup_block));
660 self.block(vec![], TerminatorKind::Return, false);
664 /// Builds a "call" shim for `instance`. The shim calls the
665 /// function specified by `call_kind`, first adjusting its first
666 /// argument according to `rcvr_adjustment`.
668 /// If `untuple_args` is a vec of types, the second argument of the
669 /// function will be untupled as these types.
670 fn build_call_shim<'tcx>(
672 instance: ty::InstanceDef<'tcx>,
673 rcvr_adjustment: Option<Adjustment>,
674 call_kind: CallKind<'tcx>,
675 untuple_args: Option<&[Ty<'tcx>]>,
678 "build_call_shim(instance={:?}, rcvr_adjustment={:?}, \
679 call_kind={:?}, untuple_args={:?})",
680 instance, rcvr_adjustment, call_kind, untuple_args
683 let def_id = instance.def_id();
684 let sig = tcx.fn_sig(def_id);
685 let mut sig = tcx.erase_late_bound_regions(&sig);
687 if let CallKind::Indirect(fnty) = call_kind {
688 // `sig` determines our local decls, and thus the callee type in the `Call` terminator. This
689 // can only be an `FnDef` or `FnPtr`, but currently will be `Self` since the types come from
690 // the implemented `FnX` trait.
692 // Apply the opposite adjustment to the MIR input.
693 let mut inputs_and_output = sig.inputs_and_output.to_vec();
695 // Initial signature is `fn(&? Self, Args) -> Self::Output` where `Args` is a tuple of the
696 // fn arguments. `Self` may be passed via (im)mutable reference or by-value.
697 assert_eq!(inputs_and_output.len(), 3);
699 // `Self` is always the original fn type `ty`. The MIR call terminator is only defined for
700 // `FnDef` and `FnPtr` callees, not the `Self` type param.
701 let self_arg = &mut inputs_and_output[0];
702 *self_arg = match rcvr_adjustment.unwrap() {
703 Adjustment::Identity => fnty,
704 Adjustment::Deref => tcx.mk_imm_ptr(fnty),
705 Adjustment::RefMut => tcx.mk_mut_ptr(fnty),
707 sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
710 // FIXME(eddyb) avoid having this snippet both here and in
711 // `Instance::fn_sig` (introduce `InstanceDef::fn_sig`?).
712 if let ty::InstanceDef::VtableShim(..) = instance {
713 // Modify fn(self, ...) to fn(self: *mut Self, ...)
714 let mut inputs_and_output = sig.inputs_and_output.to_vec();
715 let self_arg = &mut inputs_and_output[0];
716 debug_assert!(tcx.generics_of(def_id).has_self && *self_arg == tcx.types.self_param);
717 *self_arg = tcx.mk_mut_ptr(*self_arg);
718 sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
721 let span = tcx.def_span(def_id);
723 debug!("build_call_shim: sig={:?}", sig);
725 let mut local_decls = local_decls_for_sig(&sig, span);
726 let source_info = SourceInfo::outermost(span);
728 let rcvr_place = || {
729 assert!(rcvr_adjustment.is_some());
730 Place::from(Local::new(1 + 0))
732 let mut statements = vec![];
734 let rcvr = rcvr_adjustment.map(|rcvr_adjustment| match rcvr_adjustment {
735 Adjustment::Identity => Operand::Move(rcvr_place()),
736 Adjustment::Deref => Operand::Move(tcx.mk_place_deref(rcvr_place())),
737 Adjustment::RefMut => {
738 // let rcvr = &mut rcvr;
739 let ref_rcvr = local_decls.push(
742 tcx.lifetimes.re_erased,
743 ty::TypeAndMut { ty: sig.inputs()[0], mutbl: hir::Mutability::Mut },
749 let borrow_kind = BorrowKind::Mut { allow_two_phase_borrow: false };
750 statements.push(Statement {
752 kind: StatementKind::Assign(box (
753 Place::from(ref_rcvr),
754 Rvalue::Ref(tcx.lifetimes.re_erased, borrow_kind, rcvr_place()),
757 Operand::Move(Place::from(ref_rcvr))
761 let (callee, mut args) = match call_kind {
762 // `FnPtr` call has no receiver. Args are untupled below.
763 CallKind::Indirect(_) => (rcvr.unwrap(), vec![]),
765 // `FnDef` call with optional receiver.
766 CallKind::Direct(def_id) => {
767 let ty = tcx.type_of(def_id);
769 Operand::Constant(box Constant {
772 literal: ty::Const::zero_sized(tcx, ty),
774 rcvr.into_iter().collect::<Vec<_>>(),
779 let mut arg_range = 0..sig.inputs().len();
781 // Take the `self` ("receiver") argument out of the range (it's adjusted above).
782 if rcvr_adjustment.is_some() {
783 arg_range.start += 1;
786 // Take the last argument, if we need to untuple it (handled below).
787 if untuple_args.is_some() {
791 // Pass all of the non-special arguments directly.
792 args.extend(arg_range.map(|i| Operand::Move(Place::from(Local::new(1 + i)))));
794 // Untuple the last argument, if we have to.
795 if let Some(untuple_args) = untuple_args {
796 let tuple_arg = Local::new(1 + (sig.inputs().len() - 1));
797 args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
798 Operand::Move(tcx.mk_place_field(Place::from(tuple_arg), Field::new(i), *ity))
802 let n_blocks = if let Some(Adjustment::RefMut) = rcvr_adjustment { 5 } else { 2 };
803 let mut blocks = IndexVec::with_capacity(n_blocks);
804 let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
805 blocks.push(BasicBlockData {
807 terminator: Some(Terminator { source_info, kind }),
816 TerminatorKind::Call {
819 destination: Some((Place::return_place(), BasicBlock::new(1))),
820 cleanup: if let Some(Adjustment::RefMut) = rcvr_adjustment {
821 Some(BasicBlock::new(3))
831 if let Some(Adjustment::RefMut) = rcvr_adjustment {
832 // BB #1 - drop for Self
836 TerminatorKind::Drop { place: rcvr_place(), target: BasicBlock::new(2), unwind: None },
841 block(&mut blocks, vec![], TerminatorKind::Return, false);
842 if let Some(Adjustment::RefMut) = rcvr_adjustment {
843 // BB #3 - drop if closure panics
847 TerminatorKind::Drop { place: rcvr_place(), target: BasicBlock::new(4), unwind: None },
852 block(&mut blocks, vec![], TerminatorKind::Resume, true);
855 let mut body = new_body(blocks, local_decls, sig.inputs().len(), span);
857 if let Abi::RustCall = sig.abi {
858 body.spread_arg = Some(Local::new(sig.inputs().len()));
864 pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> {
865 debug_assert!(tcx.is_constructor(ctor_id));
868 tcx.hir().span_if_local(ctor_id).unwrap_or_else(|| bug!("no span for ctor {:?}", ctor_id));
870 let param_env = tcx.param_env(ctor_id);
872 // Normalize the sig.
873 let sig = tcx.fn_sig(ctor_id).no_bound_vars().expect("LBR in ADT constructor signature");
874 let sig = tcx.normalize_erasing_regions(param_env, sig);
876 let (adt_def, substs) = match sig.output().kind {
877 ty::Adt(adt_def, substs) => (adt_def, substs),
878 _ => bug!("unexpected type for ADT ctor {:?}", sig.output()),
881 debug!("build_ctor: ctor_id={:?} sig={:?}", ctor_id, sig);
883 let local_decls = local_decls_for_sig(&sig, span);
885 let source_info = SourceInfo::outermost(span);
887 let variant_index = if adt_def.is_enum() {
888 adt_def.variant_index_with_ctor_id(ctor_id)
893 // Generate the following MIR:
895 // (return as Variant).field0 = arg0;
896 // (return as Variant).field1 = arg1;
899 debug!("build_ctor: variant_index={:?}", variant_index);
901 let statements = expand_aggregate(
902 Place::return_place(),
903 adt_def.variants[variant_index].fields.iter().enumerate().map(|(idx, field_def)| {
904 (Operand::Move(Place::from(Local::new(idx + 1))), field_def.ty(tcx, substs))
906 AggregateKind::Adt(adt_def, variant_index, substs, None, None),
912 let start_block = BasicBlockData {
914 terminator: Some(Terminator { source_info, kind: TerminatorKind::Return }),
919 new_body(IndexVec::from_elem_n(start_block, 1), local_decls, sig.inputs().len(), span);
921 crate::util::dump_mir(
926 crate::transform::MirSource::item(ctor_id),