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 span = tcx.def_span(did);
45 let param_env = tcx.construct_parameter_environment(span, did, None);
47 let mut result = match instance {
48 ty::InstanceDef::Item(..) =>
49 bug!("item {:?} passed to make_shim", instance),
50 ty::InstanceDef::FnPtrShim(def_id, ty) => {
51 let trait_ = tcx.trait_of_item(def_id).unwrap();
52 let adjustment = match tcx.lang_items.fn_trait_kind(trait_) {
53 Some(ty::ClosureKind::FnOnce) => Adjustment::Identity,
54 Some(ty::ClosureKind::FnMut) |
55 Some(ty::ClosureKind::Fn) => Adjustment::Deref,
56 None => bug!("fn pointer {:?} is not an fn", ty)
58 // HACK: we need the "real" argument types for the MIR,
59 // but because our substs are (Self, Args), where Args
60 // is a tuple, we must include the *concrete* argument
61 // types in the MIR. They will be substituted again with
62 // the param-substs, but because they are concrete, this
63 // will not do any harm.
64 let sig = tcx.erase_late_bound_regions(&ty.fn_sig());
65 let arg_tys = sig.inputs();
76 ty::InstanceDef::Virtual(def_id, _) => {
77 // We are translating a call back to our def-id, which
78 // trans::mir knows to turn to an actual virtual call.
84 CallKind::Direct(def_id),
88 ty::InstanceDef::ClosureOnceShim { call_once } => {
89 let fn_mut = tcx.lang_items.fn_mut_trait().unwrap();
90 let call_mut = tcx.global_tcx()
91 .associated_items(fn_mut)
92 .find(|it| it.kind == ty::AssociatedKind::Method)
100 CallKind::Direct(call_mut),
104 ty::InstanceDef::DropGlue(def_id, ty) => {
105 build_drop_shim(tcx, ¶m_env, def_id, ty)
107 ty::InstanceDef::Intrinsic(_) => {
108 bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
111 debug!("make_shim({:?}) = untransformed {:?}", instance, result);
112 no_landing_pads::no_landing_pads(tcx, &mut result);
113 simplify::simplify_cfg(&mut result);
114 add_call_guards::add_call_guards(&mut result);
115 debug!("make_shim({:?}) = {:?}", instance, result);
117 let result = tcx.alloc_mir(result);
121 #[derive(Copy, Clone, Debug, PartialEq)]
128 #[derive(Copy, Clone, Debug, PartialEq)]
134 fn temp_decl(mutability: Mutability, ty: Ty, span: Span) -> LocalDecl {
136 mutability, ty, name: None,
137 source_info: SourceInfo { scope: ARGUMENT_VISIBILITY_SCOPE, span },
138 is_user_variable: false
142 fn local_decls_for_sig<'tcx>(sig: &ty::FnSig<'tcx>, span: Span)
143 -> IndexVec<Local, LocalDecl<'tcx>>
145 iter::once(temp_decl(Mutability::Mut, sig.output(), span))
146 .chain(sig.inputs().iter().map(
147 |ity| temp_decl(Mutability::Not, ity, span)))
151 fn build_drop_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
152 param_env: &ty::ParameterEnvironment<'tcx>,
154 ty: Option<Ty<'tcx>>)
157 debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
159 let substs = if let Some(ty) = ty {
160 tcx.mk_substs(iter::once(Kind::from(ty)))
162 param_env.free_substs
164 let fn_ty = tcx.type_of(def_id).subst(tcx, substs);
165 let sig = tcx.erase_late_bound_regions(&fn_ty.fn_sig());
166 let span = tcx.def_span(def_id);
168 let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
170 let return_block = BasicBlock::new(1);
171 let mut blocks = IndexVec::new();
172 let block = |blocks: &mut IndexVec<_, _>, kind| {
173 blocks.push(BasicBlockData {
175 terminator: Some(Terminator { source_info, kind }),
179 block(&mut blocks, TerminatorKind::Goto { target: return_block });
180 block(&mut blocks, TerminatorKind::Return);
182 let mut mir = Mir::new(
184 IndexVec::from_elem_n(
185 VisibilityScopeData { span: span, parent_scope: None }, 1
189 local_decls_for_sig(&sig, span),
195 if let Some(..) = ty {
197 let mut elaborator = DropShimElaborator {
199 patch: MirPatch::new(&mir),
202 let dropee = Lvalue::Local(Local::new(1+0)).deref();
203 let resume_block = elaborator.patch.resume_block();
204 elaborate_drops::elaborate_drop(
216 patch.apply(&mut mir);
222 pub struct DropShimElaborator<'a, 'tcx: 'a> {
224 patch: MirPatch<'tcx>,
225 tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
226 param_env: &'a ty::ParameterEnvironment<'tcx>,
229 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
230 fn fmt(&self, _f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
235 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
238 fn patch(&mut self) -> &mut MirPatch<'tcx> { &mut self.patch }
239 fn mir(&self) -> &'a Mir<'tcx> { self.mir }
240 fn tcx(&self) -> ty::TyCtxt<'a, 'tcx, 'tcx> { self.tcx }
241 fn param_env(&self) -> &'a ty::ParameterEnvironment<'tcx> { self.param_env }
243 fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
244 if let DropFlagMode::Shallow = mode {
251 fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
255 fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {
258 fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
261 fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
264 fn downcast_subpath(&self, _path: Self::Path, _variant: usize) -> Option<Self::Path> {
269 /// Build a "call" shim for `def_id`. The shim calls the
270 /// function specified by `call_kind`, first adjusting its first
271 /// argument according to `rcvr_adjustment`.
273 /// If `untuple_args` is a vec of types, the second argument of the
274 /// function will be untupled as these types.
275 fn build_call_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
276 param_env: &ty::ParameterEnvironment<'tcx>,
278 rcvr_adjustment: Adjustment,
280 untuple_args: Option<&[Ty<'tcx>]>)
283 debug!("build_call_shim(def_id={:?}, rcvr_adjustment={:?}, \
284 call_kind={:?}, untuple_args={:?})",
285 def_id, rcvr_adjustment, call_kind, untuple_args);
287 let fn_ty = tcx.type_of(def_id).subst(tcx, param_env.free_substs);
288 let sig = tcx.erase_late_bound_regions(&fn_ty.fn_sig());
289 let span = tcx.def_span(def_id);
291 debug!("build_call_shim: sig={:?}", sig);
293 let mut local_decls = local_decls_for_sig(&sig, span);
294 let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
296 let rcvr_arg = Local::new(1+0);
297 let rcvr_l = Lvalue::Local(rcvr_arg);
298 let mut statements = vec![];
300 let rcvr = match rcvr_adjustment {
301 Adjustment::Identity => Operand::Consume(rcvr_l),
302 Adjustment::Deref => Operand::Consume(rcvr_l.deref()),
303 Adjustment::RefMut => {
304 // let rcvr = &mut rcvr;
305 let ref_rcvr = local_decls.push(temp_decl(
307 tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
309 mutbl: hir::Mutability::MutMutable
313 statements.push(Statement {
314 source_info: source_info,
315 kind: StatementKind::Assign(
316 Lvalue::Local(ref_rcvr),
317 Rvalue::Ref(tcx.types.re_erased, BorrowKind::Mut, rcvr_l)
320 Operand::Consume(Lvalue::Local(ref_rcvr))
324 let (callee, mut args) = match call_kind {
325 CallKind::Indirect => (rcvr, vec![]),
326 CallKind::Direct(def_id) => (
327 Operand::Constant(Constant {
329 ty: tcx.type_of(def_id).subst(tcx, param_env.free_substs),
330 literal: Literal::Value {
331 value: ConstVal::Function(def_id, param_env.free_substs),
338 if let Some(untuple_args) = untuple_args {
339 args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
340 let arg_lv = Lvalue::Local(Local::new(1+1));
341 Operand::Consume(arg_lv.field(Field::new(i), *ity))
344 args.extend((1..sig.inputs().len()).map(|i| {
345 Operand::Consume(Lvalue::Local(Local::new(1+i)))
349 let mut blocks = IndexVec::new();
350 let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
351 blocks.push(BasicBlockData {
353 terminator: Some(Terminator { source_info, kind }),
359 block(&mut blocks, statements, TerminatorKind::Call {
362 destination: Some((Lvalue::Local(RETURN_POINTER),
363 BasicBlock::new(1))),
364 cleanup: if let Adjustment::RefMut = rcvr_adjustment {
365 Some(BasicBlock::new(3))
371 if let Adjustment::RefMut = rcvr_adjustment {
372 // BB #1 - drop for Self
373 block(&mut blocks, vec![], TerminatorKind::Drop {
374 location: Lvalue::Local(rcvr_arg),
375 target: BasicBlock::new(2),
380 block(&mut blocks, vec![], TerminatorKind::Return, false);
381 if let Adjustment::RefMut = rcvr_adjustment {
382 // BB #3 - drop if closure panics
383 block(&mut blocks, vec![], TerminatorKind::Drop {
384 location: Lvalue::Local(rcvr_arg),
385 target: BasicBlock::new(4),
390 block(&mut blocks, vec![], TerminatorKind::Resume, true);
393 let mut mir = Mir::new(
395 IndexVec::from_elem_n(
396 VisibilityScopeData { span: span, parent_scope: None }, 1
405 if let Abi::RustCall = sig.abi {
406 mir.spread_arg = Some(Local::new(sig.inputs().len()));
411 pub fn build_adt_ctor<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
412 ctor_id: ast::NodeId,
413 fields: &[hir::StructField],
415 -> (Mir<'tcx>, MirSource)
418 let def_id = tcx.hir.local_def_id(ctor_id);
419 let sig = match tcx.type_of(def_id).sty {
420 ty::TyFnDef(_, _, fty) => tcx.no_late_bound_regions(&fty)
421 .expect("LBR in ADT constructor signature"),
422 _ => bug!("unexpected type for ctor {:?}", def_id)
424 let sig = tcx.erase_regions(&sig);
426 let (adt_def, substs) = match sig.output().sty {
427 ty::TyAdt(adt_def, substs) => (adt_def, substs),
428 _ => bug!("unexpected type for ADT ctor {:?}", sig.output())
431 debug!("build_ctor: def_id={:?} sig={:?} fields={:?}", def_id, sig, fields);
433 let local_decls = local_decls_for_sig(&sig, span);
435 let source_info = SourceInfo {
437 scope: ARGUMENT_VISIBILITY_SCOPE
440 let variant_no = if adt_def.is_enum() {
441 adt_def.variant_index_with_id(def_id)
446 // return = ADT(arg0, arg1, ...); return
447 let start_block = BasicBlockData {
448 statements: vec![Statement {
449 source_info: source_info,
450 kind: StatementKind::Assign(
451 Lvalue::Local(RETURN_POINTER),
453 AggregateKind::Adt(adt_def, variant_no, substs, None),
454 (1..sig.inputs().len()+1).map(|i| {
455 Operand::Consume(Lvalue::Local(Local::new(i)))
460 terminator: Some(Terminator {
461 source_info: source_info,
462 kind: TerminatorKind::Return,
468 IndexVec::from_elem_n(start_block, 1),
469 IndexVec::from_elem_n(
470 VisibilityScopeData { span: span, parent_scope: None }, 1
479 (mir, MirSource::Fn(ctor_id))