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::region::ROOT_CODE_EXTENT;
15 use rustc::middle::const_val::ConstVal;
17 use rustc::mir::transform::MirSource;
18 use rustc::ty::{self, Ty};
19 use rustc::ty::subst::{Kind, Subst};
20 use rustc::ty::maps::Providers;
22 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
28 use std::cell::RefCell;
33 use transform::{add_call_guards, no_landing_pads, simplify};
34 use util::elaborate_drops::{self, DropElaborator, DropStyle, DropFlagMode};
35 use util::patch::MirPatch;
37 pub fn provide(providers: &mut Providers) {
38 providers.mir_shims = make_shim;
41 fn make_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
42 instance: ty::InstanceDef<'tcx>)
43 -> &'tcx RefCell<Mir<'tcx>>
45 debug!("make_shim({:?})", instance);
46 let did = instance.def_id();
47 let span = tcx.def_span(did);
49 tcx.construct_parameter_environment(span, did, ROOT_CODE_EXTENT);
51 let mut result = match instance {
52 ty::InstanceDef::Item(..) =>
53 bug!("item {:?} passed to make_shim", instance),
54 ty::InstanceDef::FnPtrShim(def_id, ty) => {
55 let trait_ = tcx.trait_of_item(def_id).unwrap();
56 let adjustment = match tcx.lang_items.fn_trait_kind(trait_) {
57 Some(ty::ClosureKind::FnOnce) => Adjustment::Identity,
58 Some(ty::ClosureKind::FnMut) |
59 Some(ty::ClosureKind::Fn) => Adjustment::Deref,
60 None => bug!("fn pointer {:?} is not an fn", ty)
62 // HACK: we need the "real" argument types for the MIR,
63 // but because our substs are (Self, Args), where Args
64 // is a tuple, we must include the *concrete* argument
65 // types in the MIR. They will be substituted again with
66 // the param-substs, but because they are concrete, this
67 // will not do any harm.
68 let sig = tcx.erase_late_bound_regions(&ty.fn_sig());
69 let arg_tys = sig.inputs();
80 ty::InstanceDef::Virtual(def_id, _) => {
81 // We are translating a call back to our def-id, which
82 // trans::mir knows to turn to an actual virtual call.
88 CallKind::Direct(def_id),
92 ty::InstanceDef::ClosureOnceShim { call_once } => {
93 let fn_mut = tcx.lang_items.fn_mut_trait().unwrap();
94 let call_mut = tcx.global_tcx()
95 .associated_items(fn_mut)
96 .find(|it| it.kind == ty::AssociatedKind::Method)
104 CallKind::Direct(call_mut),
108 ty::InstanceDef::DropGlue(def_id, ty) => {
109 build_drop_shim(tcx, ¶m_env, def_id, ty)
111 ty::InstanceDef::Intrinsic(_) => {
112 bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
115 debug!("make_shim({:?}) = untransformed {:?}", instance, result);
116 no_landing_pads::no_landing_pads(tcx, &mut result);
117 simplify::simplify_cfg(&mut result);
118 add_call_guards::add_call_guards(&mut result);
119 debug!("make_shim({:?}) = {:?}", instance, result);
121 let result = tcx.alloc_mir(result);
122 // Perma-borrow MIR from shims to prevent mutation.
123 mem::forget(result.borrow());
127 #[derive(Copy, Clone, Debug, PartialEq)]
134 #[derive(Copy, Clone, Debug, PartialEq)]
140 fn temp_decl(mutability: Mutability, ty: Ty) -> LocalDecl {
141 LocalDecl { mutability, ty, name: None, source_info: None }
144 fn local_decls_for_sig<'tcx>(sig: &ty::FnSig<'tcx>)
145 -> IndexVec<Local, LocalDecl<'tcx>>
147 iter::once(temp_decl(Mutability::Mut, sig.output()))
148 .chain(sig.inputs().iter().map(
149 |ity| temp_decl(Mutability::Not, ity)))
153 fn build_drop_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
154 param_env: &ty::ParameterEnvironment<'tcx>,
156 ty: Option<Ty<'tcx>>)
159 debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
161 let substs = if let Some(ty) = ty {
162 tcx.mk_substs(iter::once(Kind::from(ty)))
164 param_env.free_substs
166 let fn_ty = tcx.item_type(def_id).subst(tcx, substs);
167 let sig = tcx.erase_late_bound_regions(&fn_ty.fn_sig());
168 let span = tcx.def_span(def_id);
170 let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
172 let return_block = BasicBlock::new(1);
173 let mut blocks = IndexVec::new();
174 let block = |blocks: &mut IndexVec<_, _>, kind| {
175 blocks.push(BasicBlockData {
177 terminator: Some(Terminator { source_info, kind }),
181 block(&mut blocks, TerminatorKind::Goto { target: return_block });
182 block(&mut blocks, TerminatorKind::Return);
184 let mut mir = Mir::new(
186 IndexVec::from_elem_n(
187 VisibilityScopeData { span: span, parent_scope: None }, 1
191 local_decls_for_sig(&sig),
197 if let Some(..) = ty {
199 let mut elaborator = DropShimElaborator {
201 patch: MirPatch::new(&mir),
204 let dropee = Lvalue::Projection(
206 base: Lvalue::Local(Local::new(1+0)),
207 elem: ProjectionElem::Deref
210 let resume_block = elaborator.patch.resume_block();
211 elaborate_drops::elaborate_drop(
223 patch.apply(&mut mir);
229 pub struct DropShimElaborator<'a, 'tcx: 'a> {
231 patch: MirPatch<'tcx>,
232 tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
233 param_env: &'a ty::ParameterEnvironment<'tcx>,
236 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
237 fn fmt(&self, _f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
242 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
245 fn patch(&mut self) -> &mut MirPatch<'tcx> { &mut self.patch }
246 fn mir(&self) -> &'a Mir<'tcx> { self.mir }
247 fn tcx(&self) -> ty::TyCtxt<'a, 'tcx, 'tcx> { self.tcx }
248 fn param_env(&self) -> &'a ty::ParameterEnvironment<'tcx> { self.param_env }
250 fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
251 if let DropFlagMode::Shallow = mode {
258 fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
262 fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {
265 fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
268 fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
271 fn downcast_subpath(&self, _path: Self::Path, _variant: usize) -> Option<Self::Path> {
276 /// Build a "call" shim for `def_id`. The shim calls the
277 /// function specified by `call_kind`, first adjusting its first
278 /// argument according to `rcvr_adjustment`.
280 /// If `untuple_args` is a vec of types, the second argument of the
281 /// function will be untupled as these types.
282 fn build_call_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
283 param_env: &ty::ParameterEnvironment<'tcx>,
285 rcvr_adjustment: Adjustment,
287 untuple_args: Option<&[Ty<'tcx>]>)
290 debug!("build_call_shim(def_id={:?}, rcvr_adjustment={:?}, \
291 call_kind={:?}, untuple_args={:?})",
292 def_id, rcvr_adjustment, call_kind, untuple_args);
294 let fn_ty = tcx.item_type(def_id).subst(tcx, param_env.free_substs);
295 let sig = tcx.erase_late_bound_regions(&fn_ty.fn_sig());
296 let span = tcx.def_span(def_id);
298 debug!("build_call_shim: sig={:?}", sig);
300 let mut local_decls = local_decls_for_sig(&sig);
301 let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
303 let rcvr_arg = Local::new(1+0);
304 let rcvr_l = Lvalue::Local(rcvr_arg);
305 let mut statements = vec![];
307 let rcvr = match rcvr_adjustment {
308 Adjustment::Identity => Operand::Consume(rcvr_l),
309 Adjustment::Deref => Operand::Consume(Lvalue::Projection(
310 box Projection { base: rcvr_l, elem: ProjectionElem::Deref }
312 Adjustment::RefMut => {
313 // let rcvr = &mut rcvr;
314 let re_erased = tcx.mk_region(ty::ReErased);
315 let ref_rcvr = local_decls.push(temp_decl(
317 tcx.mk_ref(re_erased, ty::TypeAndMut {
319 mutbl: hir::Mutability::MutMutable
322 statements.push(Statement {
323 source_info: source_info,
324 kind: StatementKind::Assign(
325 Lvalue::Local(ref_rcvr),
326 Rvalue::Ref(re_erased, BorrowKind::Mut, rcvr_l)
329 Operand::Consume(Lvalue::Local(ref_rcvr))
333 let (callee, mut args) = match call_kind {
334 CallKind::Indirect => (rcvr, vec![]),
335 CallKind::Direct(def_id) => (
336 Operand::Constant(Constant {
338 ty: tcx.item_type(def_id).subst(tcx, param_env.free_substs),
339 literal: Literal::Value {
340 value: ConstVal::Function(def_id, param_env.free_substs),
347 if let Some(untuple_args) = untuple_args {
348 args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
349 let arg_lv = Lvalue::Local(Local::new(1+1));
350 Operand::Consume(Lvalue::Projection(box Projection {
352 elem: ProjectionElem::Field(Field::new(i), *ity)
356 args.extend((1..sig.inputs().len()).map(|i| {
357 Operand::Consume(Lvalue::Local(Local::new(1+i)))
361 let mut blocks = IndexVec::new();
362 let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
363 blocks.push(BasicBlockData {
365 terminator: Some(Terminator { source_info, kind }),
371 block(&mut blocks, statements, TerminatorKind::Call {
374 destination: Some((Lvalue::Local(RETURN_POINTER),
375 BasicBlock::new(1))),
376 cleanup: if let Adjustment::RefMut = rcvr_adjustment {
377 Some(BasicBlock::new(3))
383 if let Adjustment::RefMut = rcvr_adjustment {
384 // BB #1 - drop for Self
385 block(&mut blocks, vec![], TerminatorKind::Drop {
386 location: Lvalue::Local(rcvr_arg),
387 target: BasicBlock::new(2),
392 block(&mut blocks, vec![], TerminatorKind::Return, false);
393 if let Adjustment::RefMut = rcvr_adjustment {
394 // BB #3 - drop if closure panics
395 block(&mut blocks, vec![], TerminatorKind::Drop {
396 location: Lvalue::Local(rcvr_arg),
397 target: BasicBlock::new(4),
402 block(&mut blocks, vec![], TerminatorKind::Resume, true);
405 let mut mir = Mir::new(
407 IndexVec::from_elem_n(
408 VisibilityScopeData { span: span, parent_scope: None }, 1
417 if let Abi::RustCall = sig.abi {
418 mir.spread_arg = Some(Local::new(sig.inputs().len()));
423 pub fn build_adt_ctor<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
424 ctor_id: ast::NodeId,
425 fields: &[hir::StructField],
427 -> (Mir<'tcx>, MirSource)
430 let def_id = tcx.hir.local_def_id(ctor_id);
431 let sig = match tcx.item_type(def_id).sty {
432 ty::TyFnDef(_, _, fty) => tcx.no_late_bound_regions(&fty)
433 .expect("LBR in ADT constructor signature"),
434 _ => bug!("unexpected type for ctor {:?}", def_id)
436 let sig = tcx.erase_regions(&sig);
438 let (adt_def, substs) = match sig.output().sty {
439 ty::TyAdt(adt_def, substs) => (adt_def, substs),
440 _ => bug!("unexpected type for ADT ctor {:?}", sig.output())
443 debug!("build_ctor: def_id={:?} sig={:?} fields={:?}", def_id, sig, fields);
445 let local_decls = local_decls_for_sig(&sig);
447 let source_info = SourceInfo {
449 scope: ARGUMENT_VISIBILITY_SCOPE
452 let variant_no = if adt_def.is_enum() {
453 adt_def.variant_index_with_id(def_id)
458 // return = ADT(arg0, arg1, ...); return
459 let start_block = BasicBlockData {
460 statements: vec![Statement {
461 source_info: source_info,
462 kind: StatementKind::Assign(
463 Lvalue::Local(RETURN_POINTER),
465 AggregateKind::Adt(adt_def, variant_no, substs, None),
466 (1..sig.inputs().len()+1).map(|i| {
467 Operand::Consume(Lvalue::Local(Local::new(i)))
472 terminator: Some(Terminator {
473 source_info: source_info,
474 kind: TerminatorKind::Return,
480 IndexVec::from_elem_n(start_block, 1),
481 IndexVec::from_elem_n(
482 VisibilityScopeData { span: span, parent_scope: None }, 1
491 (mir, MirSource::Fn(ctor_id))