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};
19 use rustc::ty::maps::Providers;
21 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
27 use std::cell::RefCell;
32 use transform::{add_call_guards, no_landing_pads, simplify};
33 use util::elaborate_drops::{self, DropElaborator, DropStyle, DropFlagMode};
34 use util::patch::MirPatch;
36 pub fn provide(providers: &mut Providers) {
37 providers.mir_shims = make_shim;
40 fn make_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
41 instance: ty::InstanceDef<'tcx>)
42 -> &'tcx RefCell<Mir<'tcx>>
44 debug!("make_shim({:?})", instance);
45 let did = instance.def_id();
46 let span = tcx.def_span(did);
47 let param_env = tcx.construct_parameter_environment(span, did, None);
49 let mut result = match instance {
50 ty::InstanceDef::Item(..) =>
51 bug!("item {:?} passed to make_shim", instance),
52 ty::InstanceDef::FnPtrShim(def_id, ty) => {
53 let trait_ = tcx.trait_of_item(def_id).unwrap();
54 let adjustment = match tcx.lang_items.fn_trait_kind(trait_) {
55 Some(ty::ClosureKind::FnOnce) => Adjustment::Identity,
56 Some(ty::ClosureKind::FnMut) |
57 Some(ty::ClosureKind::Fn) => Adjustment::Deref,
58 None => bug!("fn pointer {:?} is not an fn", ty)
60 // HACK: we need the "real" argument types for the MIR,
61 // but because our substs are (Self, Args), where Args
62 // is a tuple, we must include the *concrete* argument
63 // types in the MIR. They will be substituted again with
64 // the param-substs, but because they are concrete, this
65 // will not do any harm.
66 let sig = tcx.erase_late_bound_regions(&ty.fn_sig());
67 let arg_tys = sig.inputs();
78 ty::InstanceDef::Virtual(def_id, _) => {
79 // We are translating a call back to our def-id, which
80 // trans::mir knows to turn to an actual virtual call.
86 CallKind::Direct(def_id),
90 ty::InstanceDef::ClosureOnceShim { call_once } => {
91 let fn_mut = tcx.lang_items.fn_mut_trait().unwrap();
92 let call_mut = tcx.global_tcx()
93 .associated_items(fn_mut)
94 .find(|it| it.kind == ty::AssociatedKind::Method)
102 CallKind::Direct(call_mut),
106 ty::InstanceDef::DropGlue(def_id, ty) => {
107 build_drop_shim(tcx, ¶m_env, def_id, ty)
109 ty::InstanceDef::Intrinsic(_) => {
110 bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
113 debug!("make_shim({:?}) = untransformed {:?}", instance, result);
114 no_landing_pads::no_landing_pads(tcx, &mut result);
115 simplify::simplify_cfg(&mut result);
116 add_call_guards::add_call_guards(&mut result);
117 debug!("make_shim({:?}) = {:?}", instance, result);
119 let result = tcx.alloc_mir(result);
120 // Perma-borrow MIR from shims to prevent mutation.
121 mem::forget(result.borrow());
125 #[derive(Copy, Clone, Debug, PartialEq)]
132 #[derive(Copy, Clone, Debug, PartialEq)]
138 fn temp_decl(mutability: Mutability, ty: Ty, span: Span) -> LocalDecl {
140 mutability, ty, name: None,
141 source_info: SourceInfo { scope: ARGUMENT_VISIBILITY_SCOPE, span },
142 is_user_variable: false
146 fn local_decls_for_sig<'tcx>(sig: &ty::FnSig<'tcx>, span: Span)
147 -> IndexVec<Local, LocalDecl<'tcx>>
149 iter::once(temp_decl(Mutability::Mut, sig.output(), span))
150 .chain(sig.inputs().iter().map(
151 |ity| temp_decl(Mutability::Not, ity, span)))
155 fn build_drop_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
156 param_env: &ty::ParameterEnvironment<'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 param_env.free_substs
168 let fn_ty = tcx.type_of(def_id).subst(tcx, substs);
169 let sig = tcx.erase_late_bound_regions(&fn_ty.fn_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 mut elaborator = DropShimElaborator {
203 patch: MirPatch::new(&mir),
206 let dropee = Lvalue::Local(Local::new(1+0)).deref();
207 let resume_block = elaborator.patch.resume_block();
208 elaborate_drops::elaborate_drop(
220 patch.apply(&mut mir);
226 pub struct DropShimElaborator<'a, 'tcx: 'a> {
228 patch: MirPatch<'tcx>,
229 tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
230 param_env: &'a ty::ParameterEnvironment<'tcx>,
233 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
234 fn fmt(&self, _f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
239 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
242 fn patch(&mut self) -> &mut MirPatch<'tcx> { &mut self.patch }
243 fn mir(&self) -> &'a Mir<'tcx> { self.mir }
244 fn tcx(&self) -> ty::TyCtxt<'a, 'tcx, 'tcx> { self.tcx }
245 fn param_env(&self) -> &'a ty::ParameterEnvironment<'tcx> { self.param_env }
247 fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
248 if let DropFlagMode::Shallow = mode {
255 fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
259 fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {
262 fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
265 fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
268 fn downcast_subpath(&self, _path: Self::Path, _variant: usize) -> Option<Self::Path> {
273 /// Build a "call" shim for `def_id`. The shim calls the
274 /// function specified by `call_kind`, first adjusting its first
275 /// argument according to `rcvr_adjustment`.
277 /// If `untuple_args` is a vec of types, the second argument of the
278 /// function will be untupled as these types.
279 fn build_call_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
280 param_env: &ty::ParameterEnvironment<'tcx>,
282 rcvr_adjustment: Adjustment,
284 untuple_args: Option<&[Ty<'tcx>]>)
287 debug!("build_call_shim(def_id={:?}, rcvr_adjustment={:?}, \
288 call_kind={:?}, untuple_args={:?})",
289 def_id, rcvr_adjustment, call_kind, untuple_args);
291 let fn_ty = tcx.type_of(def_id).subst(tcx, param_env.free_substs);
292 let sig = tcx.erase_late_bound_regions(&fn_ty.fn_sig());
293 let span = tcx.def_span(def_id);
295 debug!("build_call_shim: sig={:?}", sig);
297 let mut local_decls = local_decls_for_sig(&sig, span);
298 let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
300 let rcvr_arg = Local::new(1+0);
301 let rcvr_l = Lvalue::Local(rcvr_arg);
302 let mut statements = vec![];
304 let rcvr = match rcvr_adjustment {
305 Adjustment::Identity => Operand::Consume(rcvr_l),
306 Adjustment::Deref => Operand::Consume(rcvr_l.deref()),
307 Adjustment::RefMut => {
308 // let rcvr = &mut rcvr;
309 let ref_rcvr = local_decls.push(temp_decl(
311 tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
313 mutbl: hir::Mutability::MutMutable
317 statements.push(Statement {
318 source_info: source_info,
319 kind: StatementKind::Assign(
320 Lvalue::Local(ref_rcvr),
321 Rvalue::Ref(tcx.types.re_erased, BorrowKind::Mut, rcvr_l)
324 Operand::Consume(Lvalue::Local(ref_rcvr))
328 let (callee, mut args) = match call_kind {
329 CallKind::Indirect => (rcvr, vec![]),
330 CallKind::Direct(def_id) => (
331 Operand::Constant(Constant {
333 ty: tcx.type_of(def_id).subst(tcx, param_env.free_substs),
334 literal: Literal::Value {
335 value: ConstVal::Function(def_id, param_env.free_substs),
342 if let Some(untuple_args) = untuple_args {
343 args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
344 let arg_lv = Lvalue::Local(Local::new(1+1));
345 Operand::Consume(arg_lv.field(Field::new(i), *ity))
348 args.extend((1..sig.inputs().len()).map(|i| {
349 Operand::Consume(Lvalue::Local(Local::new(1+i)))
353 let mut blocks = IndexVec::new();
354 let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
355 blocks.push(BasicBlockData {
357 terminator: Some(Terminator { source_info, kind }),
363 block(&mut blocks, statements, TerminatorKind::Call {
366 destination: Some((Lvalue::Local(RETURN_POINTER),
367 BasicBlock::new(1))),
368 cleanup: if let Adjustment::RefMut = rcvr_adjustment {
369 Some(BasicBlock::new(3))
375 if let Adjustment::RefMut = rcvr_adjustment {
376 // BB #1 - drop for Self
377 block(&mut blocks, vec![], TerminatorKind::Drop {
378 location: Lvalue::Local(rcvr_arg),
379 target: BasicBlock::new(2),
384 block(&mut blocks, vec![], TerminatorKind::Return, false);
385 if let Adjustment::RefMut = rcvr_adjustment {
386 // BB #3 - drop if closure panics
387 block(&mut blocks, vec![], TerminatorKind::Drop {
388 location: Lvalue::Local(rcvr_arg),
389 target: BasicBlock::new(4),
394 block(&mut blocks, vec![], TerminatorKind::Resume, true);
397 let mut mir = Mir::new(
399 IndexVec::from_elem_n(
400 VisibilityScopeData { span: span, parent_scope: None }, 1
409 if let Abi::RustCall = sig.abi {
410 mir.spread_arg = Some(Local::new(sig.inputs().len()));
415 pub fn build_adt_ctor<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
416 ctor_id: ast::NodeId,
417 fields: &[hir::StructField],
419 -> (Mir<'tcx>, MirSource)
422 let def_id = tcx.hir.local_def_id(ctor_id);
423 let sig = match tcx.type_of(def_id).sty {
424 ty::TyFnDef(_, _, fty) => tcx.no_late_bound_regions(&fty)
425 .expect("LBR in ADT constructor signature"),
426 _ => bug!("unexpected type for ctor {:?}", def_id)
428 let sig = tcx.erase_regions(&sig);
430 let (adt_def, substs) = match sig.output().sty {
431 ty::TyAdt(adt_def, substs) => (adt_def, substs),
432 _ => bug!("unexpected type for ADT ctor {:?}", sig.output())
435 debug!("build_ctor: def_id={:?} sig={:?} fields={:?}", def_id, sig, fields);
437 let local_decls = local_decls_for_sig(&sig, span);
439 let source_info = SourceInfo {
441 scope: ARGUMENT_VISIBILITY_SCOPE
444 let variant_no = if adt_def.is_enum() {
445 adt_def.variant_index_with_id(def_id)
450 // return = ADT(arg0, arg1, ...); return
451 let start_block = BasicBlockData {
452 statements: vec![Statement {
453 source_info: source_info,
454 kind: StatementKind::Assign(
455 Lvalue::Local(RETURN_POINTER),
457 AggregateKind::Adt(adt_def, variant_no, substs, None),
458 (1..sig.inputs().len()+1).map(|i| {
459 Operand::Consume(Lvalue::Local(Local::new(i)))
464 terminator: Some(Terminator {
465 source_info: source_info,
466 kind: TerminatorKind::Return,
472 IndexVec::from_elem_n(start_block, 1),
473 IndexVec::from_elem_n(
474 VisibilityScopeData { span: span, parent_scope: None }, 1
483 (mir, MirSource::Fn(ctor_id))