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};
30 use transform::{add_call_guards, no_landing_pads, simplify};
31 use util::elaborate_drops::{self, DropElaborator, DropStyle, DropFlagMode};
32 use util::patch::MirPatch;
34 pub fn provide(providers: &mut Providers) {
35 providers.mir_shims = make_shim;
38 fn make_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
39 instance: ty::InstanceDef<'tcx>)
42 debug!("make_shim({:?})", instance);
43 let did = instance.def_id();
44 let param_env = tcx.parameter_environment(did);
46 let mut result = match instance {
47 ty::InstanceDef::Item(..) =>
48 bug!("item {:?} passed to make_shim", instance),
49 ty::InstanceDef::FnPtrShim(def_id, ty) => {
50 let trait_ = tcx.trait_of_item(def_id).unwrap();
51 let adjustment = match tcx.lang_items.fn_trait_kind(trait_) {
52 Some(ty::ClosureKind::FnOnce) => Adjustment::Identity,
53 Some(ty::ClosureKind::FnMut) |
54 Some(ty::ClosureKind::Fn) => Adjustment::Deref,
55 None => bug!("fn pointer {:?} is not an fn", ty)
57 // HACK: we need the "real" argument types for the MIR,
58 // but because our substs are (Self, Args), where Args
59 // is a tuple, we must include the *concrete* argument
60 // types in the MIR. They will be substituted again with
61 // the param-substs, but because they are concrete, this
62 // will not do any harm.
63 let sig = tcx.erase_late_bound_regions(&ty.fn_sig());
64 let arg_tys = sig.inputs();
75 ty::InstanceDef::Virtual(def_id, _) => {
76 // We are translating a call back to our def-id, which
77 // trans::mir knows to turn to an actual virtual call.
83 CallKind::Direct(def_id),
87 ty::InstanceDef::ClosureOnceShim { call_once } => {
88 let fn_mut = tcx.lang_items.fn_mut_trait().unwrap();
89 let call_mut = tcx.global_tcx()
90 .associated_items(fn_mut)
91 .find(|it| it.kind == ty::AssociatedKind::Method)
99 CallKind::Direct(call_mut),
103 ty::InstanceDef::DropGlue(def_id, ty) => {
104 build_drop_shim(tcx, ¶m_env, def_id, ty)
106 ty::InstanceDef::Intrinsic(_) => {
107 bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
110 debug!("make_shim({:?}) = untransformed {:?}", instance, result);
111 no_landing_pads::no_landing_pads(tcx, &mut result);
112 simplify::simplify_cfg(&mut result);
113 add_call_guards::add_call_guards(&mut result);
114 debug!("make_shim({:?}) = {:?}", instance, result);
116 tcx.alloc_mir(result)
119 #[derive(Copy, Clone, Debug, PartialEq)]
126 #[derive(Copy, Clone, Debug, PartialEq)]
132 fn temp_decl(mutability: Mutability, ty: Ty, span: Span) -> LocalDecl {
134 mutability, ty, name: None,
135 source_info: SourceInfo { scope: ARGUMENT_VISIBILITY_SCOPE, span },
136 is_user_variable: false
140 fn local_decls_for_sig<'tcx>(sig: &ty::FnSig<'tcx>, span: Span)
141 -> IndexVec<Local, LocalDecl<'tcx>>
143 iter::once(temp_decl(Mutability::Mut, sig.output(), span))
144 .chain(sig.inputs().iter().map(
145 |ity| temp_decl(Mutability::Not, ity, span)))
149 fn build_drop_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
150 param_env: &ty::ParameterEnvironment<'tcx>,
152 ty: Option<Ty<'tcx>>)
155 debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
157 let substs = if let Some(ty) = ty {
158 tcx.mk_substs(iter::once(Kind::from(ty)))
160 param_env.free_substs
162 let fn_ty = tcx.type_of(def_id).subst(tcx, substs);
163 let sig = tcx.erase_late_bound_regions(&fn_ty.fn_sig());
164 let span = tcx.def_span(def_id);
166 let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
168 let return_block = BasicBlock::new(1);
169 let mut blocks = IndexVec::new();
170 let block = |blocks: &mut IndexVec<_, _>, kind| {
171 blocks.push(BasicBlockData {
173 terminator: Some(Terminator { source_info, kind }),
177 block(&mut blocks, TerminatorKind::Goto { target: return_block });
178 block(&mut blocks, TerminatorKind::Return);
180 let mut mir = Mir::new(
182 IndexVec::from_elem_n(
183 VisibilityScopeData { span: span, parent_scope: None }, 1
187 local_decls_for_sig(&sig, span),
193 if let Some(..) = ty {
195 let mut elaborator = DropShimElaborator {
197 patch: MirPatch::new(&mir),
200 let dropee = Lvalue::Local(Local::new(1+0)).deref();
201 let resume_block = elaborator.patch.resume_block();
202 elaborate_drops::elaborate_drop(
214 patch.apply(&mut mir);
220 pub struct DropShimElaborator<'a, 'tcx: 'a> {
222 patch: MirPatch<'tcx>,
223 tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
224 param_env: &'a ty::ParameterEnvironment<'tcx>,
227 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
228 fn fmt(&self, _f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
233 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
236 fn patch(&mut self) -> &mut MirPatch<'tcx> { &mut self.patch }
237 fn mir(&self) -> &'a Mir<'tcx> { self.mir }
238 fn tcx(&self) -> ty::TyCtxt<'a, 'tcx, 'tcx> { self.tcx }
239 fn param_env(&self) -> &'a ty::ParameterEnvironment<'tcx> { self.param_env }
241 fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
242 if let DropFlagMode::Shallow = mode {
249 fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
253 fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {
256 fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
259 fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
262 fn downcast_subpath(&self, _path: Self::Path, _variant: usize) -> Option<Self::Path> {
267 /// Build a "call" shim for `def_id`. The shim calls the
268 /// function specified by `call_kind`, first adjusting its first
269 /// argument according to `rcvr_adjustment`.
271 /// If `untuple_args` is a vec of types, the second argument of the
272 /// function will be untupled as these types.
273 fn build_call_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
274 param_env: &ty::ParameterEnvironment<'tcx>,
276 rcvr_adjustment: Adjustment,
278 untuple_args: Option<&[Ty<'tcx>]>)
281 debug!("build_call_shim(def_id={:?}, rcvr_adjustment={:?}, \
282 call_kind={:?}, untuple_args={:?})",
283 def_id, rcvr_adjustment, call_kind, untuple_args);
285 let fn_ty = tcx.type_of(def_id).subst(tcx, param_env.free_substs);
286 let sig = tcx.erase_late_bound_regions(&fn_ty.fn_sig());
287 let span = tcx.def_span(def_id);
289 debug!("build_call_shim: sig={:?}", sig);
291 let mut local_decls = local_decls_for_sig(&sig, span);
292 let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
294 let rcvr_arg = Local::new(1+0);
295 let rcvr_l = Lvalue::Local(rcvr_arg);
296 let mut statements = vec![];
298 let rcvr = match rcvr_adjustment {
299 Adjustment::Identity => Operand::Consume(rcvr_l),
300 Adjustment::Deref => Operand::Consume(rcvr_l.deref()),
301 Adjustment::RefMut => {
302 // let rcvr = &mut rcvr;
303 let ref_rcvr = local_decls.push(temp_decl(
305 tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
307 mutbl: hir::Mutability::MutMutable
311 statements.push(Statement {
312 source_info: source_info,
313 kind: StatementKind::Assign(
314 Lvalue::Local(ref_rcvr),
315 Rvalue::Ref(tcx.types.re_erased, BorrowKind::Mut, rcvr_l)
318 Operand::Consume(Lvalue::Local(ref_rcvr))
322 let (callee, mut args) = match call_kind {
323 CallKind::Indirect => (rcvr, vec![]),
324 CallKind::Direct(def_id) => (
325 Operand::Constant(box Constant {
327 ty: tcx.type_of(def_id).subst(tcx, param_env.free_substs),
328 literal: Literal::Value {
329 value: ConstVal::Function(def_id, param_env.free_substs),
336 if let Some(untuple_args) = untuple_args {
337 args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
338 let arg_lv = Lvalue::Local(Local::new(1+1));
339 Operand::Consume(arg_lv.field(Field::new(i), *ity))
342 args.extend((1..sig.inputs().len()).map(|i| {
343 Operand::Consume(Lvalue::Local(Local::new(1+i)))
347 let mut blocks = IndexVec::new();
348 let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
349 blocks.push(BasicBlockData {
351 terminator: Some(Terminator { source_info, kind }),
357 block(&mut blocks, statements, TerminatorKind::Call {
360 destination: Some((Lvalue::Local(RETURN_POINTER),
361 BasicBlock::new(1))),
362 cleanup: if let Adjustment::RefMut = rcvr_adjustment {
363 Some(BasicBlock::new(3))
369 if let Adjustment::RefMut = rcvr_adjustment {
370 // BB #1 - drop for Self
371 block(&mut blocks, vec![], TerminatorKind::Drop {
372 location: Lvalue::Local(rcvr_arg),
373 target: BasicBlock::new(2),
378 block(&mut blocks, vec![], TerminatorKind::Return, false);
379 if let Adjustment::RefMut = rcvr_adjustment {
380 // BB #3 - drop if closure panics
381 block(&mut blocks, vec![], TerminatorKind::Drop {
382 location: Lvalue::Local(rcvr_arg),
383 target: BasicBlock::new(4),
388 block(&mut blocks, vec![], TerminatorKind::Resume, true);
391 let mut mir = Mir::new(
393 IndexVec::from_elem_n(
394 VisibilityScopeData { span: span, parent_scope: None }, 1
403 if let Abi::RustCall = sig.abi {
404 mir.spread_arg = Some(Local::new(sig.inputs().len()));
409 pub fn build_adt_ctor<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
410 ctor_id: ast::NodeId,
411 fields: &[hir::StructField],
413 -> (Mir<'tcx>, MirSource)
416 let def_id = tcx.hir.local_def_id(ctor_id);
417 let sig = match tcx.type_of(def_id).sty {
418 ty::TyFnDef(_, _, fty) => tcx.no_late_bound_regions(&fty)
419 .expect("LBR in ADT constructor signature"),
420 _ => bug!("unexpected type for ctor {:?}", def_id)
422 let sig = tcx.erase_regions(&sig);
424 let (adt_def, substs) = match sig.output().sty {
425 ty::TyAdt(adt_def, substs) => (adt_def, substs),
426 _ => bug!("unexpected type for ADT ctor {:?}", sig.output())
429 debug!("build_ctor: def_id={:?} sig={:?} fields={:?}", def_id, sig, fields);
431 let local_decls = local_decls_for_sig(&sig, span);
433 let source_info = SourceInfo {
435 scope: ARGUMENT_VISIBILITY_SCOPE
438 let variant_no = if adt_def.is_enum() {
439 adt_def.variant_index_with_id(def_id)
444 // return = ADT(arg0, arg1, ...); return
445 let start_block = BasicBlockData {
446 statements: vec![Statement {
447 source_info: source_info,
448 kind: StatementKind::Assign(
449 Lvalue::Local(RETURN_POINTER),
451 box AggregateKind::Adt(adt_def, variant_no, substs, None),
452 (1..sig.inputs().len()+1).map(|i| {
453 Operand::Consume(Lvalue::Local(Local::new(i)))
458 terminator: Some(Terminator {
459 source_info: source_info,
460 kind: TerminatorKind::Return,
466 IndexVec::from_elem_n(start_block, 1),
467 IndexVec::from_elem_n(
468 VisibilityScopeData { span: span, parent_scope: None }, 1
477 (mir, MirSource::Fn(ctor_id))