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.fn_trait_kind_from_lang_item(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 .in_definition_order()
72 .find(|it| it.kind == ty::AssocKind::Method)
79 Some(Adjustment::RefMut),
80 CallKind::Direct(call_mut),
84 ty::InstanceDef::DropGlue(def_id, ty) => build_drop_shim(tcx, def_id, ty),
85 ty::InstanceDef::CloneShim(def_id, ty) => {
86 let name = tcx.item_name(def_id);
87 if name == sym::clone {
88 build_clone_shim(tcx, def_id, ty)
89 } else if name == sym::clone_from {
90 debug!("make_shim({:?}: using default trait implementation", instance);
91 return tcx.optimized_mir(def_id);
93 bug!("builtin clone shim {:?} not supported", instance)
96 ty::InstanceDef::Virtual(..) => {
97 bug!("InstanceDef::Virtual ({:?}) is for direct calls only", instance)
99 ty::InstanceDef::Intrinsic(_) => {
100 bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
103 debug!("make_shim({:?}) = untransformed {:?}", instance, result);
112 &add_moves_for_packed_drops::AddMovesForPackedDrops,
113 &no_landing_pads::NoLandingPads::new(tcx),
114 &remove_noop_landing_pads::RemoveNoopLandingPads,
115 &simplify::SimplifyCfg::new("make_shim"),
116 &add_call_guards::CriticalCallEdges,
120 debug!("make_shim({:?}) = {:?}", instance, result);
122 result.ensure_predecessors();
123 tcx.arena.alloc(result)
126 #[derive(Copy, Clone, Debug, PartialEq)]
134 #[derive(Copy, Clone, Debug, PartialEq)]
140 fn temp_decl(mutability: Mutability, ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
141 let source_info = SourceInfo { scope: OUTERMOST_SOURCE_SCOPE, span };
145 user_ty: UserTypeProjections::none(),
148 local_info: LocalInfo::Other,
153 fn local_decls_for_sig<'tcx>(
154 sig: &ty::FnSig<'tcx>,
156 ) -> IndexVec<Local, LocalDecl<'tcx>> {
157 iter::once(temp_decl(Mutability::Mut, sig.output(), span))
158 .chain(sig.inputs().iter().map(|ity| temp_decl(Mutability::Not, ity, span)))
162 fn build_drop_shim<'tcx>(
165 ty: Option<Ty<'tcx>>,
166 ) -> BodyAndCache<'tcx> {
167 debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
169 // Check if this is a generator, if so, return the drop glue for it
170 if let Some(&ty::TyS { kind: ty::Generator(gen_def_id, substs, _), .. }) = ty {
171 let body = &**tcx.optimized_mir(gen_def_id).generator_drop.as_ref().unwrap();
172 return body.subst(tcx, substs);
175 let substs = if let Some(ty) = ty {
176 tcx.intern_substs(&[ty.into()])
178 InternalSubsts::identity_for_item(tcx, def_id)
180 let sig = tcx.fn_sig(def_id).subst(tcx, substs);
181 let sig = tcx.erase_late_bound_regions(&sig);
182 let span = tcx.def_span(def_id);
184 let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
186 let return_block = BasicBlock::new(1);
187 let mut blocks = IndexVec::with_capacity(2);
188 let block = |blocks: &mut IndexVec<_, _>, kind| {
189 blocks.push(BasicBlockData {
191 terminator: Some(Terminator { source_info, kind }),
195 block(&mut blocks, TerminatorKind::Goto { target: return_block });
196 block(&mut blocks, TerminatorKind::Return);
198 let body = new_body(blocks, local_decls_for_sig(&sig, span), sig.inputs().len(), span);
200 let mut body = BodyAndCache::new(body);
202 if let Some(..) = ty {
203 // The first argument (index 0), but add 1 for the return value.
204 let dropee_ptr = Place::from(Local::new(1 + 0));
205 if tcx.sess.opts.debugging_opts.mir_emit_retag {
206 // Function arguments should be retagged, and we make this one raw.
207 body.basic_blocks_mut()[START_BLOCK].statements.insert(
211 kind: StatementKind::Retag(RetagKind::Raw, box (dropee_ptr)),
216 let param_env = tcx.param_env(def_id).with_reveal_all();
218 DropShimElaborator { body: &body, patch: MirPatch::new(&body), tcx, param_env };
219 let dropee = tcx.mk_place_deref(dropee_ptr);
220 let resume_block = elaborator.patch.resume_block();
221 elaborate_drops::elaborate_drop(
227 elaborate_drops::Unwind::To(resume_block),
232 patch.apply(&mut body);
239 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
240 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
246 IndexVec::from_elem_n(
247 SourceScopeData { span, parent_scope: None, local_data: ClearCrossCrate::Clear },
260 pub struct DropShimElaborator<'a, 'tcx> {
261 pub body: &'a Body<'tcx>,
262 pub patch: MirPatch<'tcx>,
263 pub tcx: TyCtxt<'tcx>,
264 pub param_env: ty::ParamEnv<'tcx>,
267 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
268 fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
273 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
276 fn patch(&mut self) -> &mut MirPatch<'tcx> {
279 fn body(&self) -> &'a Body<'tcx> {
282 fn tcx(&self) -> TyCtxt<'tcx> {
285 fn param_env(&self) -> ty::ParamEnv<'tcx> {
289 fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
290 if let DropFlagMode::Shallow = mode { DropStyle::Static } else { DropStyle::Open }
293 fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
297 fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {}
299 fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
302 fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
305 fn downcast_subpath(&self, _path: Self::Path, _variant: VariantIdx) -> Option<Self::Path> {
308 fn array_subpath(&self, _path: Self::Path, _index: u32, _size: u32) -> Option<Self::Path> {
313 /// Builds a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`.
314 fn build_clone_shim<'tcx>(
318 ) -> BodyAndCache<'tcx> {
319 debug!("build_clone_shim(def_id={:?})", def_id);
321 let param_env = tcx.param_env(def_id);
323 let mut builder = CloneShimBuilder::new(tcx, def_id, self_ty);
324 let is_copy = self_ty.is_copy_modulo_regions(tcx, param_env, builder.span);
326 let dest = Place::return_place();
327 let src = tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
330 _ if is_copy => builder.copy_shim(),
331 ty::Array(ty, len) => {
332 let len = len.eval_usize(tcx, param_env);
333 builder.array_shim(dest, src, ty, len)
335 ty::Closure(def_id, substs) => {
336 builder.tuple_like_shim(dest, src, substs.as_closure().upvar_tys(def_id, tcx))
338 ty::Tuple(..) => builder.tuple_like_shim(dest, src, self_ty.tuple_fields()),
339 _ => bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty),
342 BodyAndCache::new(builder.into_mir())
345 struct CloneShimBuilder<'tcx> {
348 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
349 blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
351 sig: ty::FnSig<'tcx>,
354 impl CloneShimBuilder<'tcx> {
355 fn new(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Self {
356 // we must subst the self_ty because it's
357 // otherwise going to be TySelf and we can't index
358 // or access fields of a Place of type TySelf.
359 let substs = tcx.mk_substs_trait(self_ty, &[]);
360 let sig = tcx.fn_sig(def_id).subst(tcx, substs);
361 let sig = tcx.erase_late_bound_regions(&sig);
362 let span = tcx.def_span(def_id);
367 local_decls: local_decls_for_sig(&sig, span),
368 blocks: IndexVec::new(),
374 fn into_mir(self) -> Body<'tcx> {
375 new_body(self.blocks, self.local_decls, self.sig.inputs().len(), self.span)
378 fn source_info(&self) -> SourceInfo {
379 SourceInfo { span: self.span, scope: OUTERMOST_SOURCE_SCOPE }
384 statements: Vec<Statement<'tcx>>,
385 kind: TerminatorKind<'tcx>,
388 let source_info = self.source_info();
389 self.blocks.push(BasicBlockData {
391 terminator: Some(Terminator { source_info, kind }),
396 /// Gives the index of an upcoming BasicBlock, with an offset.
397 /// offset=0 will give you the index of the next BasicBlock,
398 /// offset=1 will give the index of the next-to-next block,
399 /// offset=-1 will give you the index of the last-created block
400 fn block_index_offset(&mut self, offset: usize) -> BasicBlock {
401 BasicBlock::new(self.blocks.len() + offset)
404 fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
405 Statement { source_info: self.source_info(), kind }
408 fn copy_shim(&mut self) {
409 let rcvr = self.tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
410 let ret_statement = self.make_statement(StatementKind::Assign(box (
411 Place::return_place(),
412 Rvalue::Use(Operand::Copy(rcvr)),
414 self.block(vec![ret_statement], TerminatorKind::Return, false);
417 fn make_place(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Place<'tcx> {
418 let span = self.span;
419 Place::from(self.local_decls.push(temp_decl(mutability, ty, span)))
432 let substs = tcx.mk_substs_trait(ty, &[]);
434 // `func == Clone::clone(&ty) -> ty`
435 let func_ty = tcx.mk_fn_def(self.def_id, substs);
436 let func = Operand::Constant(box Constant {
439 literal: ty::Const::zero_sized(tcx, func_ty),
442 let ref_loc = self.make_place(
444 tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty, mutbl: hir::Mutability::Not }),
447 // `let ref_loc: &ty = &src;`
448 let statement = self.make_statement(StatementKind::Assign(box (
450 Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, src),
453 // `let loc = Clone::clone(ref_loc);`
456 TerminatorKind::Call {
458 args: vec![Operand::Move(ref_loc)],
459 destination: Some((dest, next)),
460 cleanup: Some(cleanup),
471 loop_body: BasicBlock,
472 loop_end: BasicBlock,
477 let cond = self.make_place(Mutability::Mut, tcx.types.bool);
478 let compute_cond = self.make_statement(StatementKind::Assign(box (
480 Rvalue::BinaryOp(BinOp::Ne, Operand::Copy(end), Operand::Copy(beg)),
483 // `if end != beg { goto loop_body; } else { goto loop_end; }`
486 TerminatorKind::if_(tcx, Operand::Move(cond), loop_body, loop_end),
491 fn make_usize(&self, value: u64) -> Box<Constant<'tcx>> {
495 literal: ty::Const::from_usize(self.tcx, value),
499 fn array_shim(&mut self, dest: Place<'tcx>, src: Place<'tcx>, ty: Ty<'tcx>, len: u64) {
501 let span = self.span;
503 let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
504 let end = self.make_place(Mutability::Not, tcx.types.usize);
507 // `let mut beg = 0;`
511 self.make_statement(StatementKind::Assign(box (
513 Rvalue::Use(Operand::Constant(self.make_usize(0))),
515 self.make_statement(StatementKind::Assign(box (
517 Rvalue::Use(Operand::Constant(self.make_usize(len))),
520 self.block(inits, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
527 self.loop_header(Place::from(beg), end, BasicBlock::new(2), BasicBlock::new(4), false);
530 // `dest[i] = Clone::clone(src[beg])`;
531 // Goto #3 if ok, #5 if unwinding happens.
532 let dest_field = self.tcx.mk_place_index(dest.clone(), beg);
533 let src_field = self.tcx.mk_place_index(src, beg);
534 self.make_clone_call(dest_field, src_field, ty, BasicBlock::new(3), BasicBlock::new(5));
539 let statements = vec![self.make_statement(StatementKind::Assign(box (
543 Operand::Copy(Place::from(beg)),
544 Operand::Constant(self.make_usize(1)),
547 self.block(statements, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
551 self.block(vec![], TerminatorKind::Return, false);
555 // `let mut beg = 0;`
558 let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
559 let init = self.make_statement(StatementKind::Assign(box (
561 Rvalue::Use(Operand::Constant(self.make_usize(0))),
563 self.block(vec![init], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
565 // BB #6 (cleanup): loop {
579 // `drop(dest[beg])`;
582 TerminatorKind::Drop {
583 location: self.tcx.mk_place_index(dest, beg),
584 target: BasicBlock::new(8),
593 let statement = self.make_statement(StatementKind::Assign(box (
597 Operand::Copy(Place::from(beg)),
598 Operand::Constant(self.make_usize(1)),
601 self.block(vec![statement], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
604 self.block(vec![], TerminatorKind::Resume, true);
607 fn tuple_like_shim<I>(&mut self, dest: Place<'tcx>, src: Place<'tcx>, tys: I)
609 I: Iterator<Item = Ty<'tcx>>,
611 let mut previous_field = None;
612 for (i, ity) in tys.enumerate() {
613 let field = Field::new(i);
614 let src_field = self.tcx.mk_place_field(src.clone(), field, ity);
616 let dest_field = self.tcx.mk_place_field(dest.clone(), field, ity);
618 // #(2i + 1) is the cleanup block for the previous clone operation
619 let cleanup_block = self.block_index_offset(1);
620 // #(2i + 2) is the next cloning block
621 // (or the Return terminator if this is the last block)
622 let next_block = self.block_index_offset(2);
625 // `dest.i = Clone::clone(&src.i);`
626 // Goto #(2i + 2) if ok, #(2i + 1) if unwinding happens.
627 self.make_clone_call(dest_field.clone(), src_field, ity, next_block, cleanup_block);
629 // BB #(2i + 1) (cleanup)
630 if let Some((previous_field, previous_cleanup)) = previous_field.take() {
631 // Drop previous field and goto previous cleanup block.
634 TerminatorKind::Drop {
635 location: previous_field,
636 target: previous_cleanup,
642 // Nothing to drop, just resume.
643 self.block(vec![], TerminatorKind::Resume, true);
646 previous_field = Some((dest_field, cleanup_block));
649 self.block(vec![], TerminatorKind::Return, false);
653 /// Builds a "call" shim for `instance`. The shim calls the
654 /// function specified by `call_kind`, first adjusting its first
655 /// argument according to `rcvr_adjustment`.
657 /// If `untuple_args` is a vec of types, the second argument of the
658 /// function will be untupled as these types.
659 fn build_call_shim<'tcx>(
661 instance: ty::InstanceDef<'tcx>,
662 rcvr_adjustment: Option<Adjustment>,
664 untuple_args: Option<&[Ty<'tcx>]>,
665 ) -> BodyAndCache<'tcx> {
667 "build_call_shim(instance={:?}, rcvr_adjustment={:?}, \
668 call_kind={:?}, untuple_args={:?})",
669 instance, rcvr_adjustment, call_kind, untuple_args
672 let def_id = instance.def_id();
673 let sig = tcx.fn_sig(def_id);
674 let mut sig = tcx.erase_late_bound_regions(&sig);
676 // FIXME(eddyb) avoid having this snippet both here and in
677 // `Instance::fn_sig` (introduce `InstanceDef::fn_sig`?).
678 if let ty::InstanceDef::VtableShim(..) = instance {
679 // Modify fn(self, ...) to fn(self: *mut Self, ...)
680 let mut inputs_and_output = sig.inputs_and_output.to_vec();
681 let self_arg = &mut inputs_and_output[0];
682 debug_assert!(tcx.generics_of(def_id).has_self && *self_arg == tcx.types.self_param);
683 *self_arg = tcx.mk_mut_ptr(*self_arg);
684 sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
687 let span = tcx.def_span(def_id);
689 debug!("build_call_shim: sig={:?}", sig);
691 let mut local_decls = local_decls_for_sig(&sig, span);
692 let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
694 let rcvr_place = || {
695 assert!(rcvr_adjustment.is_some());
696 Place::from(Local::new(1 + 0))
698 let mut statements = vec![];
700 let rcvr = rcvr_adjustment.map(|rcvr_adjustment| match rcvr_adjustment {
701 Adjustment::Identity => Operand::Move(rcvr_place()),
702 Adjustment::Deref => Operand::Copy(tcx.mk_place_deref(rcvr_place())),
703 Adjustment::DerefMove => Operand::Move(tcx.mk_place_deref(rcvr_place())),
704 Adjustment::RefMut => {
705 // let rcvr = &mut rcvr;
706 let ref_rcvr = local_decls.push(temp_decl(
709 tcx.lifetimes.re_erased,
710 ty::TypeAndMut { ty: sig.inputs()[0], mutbl: hir::Mutability::Mut },
714 let borrow_kind = BorrowKind::Mut { allow_two_phase_borrow: false };
715 statements.push(Statement {
717 kind: StatementKind::Assign(box (
718 Place::from(ref_rcvr),
719 Rvalue::Ref(tcx.lifetimes.re_erased, borrow_kind, rcvr_place()),
722 Operand::Move(Place::from(ref_rcvr))
726 let (callee, mut args) = match call_kind {
727 CallKind::Indirect => (rcvr.unwrap(), vec![]),
728 CallKind::Direct(def_id) => {
729 let ty = tcx.type_of(def_id);
731 Operand::Constant(box Constant {
734 literal: ty::Const::zero_sized(tcx, ty),
736 rcvr.into_iter().collect::<Vec<_>>(),
741 let mut arg_range = 0..sig.inputs().len();
743 // Take the `self` ("receiver") argument out of the range (it's adjusted above).
744 if rcvr_adjustment.is_some() {
745 arg_range.start += 1;
748 // Take the last argument, if we need to untuple it (handled below).
749 if untuple_args.is_some() {
753 // Pass all of the non-special arguments directly.
754 args.extend(arg_range.map(|i| Operand::Move(Place::from(Local::new(1 + i)))));
756 // Untuple the last argument, if we have to.
757 if let Some(untuple_args) = untuple_args {
758 let tuple_arg = Local::new(1 + (sig.inputs().len() - 1));
759 args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
760 Operand::Move(tcx.mk_place_field(Place::from(tuple_arg), Field::new(i), *ity))
764 let n_blocks = if let Some(Adjustment::RefMut) = rcvr_adjustment { 5 } else { 2 };
765 let mut blocks = IndexVec::with_capacity(n_blocks);
766 let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
767 blocks.push(BasicBlockData {
769 terminator: Some(Terminator { source_info, kind }),
778 TerminatorKind::Call {
781 destination: Some((Place::return_place(), BasicBlock::new(1))),
782 cleanup: if let Some(Adjustment::RefMut) = rcvr_adjustment {
783 Some(BasicBlock::new(3))
792 if let Some(Adjustment::RefMut) = rcvr_adjustment {
793 // BB #1 - drop for Self
797 TerminatorKind::Drop {
798 location: rcvr_place(),
799 target: BasicBlock::new(2),
806 block(&mut blocks, vec![], TerminatorKind::Return, false);
807 if let Some(Adjustment::RefMut) = rcvr_adjustment {
808 // BB #3 - drop if closure panics
812 TerminatorKind::Drop {
813 location: rcvr_place(),
814 target: BasicBlock::new(4),
821 block(&mut blocks, vec![], TerminatorKind::Resume, true);
824 let mut body = new_body(blocks, local_decls, sig.inputs().len(), span);
826 if let Abi::RustCall = sig.abi {
827 body.spread_arg = Some(Local::new(sig.inputs().len()));
829 BodyAndCache::new(body)
832 pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> &BodyAndCache<'_> {
833 debug_assert!(tcx.is_constructor(ctor_id));
836 tcx.hir().span_if_local(ctor_id).unwrap_or_else(|| bug!("no span for ctor {:?}", ctor_id));
838 let param_env = tcx.param_env(ctor_id);
840 // Normalize the sig.
841 let sig = tcx.fn_sig(ctor_id).no_bound_vars().expect("LBR in ADT constructor signature");
842 let sig = tcx.normalize_erasing_regions(param_env, sig);
844 let (adt_def, substs) = match sig.output().kind {
845 ty::Adt(adt_def, substs) => (adt_def, substs),
846 _ => bug!("unexpected type for ADT ctor {:?}", sig.output()),
849 debug!("build_ctor: ctor_id={:?} sig={:?}", ctor_id, sig);
851 let local_decls = local_decls_for_sig(&sig, span);
853 let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
855 let variant_index = if adt_def.is_enum() {
856 adt_def.variant_index_with_ctor_id(ctor_id)
861 // Generate the following MIR:
863 // (return as Variant).field0 = arg0;
864 // (return as Variant).field1 = arg1;
867 debug!("build_ctor: variant_index={:?}", variant_index);
869 let statements = expand_aggregate(
870 Place::return_place(),
871 adt_def.variants[variant_index].fields.iter().enumerate().map(|(idx, field_def)| {
872 (Operand::Move(Place::from(Local::new(idx + 1))), field_def.ty(tcx, substs))
874 AggregateKind::Adt(adt_def, variant_index, substs, None, None),
880 let start_block = BasicBlockData {
882 terminator: Some(Terminator { source_info, kind: TerminatorKind::Return }),
887 new_body(IndexVec::from_elem_n(start_block, 1), local_decls, sig.inputs().len(), span);
889 crate::util::dump_mir(
894 crate::transform::MirSource::item(ctor_id),
899 let mut body = BodyAndCache::new(body);
900 body.ensure_predecessors();
901 tcx.arena.alloc(body)