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) => {
35 build_call_shim(tcx, instance, Adjustment::DerefMove, CallKind::Direct(def_id), None)
37 ty::InstanceDef::FnPtrShim(def_id, ty) => {
38 let trait_ = tcx.trait_of_item(def_id).unwrap();
39 let adjustment = match tcx.lang_items().fn_trait_kind(trait_) {
40 Some(ty::ClosureKind::FnOnce) => Adjustment::Identity,
41 Some(ty::ClosureKind::FnMut) | Some(ty::ClosureKind::Fn) => Adjustment::Deref,
42 None => bug!("fn pointer {:?} is not an fn", ty),
44 // HACK: we need the "real" argument types for the MIR,
45 // but because our substs are (Self, Args), where Args
46 // is a tuple, we must include the *concrete* argument
47 // types in the MIR. They will be substituted again with
48 // the param-substs, but because they are concrete, this
49 // will not do any harm.
50 let sig = tcx.erase_late_bound_regions(&ty.fn_sig(tcx));
51 let arg_tys = sig.inputs();
53 build_call_shim(tcx, instance, adjustment, CallKind::Indirect, Some(arg_tys))
55 // We are generating a call back to our def-id, which the
56 // codegen backend knows to turn to an actual call, be it
57 // a virtual call, or a direct call to a function for which
58 // indirect calls must be codegen'd differently than direct ones
59 // (such as `#[track_caller]`).
60 ty::InstanceDef::ReifyShim(def_id) => {
61 build_call_shim(tcx, instance, Adjustment::Identity, CallKind::Direct(def_id), None)
63 ty::InstanceDef::ClosureOnceShim { call_once: _ } => {
64 let fn_mut = tcx.lang_items().fn_mut_trait().unwrap();
66 .associated_items(fn_mut)
67 .find(|it| it.kind == ty::AssocKind::Method)
71 build_call_shim(tcx, instance, Adjustment::RefMut, CallKind::Direct(call_mut), None)
73 ty::InstanceDef::DropGlue(def_id, ty) => build_drop_shim(tcx, def_id, ty),
74 ty::InstanceDef::CloneShim(def_id, ty) => {
75 let name = tcx.item_name(def_id);
76 if name == sym::clone {
77 build_clone_shim(tcx, def_id, ty)
78 } else if name == sym::clone_from {
79 debug!("make_shim({:?}: using default trait implementation", instance);
80 return tcx.optimized_mir(def_id);
82 bug!("builtin clone shim {:?} not supported", instance)
85 ty::InstanceDef::Virtual(..) => {
86 bug!("InstanceDef::Virtual ({:?}) is for direct calls only", instance)
88 ty::InstanceDef::Intrinsic(_) => {
89 bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
92 debug!("make_shim({:?}) = untransformed {:?}", instance, result);
101 &add_moves_for_packed_drops::AddMovesForPackedDrops,
102 &no_landing_pads::NoLandingPads::new(tcx),
103 &remove_noop_landing_pads::RemoveNoopLandingPads,
104 &simplify::SimplifyCfg::new("make_shim"),
105 &add_call_guards::CriticalCallEdges,
109 debug!("make_shim({:?}) = {:?}", instance, result);
111 result.ensure_predecessors();
112 tcx.arena.alloc(result)
115 #[derive(Copy, Clone, Debug, PartialEq)]
123 #[derive(Copy, Clone, Debug, PartialEq)]
129 fn temp_decl(mutability: Mutability, ty: Ty<'_>, span: Span) -> LocalDecl<'_> {
130 let source_info = SourceInfo { scope: OUTERMOST_SOURCE_SCOPE, span };
134 user_ty: UserTypeProjections::none(),
137 local_info: LocalInfo::Other,
142 fn local_decls_for_sig<'tcx>(
143 sig: &ty::FnSig<'tcx>,
145 ) -> IndexVec<Local, LocalDecl<'tcx>> {
146 iter::once(temp_decl(Mutability::Mut, sig.output(), span))
147 .chain(sig.inputs().iter().map(|ity| temp_decl(Mutability::Not, ity, span)))
151 fn build_drop_shim<'tcx>(
154 ty: Option<Ty<'tcx>>,
155 ) -> BodyAndCache<'tcx> {
156 debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
158 // Check if this is a generator, if so, return the drop glue for it
159 if let Some(&ty::TyS { kind: ty::Generator(gen_def_id, substs, _), .. }) = ty {
160 let body = &**tcx.optimized_mir(gen_def_id).generator_drop.as_ref().unwrap();
161 return body.subst(tcx, substs);
164 let substs = if let Some(ty) = ty {
165 tcx.intern_substs(&[ty.into()])
167 InternalSubsts::identity_for_item(tcx, def_id)
169 let sig = tcx.fn_sig(def_id).subst(tcx, substs);
170 let sig = tcx.erase_late_bound_regions(&sig);
171 let span = tcx.def_span(def_id);
173 let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
175 let return_block = BasicBlock::new(1);
176 let mut blocks = IndexVec::with_capacity(2);
177 let block = |blocks: &mut IndexVec<_, _>, kind| {
178 blocks.push(BasicBlockData {
180 terminator: Some(Terminator { source_info, kind }),
184 block(&mut blocks, TerminatorKind::Goto { target: return_block });
185 block(&mut blocks, TerminatorKind::Return);
187 let body = new_body(blocks, local_decls_for_sig(&sig, span), sig.inputs().len(), span);
189 let mut body = BodyAndCache::new(body);
191 if let Some(..) = ty {
192 // The first argument (index 0), but add 1 for the return value.
193 let dropee_ptr = Place::from(Local::new(1 + 0));
194 if tcx.sess.opts.debugging_opts.mir_emit_retag {
195 // Function arguments should be retagged, and we make this one raw.
196 body.basic_blocks_mut()[START_BLOCK].statements.insert(
200 kind: StatementKind::Retag(RetagKind::Raw, box (dropee_ptr.clone())),
205 let param_env = tcx.param_env(def_id).with_reveal_all();
207 DropShimElaborator { body: &body, patch: MirPatch::new(&body), tcx, param_env };
208 let dropee = tcx.mk_place_deref(dropee_ptr);
209 let resume_block = elaborator.patch.resume_block();
210 elaborate_drops::elaborate_drop(
216 elaborate_drops::Unwind::To(resume_block),
221 patch.apply(&mut body);
228 basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
229 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
235 IndexVec::from_elem_n(
236 SourceScopeData { span, parent_scope: None, local_data: ClearCrossCrate::Clear },
249 pub struct DropShimElaborator<'a, 'tcx> {
250 pub body: &'a Body<'tcx>,
251 pub patch: MirPatch<'tcx>,
252 pub tcx: TyCtxt<'tcx>,
253 pub param_env: ty::ParamEnv<'tcx>,
256 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
257 fn fmt(&self, _f: &mut fmt::Formatter<'_>) -> Result<(), fmt::Error> {
262 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
265 fn patch(&mut self) -> &mut MirPatch<'tcx> {
268 fn body(&self) -> &'a Body<'tcx> {
271 fn tcx(&self) -> TyCtxt<'tcx> {
274 fn param_env(&self) -> ty::ParamEnv<'tcx> {
278 fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
279 if let DropFlagMode::Shallow = mode { DropStyle::Static } else { DropStyle::Open }
282 fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
286 fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {}
288 fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
291 fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
294 fn downcast_subpath(&self, _path: Self::Path, _variant: VariantIdx) -> Option<Self::Path> {
297 fn array_subpath(&self, _path: Self::Path, _index: u32, _size: u32) -> Option<Self::Path> {
302 /// Builds a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`.
303 fn build_clone_shim<'tcx>(
307 ) -> BodyAndCache<'tcx> {
308 debug!("build_clone_shim(def_id={:?})", def_id);
310 let param_env = tcx.param_env(def_id);
312 let mut builder = CloneShimBuilder::new(tcx, def_id, self_ty);
313 let is_copy = self_ty.is_copy_modulo_regions(tcx, param_env, builder.span);
315 let dest = Place::return_place();
316 let src = tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
319 _ if is_copy => builder.copy_shim(),
320 ty::Array(ty, len) => {
321 let len = len.eval_usize(tcx, param_env);
322 builder.array_shim(dest, src, ty, len)
324 ty::Closure(def_id, substs) => {
325 builder.tuple_like_shim(dest, src, substs.as_closure().upvar_tys(def_id, tcx))
327 ty::Tuple(..) => builder.tuple_like_shim(dest, src, self_ty.tuple_fields()),
328 _ => bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty),
331 BodyAndCache::new(builder.into_mir())
334 struct CloneShimBuilder<'tcx> {
337 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
338 blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
340 sig: ty::FnSig<'tcx>,
343 impl CloneShimBuilder<'tcx> {
344 fn new(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Self {
345 // we must subst the self_ty because it's
346 // otherwise going to be TySelf and we can't index
347 // or access fields of a Place of type TySelf.
348 let substs = tcx.mk_substs_trait(self_ty, &[]);
349 let sig = tcx.fn_sig(def_id).subst(tcx, substs);
350 let sig = tcx.erase_late_bound_regions(&sig);
351 let span = tcx.def_span(def_id);
356 local_decls: local_decls_for_sig(&sig, span),
357 blocks: IndexVec::new(),
363 fn into_mir(self) -> Body<'tcx> {
364 new_body(self.blocks, self.local_decls, self.sig.inputs().len(), self.span)
367 fn source_info(&self) -> SourceInfo {
368 SourceInfo { span: self.span, scope: OUTERMOST_SOURCE_SCOPE }
373 statements: Vec<Statement<'tcx>>,
374 kind: TerminatorKind<'tcx>,
377 let source_info = self.source_info();
378 self.blocks.push(BasicBlockData {
380 terminator: Some(Terminator { source_info, kind }),
385 /// Gives the index of an upcoming BasicBlock, with an offset.
386 /// offset=0 will give you the index of the next BasicBlock,
387 /// offset=1 will give the index of the next-to-next block,
388 /// offset=-1 will give you the index of the last-created block
389 fn block_index_offset(&mut self, offset: usize) -> BasicBlock {
390 BasicBlock::new(self.blocks.len() + offset)
393 fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
394 Statement { source_info: self.source_info(), kind }
397 fn copy_shim(&mut self) {
398 let rcvr = self.tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
399 let ret_statement = self.make_statement(StatementKind::Assign(box (
400 Place::return_place(),
401 Rvalue::Use(Operand::Copy(rcvr)),
403 self.block(vec![ret_statement], TerminatorKind::Return, false);
406 fn make_place(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Place<'tcx> {
407 let span = self.span;
408 Place::from(self.local_decls.push(temp_decl(mutability, ty, span)))
421 let substs = tcx.mk_substs_trait(ty, &[]);
423 // `func == Clone::clone(&ty) -> ty`
424 let func_ty = tcx.mk_fn_def(self.def_id, substs);
425 let func = Operand::Constant(box Constant {
428 literal: ty::Const::zero_sized(tcx, func_ty),
431 let ref_loc = self.make_place(
433 tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty, mutbl: hir::Mutability::Not }),
436 // `let ref_loc: &ty = &src;`
437 let statement = self.make_statement(StatementKind::Assign(box (
439 Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, src),
442 // `let loc = Clone::clone(ref_loc);`
445 TerminatorKind::Call {
447 args: vec![Operand::Move(ref_loc)],
448 destination: Some((dest, next)),
449 cleanup: Some(cleanup),
460 loop_body: BasicBlock,
461 loop_end: BasicBlock,
466 let cond = self.make_place(Mutability::Mut, tcx.types.bool);
467 let compute_cond = self.make_statement(StatementKind::Assign(box (
469 Rvalue::BinaryOp(BinOp::Ne, Operand::Copy(end), Operand::Copy(beg)),
472 // `if end != beg { goto loop_body; } else { goto loop_end; }`
475 TerminatorKind::if_(tcx, Operand::Move(cond), loop_body, loop_end),
480 fn make_usize(&self, value: u64) -> Box<Constant<'tcx>> {
484 literal: ty::Const::from_usize(self.tcx, value),
488 fn array_shim(&mut self, dest: Place<'tcx>, src: Place<'tcx>, ty: Ty<'tcx>, len: u64) {
490 let span = self.span;
492 let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
493 let end = self.make_place(Mutability::Not, tcx.types.usize);
496 // `let mut beg = 0;`
500 self.make_statement(StatementKind::Assign(box (
502 Rvalue::Use(Operand::Constant(self.make_usize(0))),
504 self.make_statement(StatementKind::Assign(box (
506 Rvalue::Use(Operand::Constant(self.make_usize(len))),
509 self.block(inits, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
516 self.loop_header(Place::from(beg), end, BasicBlock::new(2), BasicBlock::new(4), false);
519 // `dest[i] = Clone::clone(src[beg])`;
520 // Goto #3 if ok, #5 if unwinding happens.
521 let dest_field = self.tcx.mk_place_index(dest.clone(), beg);
522 let src_field = self.tcx.mk_place_index(src, beg);
523 self.make_clone_call(dest_field, src_field, ty, BasicBlock::new(3), BasicBlock::new(5));
528 let statements = vec![self.make_statement(StatementKind::Assign(box (
532 Operand::Copy(Place::from(beg)),
533 Operand::Constant(self.make_usize(1)),
536 self.block(statements, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
540 self.block(vec![], TerminatorKind::Return, false);
544 // `let mut beg = 0;`
547 let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
548 let init = self.make_statement(StatementKind::Assign(box (
550 Rvalue::Use(Operand::Constant(self.make_usize(0))),
552 self.block(vec![init], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
554 // BB #6 (cleanup): loop {
568 // `drop(dest[beg])`;
571 TerminatorKind::Drop {
572 location: self.tcx.mk_place_index(dest, beg),
573 target: BasicBlock::new(8),
582 let statement = self.make_statement(StatementKind::Assign(box (
586 Operand::Copy(Place::from(beg)),
587 Operand::Constant(self.make_usize(1)),
590 self.block(vec![statement], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
593 self.block(vec![], TerminatorKind::Resume, true);
596 fn tuple_like_shim<I>(&mut self, dest: Place<'tcx>, src: Place<'tcx>, tys: I)
598 I: Iterator<Item = Ty<'tcx>>,
600 let mut previous_field = None;
601 for (i, ity) in tys.enumerate() {
602 let field = Field::new(i);
603 let src_field = self.tcx.mk_place_field(src.clone(), field, ity);
605 let dest_field = self.tcx.mk_place_field(dest.clone(), field, ity);
607 // #(2i + 1) is the cleanup block for the previous clone operation
608 let cleanup_block = self.block_index_offset(1);
609 // #(2i + 2) is the next cloning block
610 // (or the Return terminator if this is the last block)
611 let next_block = self.block_index_offset(2);
614 // `dest.i = Clone::clone(&src.i);`
615 // Goto #(2i + 2) if ok, #(2i + 1) if unwinding happens.
616 self.make_clone_call(dest_field.clone(), src_field, ity, next_block, cleanup_block);
618 // BB #(2i + 1) (cleanup)
619 if let Some((previous_field, previous_cleanup)) = previous_field.take() {
620 // Drop previous field and goto previous cleanup block.
623 TerminatorKind::Drop {
624 location: previous_field,
625 target: previous_cleanup,
631 // Nothing to drop, just resume.
632 self.block(vec![], TerminatorKind::Resume, true);
635 previous_field = Some((dest_field, cleanup_block));
638 self.block(vec![], TerminatorKind::Return, false);
642 /// Builds a "call" shim for `instance`. The shim calls the
643 /// function specified by `call_kind`, first adjusting its first
644 /// argument according to `rcvr_adjustment`.
646 /// If `untuple_args` is a vec of types, the second argument of the
647 /// function will be untupled as these types.
648 fn build_call_shim<'tcx>(
650 instance: ty::InstanceDef<'tcx>,
651 rcvr_adjustment: Adjustment,
653 untuple_args: Option<&[Ty<'tcx>]>,
654 ) -> BodyAndCache<'tcx> {
656 "build_call_shim(instance={:?}, rcvr_adjustment={:?}, \
657 call_kind={:?}, untuple_args={:?})",
658 instance, rcvr_adjustment, call_kind, untuple_args
661 let def_id = instance.def_id();
662 let sig = tcx.fn_sig(def_id);
663 let mut sig = tcx.erase_late_bound_regions(&sig);
665 // FIXME(eddyb) avoid having this snippet both here and in
666 // `Instance::fn_sig` (introduce `InstanceDef::fn_sig`?).
667 if let ty::InstanceDef::VtableShim(..) = instance {
668 // Modify fn(self, ...) to fn(self: *mut Self, ...)
669 let mut inputs_and_output = sig.inputs_and_output.to_vec();
670 let self_arg = &mut inputs_and_output[0];
671 debug_assert!(tcx.generics_of(def_id).has_self && *self_arg == tcx.types.self_param);
672 *self_arg = tcx.mk_mut_ptr(*self_arg);
673 sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
676 let span = tcx.def_span(def_id);
678 debug!("build_call_shim: sig={:?}", sig);
680 let mut local_decls = local_decls_for_sig(&sig, span);
681 let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
683 let rcvr_arg = Local::new(1 + 0);
684 let rcvr_l = Place::from(rcvr_arg);
685 let mut statements = vec![];
687 let rcvr = match rcvr_adjustment {
688 Adjustment::Identity => Operand::Move(rcvr_l),
689 Adjustment::Deref => Operand::Copy(tcx.mk_place_deref(rcvr_l)),
690 Adjustment::DerefMove => Operand::Move(tcx.mk_place_deref(rcvr_l)),
691 Adjustment::RefMut => {
692 // let rcvr = &mut rcvr;
693 let ref_rcvr = local_decls.push(temp_decl(
696 tcx.lifetimes.re_erased,
697 ty::TypeAndMut { ty: sig.inputs()[0], mutbl: hir::Mutability::Mut },
701 let borrow_kind = BorrowKind::Mut { allow_two_phase_borrow: false };
702 statements.push(Statement {
704 kind: StatementKind::Assign(box (
705 Place::from(ref_rcvr),
706 Rvalue::Ref(tcx.lifetimes.re_erased, borrow_kind, rcvr_l),
709 Operand::Move(Place::from(ref_rcvr))
713 let (callee, mut args) = match call_kind {
714 CallKind::Indirect => (rcvr, vec![]),
715 CallKind::Direct(def_id) => {
716 let ty = tcx.type_of(def_id);
718 Operand::Constant(box Constant {
721 literal: ty::Const::zero_sized(tcx, ty),
728 if let Some(untuple_args) = untuple_args {
729 args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
730 let arg_place = Place::from(Local::new(1 + 1));
731 Operand::Move(tcx.mk_place_field(arg_place, Field::new(i), *ity))
734 args.extend((1..sig.inputs().len()).map(|i| Operand::Move(Place::from(Local::new(1 + i)))));
737 let n_blocks = if let Adjustment::RefMut = rcvr_adjustment { 5 } else { 2 };
738 let mut blocks = IndexVec::with_capacity(n_blocks);
739 let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
740 blocks.push(BasicBlockData {
742 terminator: Some(Terminator { source_info, kind }),
751 TerminatorKind::Call {
754 destination: Some((Place::return_place(), BasicBlock::new(1))),
755 cleanup: if let Adjustment::RefMut = rcvr_adjustment {
756 Some(BasicBlock::new(3))
765 if let Adjustment::RefMut = rcvr_adjustment {
766 // BB #1 - drop for Self
770 TerminatorKind::Drop {
771 location: Place::from(rcvr_arg),
772 target: BasicBlock::new(2),
779 block(&mut blocks, vec![], TerminatorKind::Return, false);
780 if let Adjustment::RefMut = rcvr_adjustment {
781 // BB #3 - drop if closure panics
785 TerminatorKind::Drop {
786 location: Place::from(rcvr_arg),
787 target: BasicBlock::new(4),
794 block(&mut blocks, vec![], TerminatorKind::Resume, true);
797 let mut body = new_body(blocks, local_decls, sig.inputs().len(), span);
799 if let Abi::RustCall = sig.abi {
800 body.spread_arg = Some(Local::new(sig.inputs().len()));
802 BodyAndCache::new(body)
805 pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> &BodyAndCache<'_> {
806 debug_assert!(tcx.is_constructor(ctor_id));
809 tcx.hir().span_if_local(ctor_id).unwrap_or_else(|| bug!("no span for ctor {:?}", ctor_id));
811 let param_env = tcx.param_env(ctor_id);
813 // Normalize the sig.
814 let sig = tcx.fn_sig(ctor_id).no_bound_vars().expect("LBR in ADT constructor signature");
815 let sig = tcx.normalize_erasing_regions(param_env, sig);
817 let (adt_def, substs) = match sig.output().kind {
818 ty::Adt(adt_def, substs) => (adt_def, substs),
819 _ => bug!("unexpected type for ADT ctor {:?}", sig.output()),
822 debug!("build_ctor: ctor_id={:?} sig={:?}", ctor_id, sig);
824 let local_decls = local_decls_for_sig(&sig, span);
826 let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
828 let variant_index = if adt_def.is_enum() {
829 adt_def.variant_index_with_ctor_id(ctor_id)
834 // Generate the following MIR:
836 // (return as Variant).field0 = arg0;
837 // (return as Variant).field1 = arg1;
840 debug!("build_ctor: variant_index={:?}", variant_index);
842 let statements = expand_aggregate(
843 Place::return_place(),
844 adt_def.variants[variant_index].fields.iter().enumerate().map(|(idx, field_def)| {
845 (Operand::Move(Place::from(Local::new(idx + 1))), field_def.ty(tcx, substs))
847 AggregateKind::Adt(adt_def, variant_index, substs, None, None),
853 let start_block = BasicBlockData {
855 terminator: Some(Terminator { source_info, kind: TerminatorKind::Return }),
860 new_body(IndexVec::from_elem_n(start_block, 1), local_decls, sig.inputs().len(), span);
862 crate::util::dump_mir(
867 crate::transform::MirSource::item(ctor_id),
872 let mut body = BodyAndCache::new(body);
873 body.ensure_predecessors();
874 tcx.arena.alloc(body)