1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
12 use rustc::hir::def_id::DefId;
14 use rustc::middle::const_val::ConstVal;
16 use rustc::mir::transform::MirSource;
17 use rustc::ty::{self, Ty};
18 use rustc::ty::subst::{Kind, Subst, Substs};
19 use rustc::ty::maps::Providers;
20 use rustc_const_math::{ConstInt, ConstUsize};
22 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
31 use transform::{add_call_guards, no_landing_pads, simplify};
32 use util::elaborate_drops::{self, DropElaborator, DropStyle, DropFlagMode};
33 use util::patch::MirPatch;
35 pub fn provide(providers: &mut Providers) {
36 providers.mir_shims = make_shim;
39 fn make_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
40 instance: ty::InstanceDef<'tcx>)
43 debug!("make_shim({:?})", instance);
45 let mut result = match instance {
46 ty::InstanceDef::Item(..) =>
47 bug!("item {:?} passed to make_shim", instance),
48 ty::InstanceDef::FnPtrShim(def_id, ty) => {
49 let trait_ = tcx.trait_of_item(def_id).unwrap();
50 let adjustment = match tcx.lang_items.fn_trait_kind(trait_) {
51 Some(ty::ClosureKind::FnOnce) => Adjustment::Identity,
52 Some(ty::ClosureKind::FnMut) |
53 Some(ty::ClosureKind::Fn) => Adjustment::Deref,
54 None => bug!("fn pointer {:?} is not an fn", ty)
56 // HACK: we need the "real" argument types for the MIR,
57 // but because our substs are (Self, Args), where Args
58 // is a tuple, we must include the *concrete* argument
59 // types in the MIR. They will be substituted again with
60 // the param-substs, but because they are concrete, this
61 // will not do any harm.
62 let sig = tcx.erase_late_bound_regions(&ty.fn_sig(tcx));
63 let arg_tys = sig.inputs();
73 ty::InstanceDef::Virtual(def_id, _) => {
74 // We are translating a call back to our def-id, which
75 // trans::mir knows to turn to an actual virtual call.
80 CallKind::Direct(def_id),
84 ty::InstanceDef::ClosureOnceShim { call_once } => {
85 let fn_mut = tcx.lang_items.fn_mut_trait().unwrap();
86 let call_mut = tcx.global_tcx()
87 .associated_items(fn_mut)
88 .find(|it| it.kind == ty::AssociatedKind::Method)
95 CallKind::Direct(call_mut),
99 ty::InstanceDef::DropGlue(def_id, ty) => {
100 build_drop_shim(tcx, def_id, ty)
102 ty::InstanceDef::CloneShim(def_id, ty) => {
103 let name = tcx.item_name(def_id).as_str();
105 build_clone_shim(tcx, def_id, ty)
106 } else if name == "clone_from" {
107 debug!("make_shim({:?}: using default trait implementation", instance);
108 return tcx.optimized_mir(def_id);
110 bug!("builtin clone shim {:?} not supported", instance)
113 ty::InstanceDef::Intrinsic(_) => {
114 bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
117 debug!("make_shim({:?}) = untransformed {:?}", instance, result);
118 no_landing_pads::no_landing_pads(tcx, &mut result);
119 simplify::simplify_cfg(&mut result);
120 add_call_guards::CriticalCallEdges.add_call_guards(&mut result);
121 debug!("make_shim({:?}) = {:?}", instance, result);
123 tcx.alloc_mir(result)
126 #[derive(Copy, Clone, Debug, PartialEq)]
133 #[derive(Copy, Clone, Debug, PartialEq)]
139 fn temp_decl(mutability: Mutability, ty: Ty, span: Span) -> LocalDecl {
141 mutability, ty, name: None,
142 source_info: SourceInfo { scope: ARGUMENT_VISIBILITY_SCOPE, span },
143 is_user_variable: false
147 fn local_decls_for_sig<'tcx>(sig: &ty::FnSig<'tcx>, span: Span)
148 -> IndexVec<Local, LocalDecl<'tcx>>
150 iter::once(temp_decl(Mutability::Mut, sig.output(), span))
151 .chain(sig.inputs().iter().map(
152 |ity| temp_decl(Mutability::Not, ity, span)))
156 fn build_drop_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
158 ty: Option<Ty<'tcx>>)
161 debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
163 let substs = if let Some(ty) = ty {
164 tcx.mk_substs(iter::once(Kind::from(ty)))
166 Substs::identity_for_item(tcx, def_id)
168 let sig = tcx.fn_sig(def_id).subst(tcx, substs);
169 let sig = tcx.erase_late_bound_regions(&sig);
170 let span = tcx.def_span(def_id);
172 let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
174 let return_block = BasicBlock::new(1);
175 let mut blocks = IndexVec::new();
176 let block = |blocks: &mut IndexVec<_, _>, kind| {
177 blocks.push(BasicBlockData {
179 terminator: Some(Terminator { source_info, kind }),
183 block(&mut blocks, TerminatorKind::Goto { target: return_block });
184 block(&mut blocks, TerminatorKind::Return);
186 let mut mir = Mir::new(
188 IndexVec::from_elem_n(
189 VisibilityScopeData { span: span, parent_scope: None }, 1
193 local_decls_for_sig(&sig, span),
199 if let Some(..) = ty {
201 let param_env = tcx.param_env(def_id);
202 let mut elaborator = DropShimElaborator {
204 patch: MirPatch::new(&mir),
208 let dropee = Lvalue::Local(Local::new(1+0)).deref();
209 let resume_block = elaborator.patch.resume_block();
210 elaborate_drops::elaborate_drop(
216 elaborate_drops::Unwind::To(resume_block),
221 patch.apply(&mut mir);
227 pub struct DropShimElaborator<'a, 'tcx: 'a> {
229 patch: MirPatch<'tcx>,
230 tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
231 param_env: ty::ParamEnv<'tcx>,
234 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
235 fn fmt(&self, _f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
240 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
243 fn patch(&mut self) -> &mut MirPatch<'tcx> { &mut self.patch }
244 fn mir(&self) -> &'a Mir<'tcx> { self.mir }
245 fn tcx(&self) -> ty::TyCtxt<'a, 'tcx, 'tcx> { self.tcx }
246 fn param_env(&self) -> ty::ParamEnv<'tcx> { self.param_env }
248 fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
249 if let DropFlagMode::Shallow = mode {
256 fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
260 fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {
263 fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
266 fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
269 fn downcast_subpath(&self, _path: Self::Path, _variant: usize) -> Option<Self::Path> {
274 /// Build a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`.
275 fn build_clone_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
277 self_ty: ty::Ty<'tcx>)
280 debug!("build_clone_shim(def_id={:?})", def_id);
282 let mut builder = CloneShimBuilder::new(tcx, def_id);
283 let is_copy = !self_ty.moves_by_default(tcx, tcx.param_env(def_id), builder.span);
286 _ if is_copy => builder.copy_shim(),
287 ty::TyArray(ty, len) => builder.array_shim(ty, len),
288 ty::TyTuple(tys, _) => builder.tuple_shim(tys),
290 bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty);
297 struct CloneShimBuilder<'a, 'tcx: 'a> {
298 tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
300 local_decls: IndexVec<Local, LocalDecl<'tcx>>,
301 blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
303 sig: ty::FnSig<'tcx>,
306 impl<'a, 'tcx> CloneShimBuilder<'a, 'tcx> {
307 fn new(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> Self {
308 let sig = tcx.fn_sig(def_id);
309 let sig = tcx.erase_late_bound_regions(&sig);
310 let span = tcx.def_span(def_id);
315 local_decls: local_decls_for_sig(&sig, span),
316 blocks: IndexVec::new(),
322 fn into_mir(self) -> Mir<'tcx> {
325 IndexVec::from_elem_n(
326 VisibilityScopeData { span: self.span, parent_scope: None }, 1
331 self.sig.inputs().len(),
337 fn source_info(&self) -> SourceInfo {
338 SourceInfo { span: self.span, scope: ARGUMENT_VISIBILITY_SCOPE }
343 statements: Vec<Statement<'tcx>>,
344 kind: TerminatorKind<'tcx>,
347 let source_info = self.source_info();
348 self.blocks.push(BasicBlockData {
350 terminator: Some(Terminator { source_info, kind }),
355 fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
357 source_info: self.source_info(),
362 fn copy_shim(&mut self) {
363 let rcvr = Lvalue::Local(Local::new(1+0)).deref();
364 let ret_statement = self.make_statement(
365 StatementKind::Assign(
366 Lvalue::Local(RETURN_POINTER),
367 Rvalue::Use(Operand::Consume(rcvr))
370 self.block(vec![ret_statement], TerminatorKind::Return, false);
373 fn make_lvalue(&mut self, mutability: Mutability, ty: ty::Ty<'tcx>) -> Lvalue<'tcx> {
374 let span = self.span;
376 self.local_decls.push(temp_decl(mutability, ty, span))
383 rcvr_field: Lvalue<'tcx>,
389 let substs = Substs::for_item(
392 |_, _| tcx.types.re_erased,
396 // `func == Clone::clone(&ty) -> ty`
397 let func = Operand::Constant(box Constant {
399 ty: tcx.mk_fn_def(self.def_id, substs),
400 literal: Literal::Value {
401 value: ConstVal::Function(self.def_id, substs),
405 let ref_loc = self.make_lvalue(
407 tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
409 mutbl: hir::Mutability::MutImmutable,
413 let loc = self.make_lvalue(Mutability::Not, ty);
415 // `let ref_loc: &ty = &rcvr_field;`
416 let statement = self.make_statement(
417 StatementKind::Assign(
419 Rvalue::Ref(tcx.types.re_erased, BorrowKind::Shared, rcvr_field)
423 // `let loc = Clone::clone(ref_loc);`
424 self.block(vec![statement], TerminatorKind::Call {
426 args: vec![Operand::Consume(ref_loc)],
427 destination: Some((loc.clone(), next)),
428 cleanup: Some(cleanup),
438 loop_body: BasicBlock,
439 loop_end: BasicBlock,
444 let cond = self.make_lvalue(Mutability::Mut, tcx.types.bool);
445 let compute_cond = self.make_statement(
446 StatementKind::Assign(
448 Rvalue::BinaryOp(BinOp::Ne, Operand::Consume(end), Operand::Consume(beg))
452 // `if end != beg { goto loop_body; } else { goto loop_end; }`
455 TerminatorKind::if_(tcx, Operand::Consume(cond), loop_body, loop_end),
460 fn make_usize(&self, value: usize) -> Box<Constant<'tcx>> {
461 let value = ConstUsize::new(value as u64, self.tcx.sess.target.uint_type).unwrap();
464 ty: self.tcx.types.usize,
465 literal: Literal::Value {
466 value: ConstVal::Integral(ConstInt::Usize(value))
471 fn array_shim(&mut self, ty: ty::Ty<'tcx>, len: usize) {
473 let rcvr = Lvalue::Local(Local::new(1+0)).deref();
475 let beg = self.make_lvalue(Mutability::Mut, tcx.types.usize);
476 let end = self.make_lvalue(Mutability::Not, tcx.types.usize);
477 let ret = self.make_lvalue(Mutability::Mut, tcx.mk_array(ty, len));
480 // `let mut beg = 0;`
485 StatementKind::Assign(
487 Rvalue::Use(Operand::Constant(self.make_usize(0)))
491 StatementKind::Assign(
493 Rvalue::Use(Operand::Constant(self.make_usize(len)))
497 self.block(inits, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
504 self.loop_header(beg.clone(), end, BasicBlock::new(2), BasicBlock::new(4), false);
507 // `let cloned = Clone::clone(rcvr[beg])`;
508 // Goto #3 if ok, #5 if unwinding happens.
509 let rcvr_field = rcvr.clone().index(Operand::Consume(beg.clone()));
510 let cloned = self.make_clone_call(ty, rcvr_field, BasicBlock::new(3), BasicBlock::new(5));
513 // `ret[beg] = cloned;`
516 let ret_field = ret.clone().index(Operand::Consume(beg.clone()));
517 let statements = vec![
519 StatementKind::Assign(
521 Rvalue::Use(Operand::Consume(cloned))
525 StatementKind::Assign(
529 Operand::Consume(beg.clone()),
530 Operand::Constant(self.make_usize(1))
535 self.block(statements, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
539 let ret_statement = self.make_statement(
540 StatementKind::Assign(
541 Lvalue::Local(RETURN_POINTER),
542 Rvalue::Use(Operand::Consume(ret.clone())),
545 self.block(vec![ret_statement], TerminatorKind::Return, false);
549 // `let mut beg = 0;`
552 let beg = self.make_lvalue(Mutability::Mut, tcx.types.usize);
553 let init = self.make_statement(
554 StatementKind::Assign(
556 Rvalue::Use(Operand::Constant(self.make_usize(0)))
559 self.block(vec![init], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
561 // BB #6 (cleanup): loop {
566 self.loop_header(beg.clone(), end, BasicBlock::new(7), BasicBlock::new(9), true);
570 self.block(vec![], TerminatorKind::Drop {
571 location: ret.index(Operand::Consume(beg.clone())),
572 target: BasicBlock::new(8),
579 let statement = self.make_statement(
580 StatementKind::Assign(
584 Operand::Consume(beg.clone()),
585 Operand::Constant(self.make_usize(1))
589 self.block(vec![statement], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
592 self.block(vec![], TerminatorKind::Resume, true);
595 fn tuple_shim(&mut self, tys: &ty::Slice<ty::Ty<'tcx>>) {
596 let rcvr = Lvalue::Local(Local::new(1+0)).deref();
598 let mut returns = Vec::new();
599 for (i, ity) in tys.iter().enumerate() {
600 let rcvr_field = rcvr.clone().field(Field::new(i), *ity);
603 // `returns[i] = Clone::clone(&rcvr.i);`
604 // Goto #(2i + 2) if ok, #(2i + 1) if unwinding happens.
606 self.make_clone_call(
609 BasicBlock::new(2 * i + 2),
610 BasicBlock::new(2 * i + 1),
614 // BB #(2i + 1) (cleanup)
616 // Nothing to drop, just resume.
617 self.block(vec![], TerminatorKind::Resume, true);
619 // Drop previous field and goto previous cleanup block.
620 self.block(vec![], TerminatorKind::Drop {
621 location: returns[i - 1].clone(),
622 target: BasicBlock::new(2 * i - 1),
628 // `return (returns[0], returns[1], ..., returns[tys.len() - 1]);`
629 let ret_statement = self.make_statement(
630 StatementKind::Assign(
631 Lvalue::Local(RETURN_POINTER),
633 box AggregateKind::Tuple,
634 returns.into_iter().map(Operand::Consume).collect()
638 self.block(vec![ret_statement], TerminatorKind::Return, false);
642 /// Build a "call" shim for `def_id`. 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<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
650 rcvr_adjustment: Adjustment,
652 untuple_args: Option<&[Ty<'tcx>]>)
655 debug!("build_call_shim(def_id={:?}, rcvr_adjustment={:?}, \
656 call_kind={:?}, untuple_args={:?})",
657 def_id, rcvr_adjustment, call_kind, untuple_args);
659 let sig = tcx.fn_sig(def_id);
660 let sig = tcx.erase_late_bound_regions(&sig);
661 let span = tcx.def_span(def_id);
663 debug!("build_call_shim: sig={:?}", sig);
665 let mut local_decls = local_decls_for_sig(&sig, span);
666 let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
668 let rcvr_arg = Local::new(1+0);
669 let rcvr_l = Lvalue::Local(rcvr_arg);
670 let mut statements = vec![];
672 let rcvr = match rcvr_adjustment {
673 Adjustment::Identity => Operand::Consume(rcvr_l),
674 Adjustment::Deref => Operand::Consume(rcvr_l.deref()),
675 Adjustment::RefMut => {
676 // let rcvr = &mut rcvr;
677 let ref_rcvr = local_decls.push(temp_decl(
679 tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
681 mutbl: hir::Mutability::MutMutable
685 statements.push(Statement {
687 kind: StatementKind::Assign(
688 Lvalue::Local(ref_rcvr),
689 Rvalue::Ref(tcx.types.re_erased, BorrowKind::Mut, rcvr_l)
692 Operand::Consume(Lvalue::Local(ref_rcvr))
696 let (callee, mut args) = match call_kind {
697 CallKind::Indirect => (rcvr, vec![]),
698 CallKind::Direct(def_id) => (
699 Operand::Constant(box Constant {
701 ty: tcx.type_of(def_id),
702 literal: Literal::Value {
703 value: ConstVal::Function(def_id,
704 Substs::identity_for_item(tcx, def_id)),
711 if let Some(untuple_args) = untuple_args {
712 args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
713 let arg_lv = Lvalue::Local(Local::new(1+1));
714 Operand::Consume(arg_lv.field(Field::new(i), *ity))
717 args.extend((1..sig.inputs().len()).map(|i| {
718 Operand::Consume(Lvalue::Local(Local::new(1+i)))
722 let mut blocks = IndexVec::new();
723 let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
724 blocks.push(BasicBlockData {
726 terminator: Some(Terminator { source_info, kind }),
732 block(&mut blocks, statements, TerminatorKind::Call {
735 destination: Some((Lvalue::Local(RETURN_POINTER),
736 BasicBlock::new(1))),
737 cleanup: if let Adjustment::RefMut = rcvr_adjustment {
738 Some(BasicBlock::new(3))
744 if let Adjustment::RefMut = rcvr_adjustment {
745 // BB #1 - drop for Self
746 block(&mut blocks, vec![], TerminatorKind::Drop {
747 location: Lvalue::Local(rcvr_arg),
748 target: BasicBlock::new(2),
753 block(&mut blocks, vec![], TerminatorKind::Return, false);
754 if let Adjustment::RefMut = rcvr_adjustment {
755 // BB #3 - drop if closure panics
756 block(&mut blocks, vec![], TerminatorKind::Drop {
757 location: Lvalue::Local(rcvr_arg),
758 target: BasicBlock::new(4),
763 block(&mut blocks, vec![], TerminatorKind::Resume, true);
766 let mut mir = Mir::new(
768 IndexVec::from_elem_n(
769 VisibilityScopeData { span: span, parent_scope: None }, 1
778 if let Abi::RustCall = sig.abi {
779 mir.spread_arg = Some(Local::new(sig.inputs().len()));
784 pub fn build_adt_ctor<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
785 ctor_id: ast::NodeId,
786 fields: &[hir::StructField],
788 -> (Mir<'tcx>, MirSource)
791 let def_id = tcx.hir.local_def_id(ctor_id);
792 let sig = tcx.no_late_bound_regions(&tcx.fn_sig(def_id))
793 .expect("LBR in ADT constructor signature");
794 let sig = tcx.erase_regions(&sig);
796 let (adt_def, substs) = match sig.output().sty {
797 ty::TyAdt(adt_def, substs) => (adt_def, substs),
798 _ => bug!("unexpected type for ADT ctor {:?}", sig.output())
801 debug!("build_ctor: def_id={:?} sig={:?} fields={:?}", def_id, sig, fields);
803 let local_decls = local_decls_for_sig(&sig, span);
805 let source_info = SourceInfo {
807 scope: ARGUMENT_VISIBILITY_SCOPE
810 let variant_no = if adt_def.is_enum() {
811 adt_def.variant_index_with_id(def_id)
816 // return = ADT(arg0, arg1, ...); return
817 let start_block = BasicBlockData {
818 statements: vec![Statement {
820 kind: StatementKind::Assign(
821 Lvalue::Local(RETURN_POINTER),
823 box AggregateKind::Adt(adt_def, variant_no, substs, None),
824 (1..sig.inputs().len()+1).map(|i| {
825 Operand::Consume(Lvalue::Local(Local::new(i)))
830 terminator: Some(Terminator {
832 kind: TerminatorKind::Return,
838 IndexVec::from_elem_n(start_block, 1),
839 IndexVec::from_elem_n(
840 VisibilityScopeData { span: span, parent_scope: None }, 1
849 (mir, MirSource::Fn(ctor_id))