2 use rustc::ty::layout::VariantIdx;
3 use rustc::ty::query::Providers;
4 use rustc::ty::subst::{InternalSubsts, Subst};
5 use rustc::ty::{self, Ty, TyCtxt};
7 use rustc_hir::def_id::DefId;
9 use rustc_index::vec::{Idx, IndexVec};
11 use rustc_span::{sym, Span};
12 use rustc_target::spec::abi::Abi;
17 use crate::transform::{
18 add_call_guards, add_moves_for_packed_drops, no_landing_pads, remove_noop_landing_pads,
21 use crate::util::elaborate_drops::{self, DropElaborator, DropFlagMode, DropStyle};
22 use crate::util::expand_aggregate;
23 use crate::util::patch::MirPatch;
25 pub fn provide(providers: &mut Providers<'_>) {
26 providers.mir_shims = make_shim;
29 fn make_shim<'tcx>(tcx: TyCtxt<'tcx>, instance: ty::InstanceDef<'tcx>) -> &'tcx BodyAndCache<'tcx> {
30 debug!("make_shim({:?})", instance);
32 let mut result = match instance {
33 ty::InstanceDef::Item(..) => bug!("item {:?} passed to make_shim", instance),
34 ty::InstanceDef::VtableShim(def_id) => build_call_shim(
37 Some(Adjustment::DerefMove),
38 CallKind::Direct(def_id),
41 ty::InstanceDef::FnPtrShim(def_id, ty) => {
42 let trait_ = tcx.trait_of_item(def_id).unwrap();
43 let adjustment = match tcx.lang_items().fn_trait_kind(trait_) {
44 Some(ty::ClosureKind::FnOnce) => Adjustment::Identity,
45 Some(ty::ClosureKind::FnMut) | Some(ty::ClosureKind::Fn) => Adjustment::Deref,
46 None => bug!("fn pointer {:?} is not an fn", ty),
48 // HACK: we need the "real" argument types for the MIR,
49 // but because our substs are (Self, Args), where Args
50 // is a tuple, we must include the *concrete* argument
51 // types in the MIR. They will be substituted again with
52 // the param-substs, but because they are concrete, this
53 // will not do any harm.
54 let sig = tcx.erase_late_bound_regions(&ty.fn_sig(tcx));
55 let arg_tys = sig.inputs();
57 build_call_shim(tcx, instance, Some(adjustment), CallKind::Indirect, Some(arg_tys))
59 // We are generating a call back to our def-id, which the
60 // codegen backend knows to turn to an actual call, be it
61 // a virtual call, or a direct call to a function for which
62 // indirect calls must be codegen'd differently than direct ones
63 // (such as `#[track_caller]`).
64 ty::InstanceDef::ReifyShim(def_id) => {
65 build_call_shim(tcx, instance, None, CallKind::Direct(def_id), None)
67 ty::InstanceDef::ClosureOnceShim { call_once: _ } => {
68 let fn_mut = tcx.lang_items().fn_mut_trait().unwrap();
70 .associated_items(fn_mut)
71 .find(|it| it.kind == ty::AssocKind::Method)
78 Some(Adjustment::RefMut),
79 CallKind::Direct(call_mut),
83 ty::InstanceDef::DropGlue(def_id, ty) => build_drop_shim(tcx, def_id, ty),
84 ty::InstanceDef::CloneShim(def_id, ty) => {
85 let name = tcx.item_name(def_id);
86 if name == sym::clone {
87 build_clone_shim(tcx, def_id, ty)
88 } else if name == sym::clone_from {
89 debug!("make_shim({:?}: using default trait implementation", instance);
90 return tcx.optimized_mir(def_id);
92 bug!("builtin clone shim {:?} not supported", instance)
95 ty::InstanceDef::Virtual(..) => {
96 bug!("InstanceDef::Virtual ({:?}) is for direct calls only", instance)
98 ty::InstanceDef::Intrinsic(_) => {
99 bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
102 debug!("make_shim({:?}) = untransformed {:?}", instance, result);
111 &add_moves_for_packed_drops::AddMovesForPackedDrops,
112 &no_landing_pads::NoLandingPads::new(tcx),
113 &remove_noop_landing_pads::RemoveNoopLandingPads,
114 &simplify::SimplifyCfg::new("make_shim"),
115 &add_call_guards::CriticalCallEdges,
119 debug!("make_shim({:?}) = {:?}", instance, result);
121 result.ensure_predecessors();
122 tcx.arena.alloc(result)
125 #[derive(Copy, Clone, Debug, PartialEq)]
133 #[derive(Copy, Clone, Debug, PartialEq)]
139 fn temp_decl(mutability: Mutability, ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
140 let source_info = SourceInfo { scope: OUTERMOST_SOURCE_SCOPE, span };
144 user_ty: UserTypeProjections::none(),
147 local_info: LocalInfo::Other,
152 fn local_decls_for_sig<'tcx>(
153 sig: &ty::FnSig<'tcx>,
155 ) -> IndexVec<Local, LocalDecl<'tcx>> {
156 iter::once(temp_decl(Mutability::Mut, sig.output(), span))
157 .chain(sig.inputs().iter().map(|ity| temp_decl(Mutability::Not, ity, span)))
161 fn build_drop_shim<'tcx>(
164 ty: Option<Ty<'tcx>>,
165 ) -> BodyAndCache<'tcx> {
166 debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
168 // Check if this is a generator, if so, return the drop glue for it
169 if let Some(&ty::TyS { kind: ty::Generator(gen_def_id, substs, _), .. }) = ty {
170 let body = &**tcx.optimized_mir(gen_def_id).generator_drop.as_ref().unwrap();
171 return body.subst(tcx, substs);
174 let substs = if let Some(ty) = ty {
175 tcx.intern_substs(&[ty.into()])
177 InternalSubsts::identity_for_item(tcx, def_id)
179 let sig = tcx.fn_sig(def_id).subst(tcx, substs);
180 let sig = tcx.erase_late_bound_regions(&sig);
181 let span = tcx.def_span(def_id);
183 let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
185 let return_block = BasicBlock::new(1);
186 let mut blocks = IndexVec::with_capacity(2);
187 let block = |blocks: &mut IndexVec<_, _>, kind| {
188 blocks.push(BasicBlockData {
190 terminator: Some(Terminator { source_info, kind }),
194 block(&mut blocks, TerminatorKind::Goto { target: return_block });
195 block(&mut blocks, TerminatorKind::Return);
197 let body = new_body(blocks, local_decls_for_sig(&sig, span), sig.inputs().len(), span);
199 let mut body = BodyAndCache::new(body);
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 {
289 if let DropFlagMode::Shallow = mode { DropStyle::Static } else { DropStyle::Open }
292 fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
296 fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {}
298 fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
301 fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
304 fn downcast_subpath(&self, _path: Self::Path, _variant: VariantIdx) -> Option<Self::Path> {
307 fn array_subpath(&self, _path: Self::Path, _index: u32, _size: u32) -> Option<Self::Path> {
312 /// Builds a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`.
313 fn build_clone_shim<'tcx>(
317 ) -> BodyAndCache<'tcx> {
318 debug!("build_clone_shim(def_id={:?})", def_id);
320 let param_env = tcx.param_env(def_id);
322 let mut builder = CloneShimBuilder::new(tcx, def_id, self_ty);
323 let is_copy = self_ty.is_copy_modulo_regions(tcx, param_env, builder.span);
325 let dest = Place::return_place();
326 let src = tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
329 _ if is_copy => builder.copy_shim(),
330 ty::Array(ty, len) => {
331 let len = len.eval_usize(tcx, param_env);
332 builder.array_shim(dest, src, ty, len)
334 ty::Closure(def_id, substs) => {
335 builder.tuple_like_shim(dest, src, substs.as_closure().upvar_tys(def_id, tcx))
337 ty::Tuple(..) => builder.tuple_like_shim(dest, src, self_ty.tuple_fields()),
338 _ => bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty),
341 BodyAndCache::new(builder.into_mir())
344 struct CloneShimBuilder<'tcx> {
347 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
348 blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
350 sig: ty::FnSig<'tcx>,
353 impl CloneShimBuilder<'tcx> {
354 fn new(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Self {
355 // we must subst the self_ty because it's
356 // otherwise going to be TySelf and we can't index
357 // or access fields of a Place of type TySelf.
358 let substs = tcx.mk_substs_trait(self_ty, &[]);
359 let sig = tcx.fn_sig(def_id).subst(tcx, substs);
360 let sig = tcx.erase_late_bound_regions(&sig);
361 let span = tcx.def_span(def_id);
366 local_decls: local_decls_for_sig(&sig, span),
367 blocks: IndexVec::new(),
373 fn into_mir(self) -> Body<'tcx> {
374 new_body(self.blocks, self.local_decls, self.sig.inputs().len(), self.span)
377 fn source_info(&self) -> SourceInfo {
378 SourceInfo { span: self.span, scope: OUTERMOST_SOURCE_SCOPE }
383 statements: Vec<Statement<'tcx>>,
384 kind: TerminatorKind<'tcx>,
387 let source_info = self.source_info();
388 self.blocks.push(BasicBlockData {
390 terminator: Some(Terminator { source_info, kind }),
395 /// Gives the index of an upcoming BasicBlock, with an offset.
396 /// offset=0 will give you the index of the next BasicBlock,
397 /// offset=1 will give the index of the next-to-next block,
398 /// offset=-1 will give you the index of the last-created block
399 fn block_index_offset(&mut self, offset: usize) -> BasicBlock {
400 BasicBlock::new(self.blocks.len() + offset)
403 fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
404 Statement { source_info: self.source_info(), kind }
407 fn copy_shim(&mut self) {
408 let rcvr = self.tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
409 let ret_statement = self.make_statement(StatementKind::Assign(box (
410 Place::return_place(),
411 Rvalue::Use(Operand::Copy(rcvr)),
413 self.block(vec![ret_statement], TerminatorKind::Return, false);
416 fn make_place(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Place<'tcx> {
417 let span = self.span;
418 Place::from(self.local_decls.push(temp_decl(mutability, ty, span)))
431 let substs = tcx.mk_substs_trait(ty, &[]);
433 // `func == Clone::clone(&ty) -> ty`
434 let func_ty = tcx.mk_fn_def(self.def_id, substs);
435 let func = Operand::Constant(box Constant {
438 literal: ty::Const::zero_sized(tcx, func_ty),
441 let ref_loc = self.make_place(
443 tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty, mutbl: hir::Mutability::Not }),
446 // `let ref_loc: &ty = &src;`
447 let statement = self.make_statement(StatementKind::Assign(box (
449 Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, src),
452 // `let loc = Clone::clone(ref_loc);`
455 TerminatorKind::Call {
457 args: vec![Operand::Move(ref_loc)],
458 destination: Some((dest, next)),
459 cleanup: Some(cleanup),
470 loop_body: BasicBlock,
471 loop_end: BasicBlock,
476 let cond = self.make_place(Mutability::Mut, tcx.types.bool);
477 let compute_cond = self.make_statement(StatementKind::Assign(box (
479 Rvalue::BinaryOp(BinOp::Ne, Operand::Copy(end), Operand::Copy(beg)),
482 // `if end != beg { goto loop_body; } else { goto loop_end; }`
485 TerminatorKind::if_(tcx, Operand::Move(cond), loop_body, loop_end),
490 fn make_usize(&self, value: u64) -> Box<Constant<'tcx>> {
494 literal: ty::Const::from_usize(self.tcx, value),
498 fn array_shim(&mut self, dest: Place<'tcx>, src: Place<'tcx>, ty: Ty<'tcx>, len: u64) {
500 let span = self.span;
502 let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
503 let end = self.make_place(Mutability::Not, tcx.types.usize);
506 // `let mut beg = 0;`
510 self.make_statement(StatementKind::Assign(box (
512 Rvalue::Use(Operand::Constant(self.make_usize(0))),
514 self.make_statement(StatementKind::Assign(box (
516 Rvalue::Use(Operand::Constant(self.make_usize(len))),
519 self.block(inits, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
526 self.loop_header(Place::from(beg), end, BasicBlock::new(2), BasicBlock::new(4), false);
529 // `dest[i] = Clone::clone(src[beg])`;
530 // Goto #3 if ok, #5 if unwinding happens.
531 let dest_field = self.tcx.mk_place_index(dest.clone(), beg);
532 let src_field = self.tcx.mk_place_index(src, beg);
533 self.make_clone_call(dest_field, src_field, ty, BasicBlock::new(3), BasicBlock::new(5));
538 let statements = vec![self.make_statement(StatementKind::Assign(box (
542 Operand::Copy(Place::from(beg)),
543 Operand::Constant(self.make_usize(1)),
546 self.block(statements, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
550 self.block(vec![], TerminatorKind::Return, false);
554 // `let mut beg = 0;`
557 let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
558 let init = self.make_statement(StatementKind::Assign(box (
560 Rvalue::Use(Operand::Constant(self.make_usize(0))),
562 self.block(vec![init], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
564 // BB #6 (cleanup): loop {
578 // `drop(dest[beg])`;
581 TerminatorKind::Drop {
582 location: self.tcx.mk_place_index(dest, beg),
583 target: BasicBlock::new(8),
592 let statement = self.make_statement(StatementKind::Assign(box (
596 Operand::Copy(Place::from(beg)),
597 Operand::Constant(self.make_usize(1)),
600 self.block(vec![statement], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
603 self.block(vec![], TerminatorKind::Resume, true);
606 fn tuple_like_shim<I>(&mut self, dest: Place<'tcx>, src: Place<'tcx>, tys: I)
608 I: Iterator<Item = Ty<'tcx>>,
610 let mut previous_field = None;
611 for (i, ity) in tys.enumerate() {
612 let field = Field::new(i);
613 let src_field = self.tcx.mk_place_field(src.clone(), field, ity);
615 let dest_field = self.tcx.mk_place_field(dest.clone(), field, ity);
617 // #(2i + 1) is the cleanup block for the previous clone operation
618 let cleanup_block = self.block_index_offset(1);
619 // #(2i + 2) is the next cloning block
620 // (or the Return terminator if this is the last block)
621 let next_block = self.block_index_offset(2);
624 // `dest.i = Clone::clone(&src.i);`
625 // Goto #(2i + 2) if ok, #(2i + 1) if unwinding happens.
626 self.make_clone_call(dest_field.clone(), src_field, ity, next_block, cleanup_block);
628 // BB #(2i + 1) (cleanup)
629 if let Some((previous_field, previous_cleanup)) = previous_field.take() {
630 // Drop previous field and goto previous cleanup block.
633 TerminatorKind::Drop {
634 location: previous_field,
635 target: previous_cleanup,
641 // Nothing to drop, just resume.
642 self.block(vec![], TerminatorKind::Resume, true);
645 previous_field = Some((dest_field, cleanup_block));
648 self.block(vec![], TerminatorKind::Return, false);
652 /// Builds a "call" shim for `instance`. The shim calls the
653 /// function specified by `call_kind`, first adjusting its first
654 /// argument according to `rcvr_adjustment`.
656 /// If `untuple_args` is a vec of types, the second argument of the
657 /// function will be untupled as these types.
658 fn build_call_shim<'tcx>(
660 instance: ty::InstanceDef<'tcx>,
661 rcvr_adjustment: Option<Adjustment>,
663 untuple_args: Option<&[Ty<'tcx>]>,
664 ) -> BodyAndCache<'tcx> {
666 "build_call_shim(instance={:?}, rcvr_adjustment={:?}, \
667 call_kind={:?}, untuple_args={:?})",
668 instance, rcvr_adjustment, call_kind, untuple_args
671 let def_id = instance.def_id();
672 let sig = tcx.fn_sig(def_id);
673 let mut sig = tcx.erase_late_bound_regions(&sig);
675 // FIXME(eddyb) avoid having this snippet both here and in
676 // `Instance::fn_sig` (introduce `InstanceDef::fn_sig`?).
677 if let ty::InstanceDef::VtableShim(..) = instance {
678 // Modify fn(self, ...) to fn(self: *mut Self, ...)
679 let mut inputs_and_output = sig.inputs_and_output.to_vec();
680 let self_arg = &mut inputs_and_output[0];
681 debug_assert!(tcx.generics_of(def_id).has_self && *self_arg == tcx.types.self_param);
682 *self_arg = tcx.mk_mut_ptr(*self_arg);
683 sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
686 let span = tcx.def_span(def_id);
688 debug!("build_call_shim: sig={:?}", sig);
690 let mut local_decls = local_decls_for_sig(&sig, span);
691 let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
693 let rcvr_place = || {
694 assert!(rcvr_adjustment.is_some());
695 Place::from(Local::new(1 + 0))
697 let mut statements = vec![];
699 let rcvr = rcvr_adjustment.map(|rcvr_adjustment| match rcvr_adjustment {
700 Adjustment::Identity => Operand::Move(rcvr_place()),
701 Adjustment::Deref => Operand::Copy(tcx.mk_place_deref(rcvr_place())),
702 Adjustment::DerefMove => Operand::Move(tcx.mk_place_deref(rcvr_place())),
703 Adjustment::RefMut => {
704 // let rcvr = &mut rcvr;
705 let ref_rcvr = local_decls.push(temp_decl(
708 tcx.lifetimes.re_erased,
709 ty::TypeAndMut { ty: sig.inputs()[0], mutbl: hir::Mutability::Mut },
713 let borrow_kind = BorrowKind::Mut { allow_two_phase_borrow: false };
714 statements.push(Statement {
716 kind: StatementKind::Assign(box (
717 Place::from(ref_rcvr),
718 Rvalue::Ref(tcx.lifetimes.re_erased, borrow_kind, rcvr_place()),
721 Operand::Move(Place::from(ref_rcvr))
725 let (callee, mut args) = match call_kind {
726 CallKind::Indirect => (rcvr.unwrap(), vec![]),
727 CallKind::Direct(def_id) => {
728 let ty = tcx.type_of(def_id);
730 Operand::Constant(box Constant {
733 literal: ty::Const::zero_sized(tcx, ty),
735 rcvr.into_iter().collect::<Vec<_>>(),
740 let mut arg_range = 0..sig.inputs().len();
742 // Take the `self` ("receiver") argument out of the range (it's adjusted above).
743 if rcvr_adjustment.is_some() {
744 arg_range.start += 1;
747 // Take the last argument, if we need to untuple it (handled below).
748 if untuple_args.is_some() {
752 // Pass all of the non-special arguments directly.
753 args.extend(arg_range.map(|i| Operand::Move(Place::from(Local::new(1 + i)))));
755 // Untuple the last argument, if we have to.
756 if let Some(untuple_args) = untuple_args {
757 let tuple_arg = Local::new(1 + (sig.inputs().len() - 1));
758 args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
759 Operand::Move(tcx.mk_place_field(Place::from(tuple_arg), Field::new(i), *ity))
763 let n_blocks = if let Some(Adjustment::RefMut) = rcvr_adjustment { 5 } else { 2 };
764 let mut blocks = IndexVec::with_capacity(n_blocks);
765 let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
766 blocks.push(BasicBlockData {
768 terminator: Some(Terminator { source_info, kind }),
777 TerminatorKind::Call {
780 destination: Some((Place::return_place(), BasicBlock::new(1))),
781 cleanup: if let Some(Adjustment::RefMut) = rcvr_adjustment {
782 Some(BasicBlock::new(3))
791 if let Some(Adjustment::RefMut) = rcvr_adjustment {
792 // BB #1 - drop for Self
796 TerminatorKind::Drop {
797 location: rcvr_place(),
798 target: BasicBlock::new(2),
805 block(&mut blocks, vec![], TerminatorKind::Return, false);
806 if let Some(Adjustment::RefMut) = rcvr_adjustment {
807 // BB #3 - drop if closure panics
811 TerminatorKind::Drop {
812 location: rcvr_place(),
813 target: BasicBlock::new(4),
820 block(&mut blocks, vec![], TerminatorKind::Resume, true);
823 let mut body = new_body(blocks, local_decls, sig.inputs().len(), span);
825 if let Abi::RustCall = sig.abi {
826 body.spread_arg = Some(Local::new(sig.inputs().len()));
828 BodyAndCache::new(body)
831 pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> &BodyAndCache<'_> {
832 debug_assert!(tcx.is_constructor(ctor_id));
835 tcx.hir().span_if_local(ctor_id).unwrap_or_else(|| bug!("no span for ctor {:?}", ctor_id));
837 let param_env = tcx.param_env(ctor_id);
839 // Normalize the sig.
840 let sig = tcx.fn_sig(ctor_id).no_bound_vars().expect("LBR in ADT constructor signature");
841 let sig = tcx.normalize_erasing_regions(param_env, sig);
843 let (adt_def, substs) = match sig.output().kind {
844 ty::Adt(adt_def, substs) => (adt_def, substs),
845 _ => bug!("unexpected type for ADT ctor {:?}", sig.output()),
848 debug!("build_ctor: ctor_id={:?} sig={:?}", ctor_id, sig);
850 let local_decls = local_decls_for_sig(&sig, span);
852 let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
854 let variant_index = if adt_def.is_enum() {
855 adt_def.variant_index_with_ctor_id(ctor_id)
860 // Generate the following MIR:
862 // (return as Variant).field0 = arg0;
863 // (return as Variant).field1 = arg1;
866 debug!("build_ctor: variant_index={:?}", variant_index);
868 let statements = expand_aggregate(
869 Place::return_place(),
870 adt_def.variants[variant_index].fields.iter().enumerate().map(|(idx, field_def)| {
871 (Operand::Move(Place::from(Local::new(idx + 1))), field_def.ty(tcx, substs))
873 AggregateKind::Adt(adt_def, variant_index, substs, None, None),
879 let start_block = BasicBlockData {
881 terminator: Some(Terminator { source_info, kind: TerminatorKind::Return }),
886 new_body(IndexVec::from_elem_n(start_block, 1), local_decls, sig.inputs().len(), span);
888 crate::util::dump_mir(
893 crate::transform::MirSource::item(ctor_id),
898 let mut body = BodyAndCache::new(body);
899 body.ensure_predecessors();
900 tcx.arena.alloc(body)