]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/shim.rs
a899c69ca150acad42fc4f524dda2667e2687281
[rust.git] / src / librustc_mir / shim.rs
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.
4 //
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.
10
11 use rustc::hir;
12 use rustc::hir::def_id::DefId;
13 use rustc::infer;
14 use rustc::middle::const_val::ConstVal;
15 use rustc::mir::*;
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;
20
21 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
22
23 use syntax::abi::Abi;
24 use syntax::ast;
25 use syntax_pos::Span;
26
27 use std::fmt;
28 use std::iter;
29
30 use transform::{add_call_guards, no_landing_pads, simplify};
31 use util::elaborate_drops::{self, DropElaborator, DropStyle, DropFlagMode};
32 use util::patch::MirPatch;
33
34 pub fn provide(providers: &mut Providers) {
35     providers.mir_shims = make_shim;
36 }
37
38 fn make_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
39                        instance: ty::InstanceDef<'tcx>)
40                        -> &'tcx Mir<'tcx>
41 {
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);
46
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)
57             };
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();
66
67             build_call_shim(
68                 tcx,
69                 &param_env,
70                 def_id,
71                 adjustment,
72                 CallKind::Indirect,
73                 Some(arg_tys)
74             )
75         }
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.
79             build_call_shim(
80                 tcx,
81                 &param_env,
82                 def_id,
83                 Adjustment::Identity,
84                 CallKind::Direct(def_id),
85                 None
86             )
87         }
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)
93                 .unwrap().def_id;
94
95             build_call_shim(
96                 tcx,
97                 &param_env,
98                 call_once,
99                 Adjustment::RefMut,
100                 CallKind::Direct(call_mut),
101                 None
102             )
103         }
104         ty::InstanceDef::DropGlue(def_id, ty) => {
105             build_drop_shim(tcx, &param_env, def_id, ty)
106         }
107         ty::InstanceDef::Intrinsic(_) => {
108             bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
109         }
110     };
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);
116
117     let result = tcx.alloc_mir(result);
118     result
119 }
120
121 #[derive(Copy, Clone, Debug, PartialEq)]
122 enum Adjustment {
123     Identity,
124     Deref,
125     RefMut,
126 }
127
128 #[derive(Copy, Clone, Debug, PartialEq)]
129 enum CallKind {
130     Indirect,
131     Direct(DefId),
132 }
133
134 fn temp_decl(mutability: Mutability, ty: Ty, span: Span) -> LocalDecl {
135     LocalDecl {
136         mutability, ty, name: None,
137         source_info: SourceInfo { scope: ARGUMENT_VISIBILITY_SCOPE, span },
138         is_user_variable: false
139     }
140 }
141
142 fn local_decls_for_sig<'tcx>(sig: &ty::FnSig<'tcx>, span: Span)
143     -> IndexVec<Local, LocalDecl<'tcx>>
144 {
145     iter::once(temp_decl(Mutability::Mut, sig.output(), span))
146         .chain(sig.inputs().iter().map(
147             |ity| temp_decl(Mutability::Not, ity, span)))
148         .collect()
149 }
150
151 fn build_drop_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
152                              param_env: &ty::ParameterEnvironment<'tcx>,
153                              def_id: DefId,
154                              ty: Option<Ty<'tcx>>)
155                              -> Mir<'tcx>
156 {
157     debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
158
159     let substs = if let Some(ty) = ty {
160         tcx.mk_substs(iter::once(Kind::from(ty)))
161     } else {
162         param_env.free_substs
163     };
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);
167
168     let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
169
170     let return_block = BasicBlock::new(1);
171     let mut blocks = IndexVec::new();
172     let block = |blocks: &mut IndexVec<_, _>, kind| {
173         blocks.push(BasicBlockData {
174             statements: vec![],
175             terminator: Some(Terminator { source_info, kind }),
176             is_cleanup: false
177         })
178     };
179     block(&mut blocks, TerminatorKind::Goto { target: return_block });
180     block(&mut blocks, TerminatorKind::Return);
181
182     let mut mir = Mir::new(
183         blocks,
184         IndexVec::from_elem_n(
185             VisibilityScopeData { span: span, parent_scope: None }, 1
186         ),
187         IndexVec::new(),
188         sig.output(),
189         local_decls_for_sig(&sig, span),
190         sig.inputs().len(),
191         vec![],
192         span
193     );
194
195     if let Some(..) = ty {
196         let patch = {
197             let mut elaborator = DropShimElaborator {
198                 mir: &mir,
199                 patch: MirPatch::new(&mir),
200                 tcx, param_env
201             };
202             let dropee = Lvalue::Local(Local::new(1+0)).deref();
203             let resume_block = elaborator.patch.resume_block();
204             elaborate_drops::elaborate_drop(
205                 &mut elaborator,
206                 source_info,
207                 false,
208                 &dropee,
209                 (),
210                 return_block,
211                 Some(resume_block),
212                 START_BLOCK
213             );
214             elaborator.patch
215         };
216         patch.apply(&mut mir);
217     }
218
219     mir
220 }
221
222 pub struct DropShimElaborator<'a, 'tcx: 'a> {
223     mir: &'a Mir<'tcx>,
224     patch: MirPatch<'tcx>,
225     tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
226     param_env: &'a ty::ParameterEnvironment<'tcx>,
227 }
228
229 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
230     fn fmt(&self, _f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
231         Ok(())
232     }
233 }
234
235 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
236     type Path = ();
237
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 }
242
243     fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
244         if let DropFlagMode::Shallow = mode {
245             DropStyle::Static
246         } else {
247             DropStyle::Open
248         }
249     }
250
251     fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
252         None
253     }
254
255     fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {
256     }
257
258     fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
259         None
260     }
261     fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
262         None
263     }
264     fn downcast_subpath(&self, _path: Self::Path, _variant: usize) -> Option<Self::Path> {
265         Some(())
266     }
267 }
268
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`.
272 ///
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>,
277                              def_id: DefId,
278                              rcvr_adjustment: Adjustment,
279                              call_kind: CallKind,
280                              untuple_args: Option<&[Ty<'tcx>]>)
281                              -> Mir<'tcx>
282 {
283     debug!("build_call_shim(def_id={:?}, rcvr_adjustment={:?}, \
284             call_kind={:?}, untuple_args={:?})",
285            def_id, rcvr_adjustment, call_kind, untuple_args);
286
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);
290
291     debug!("build_call_shim: sig={:?}", sig);
292
293     let mut local_decls = local_decls_for_sig(&sig, span);
294     let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
295
296     let rcvr_arg = Local::new(1+0);
297     let rcvr_l = Lvalue::Local(rcvr_arg);
298     let mut statements = vec![];
299
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(
306                 Mutability::Not,
307                 tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
308                     ty: sig.inputs()[0],
309                     mutbl: hir::Mutability::MutMutable
310                 }),
311                 span
312             ));
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)
318                 )
319             });
320             Operand::Consume(Lvalue::Local(ref_rcvr))
321         }
322     };
323
324     let (callee, mut args) = match call_kind {
325         CallKind::Indirect => (rcvr, vec![]),
326         CallKind::Direct(def_id) => (
327             Operand::Constant(Constant {
328                 span: span,
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),
332                 },
333             }),
334             vec![rcvr]
335         )
336     };
337
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))
342         }));
343     } else {
344         args.extend((1..sig.inputs().len()).map(|i| {
345             Operand::Consume(Lvalue::Local(Local::new(1+i)))
346         }));
347     }
348
349     let mut blocks = IndexVec::new();
350     let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
351         blocks.push(BasicBlockData {
352             statements,
353             terminator: Some(Terminator { source_info, kind }),
354             is_cleanup
355         })
356     };
357
358     // BB #0
359     block(&mut blocks, statements, TerminatorKind::Call {
360         func: callee,
361         args: args,
362         destination: Some((Lvalue::Local(RETURN_POINTER),
363                            BasicBlock::new(1))),
364         cleanup: if let Adjustment::RefMut = rcvr_adjustment {
365             Some(BasicBlock::new(3))
366         } else {
367             None
368         }
369     }, false);
370
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),
376             unwind: None
377         }, false);
378     }
379     // BB #1/#2 - return
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),
386             unwind: None
387         }, true);
388
389         // BB #4 - resume
390         block(&mut blocks, vec![], TerminatorKind::Resume, true);
391     }
392
393     let mut mir = Mir::new(
394         blocks,
395         IndexVec::from_elem_n(
396             VisibilityScopeData { span: span, parent_scope: None }, 1
397         ),
398         IndexVec::new(),
399         sig.output(),
400         local_decls,
401         sig.inputs().len(),
402         vec![],
403         span
404     );
405     if let Abi::RustCall = sig.abi {
406         mir.spread_arg = Some(Local::new(sig.inputs().len()));
407     }
408     mir
409 }
410
411 pub fn build_adt_ctor<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
412                                       ctor_id: ast::NodeId,
413                                       fields: &[hir::StructField],
414                                       span: Span)
415                                       -> (Mir<'tcx>, MirSource)
416 {
417     let tcx = infcx.tcx;
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)
423     };
424     let sig = tcx.erase_regions(&sig);
425
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())
429     };
430
431     debug!("build_ctor: def_id={:?} sig={:?} fields={:?}", def_id, sig, fields);
432
433     let local_decls = local_decls_for_sig(&sig, span);
434
435     let source_info = SourceInfo {
436         span: span,
437         scope: ARGUMENT_VISIBILITY_SCOPE
438     };
439
440     let variant_no = if adt_def.is_enum() {
441         adt_def.variant_index_with_id(def_id)
442     } else {
443         0
444     };
445
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),
452                 Rvalue::Aggregate(
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)))
456                     }).collect()
457                 )
458             )
459         }],
460         terminator: Some(Terminator {
461             source_info: source_info,
462             kind: TerminatorKind::Return,
463         }),
464         is_cleanup: false
465     };
466
467     let mir = Mir::new(
468         IndexVec::from_elem_n(start_block, 1),
469         IndexVec::from_elem_n(
470             VisibilityScopeData { span: span, parent_scope: None }, 1
471         ),
472         IndexVec::new(),
473         sig.output(),
474         local_decls,
475         sig.inputs().len(),
476         vec![],
477         span
478     );
479     (mir, MirSource::Fn(ctor_id))
480 }