]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/shim.rs
Fix invalid associated type rendering in rustdoc
[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::region::ROOT_CODE_EXTENT;
15 use rustc::middle::const_val::ConstVal;
16 use rustc::mir::*;
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;
21
22 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
23
24 use syntax::abi::Abi;
25 use syntax::ast;
26 use syntax_pos::Span;
27
28 use std::cell::RefCell;
29 use std::fmt;
30 use std::iter;
31 use std::mem;
32
33 use transform::{add_call_guards, no_landing_pads, simplify};
34 use util::elaborate_drops::{self, DropElaborator, DropStyle, DropFlagMode};
35 use util::patch::MirPatch;
36
37 pub fn provide(providers: &mut Providers) {
38     providers.mir_shims = make_shim;
39 }
40
41 fn make_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
42                        instance: ty::InstanceDef<'tcx>)
43                        -> &'tcx RefCell<Mir<'tcx>>
44 {
45     debug!("make_shim({:?})", instance);
46     let did = instance.def_id();
47     let span = tcx.def_span(did);
48     let param_env =
49         tcx.construct_parameter_environment(span, did, ROOT_CODE_EXTENT);
50
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)
61             };
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();
70
71             build_call_shim(
72                 tcx,
73                 &param_env,
74                 def_id,
75                 adjustment,
76                 CallKind::Indirect,
77                 Some(arg_tys)
78             )
79         }
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.
83             build_call_shim(
84                 tcx,
85                 &param_env,
86                 def_id,
87                 Adjustment::Identity,
88                 CallKind::Direct(def_id),
89                 None
90             )
91         }
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)
97                 .unwrap().def_id;
98
99             build_call_shim(
100                 tcx,
101                 &param_env,
102                 call_once,
103                 Adjustment::RefMut,
104                 CallKind::Direct(call_mut),
105                 None
106             )
107         }
108         ty::InstanceDef::DropGlue(def_id, ty) => {
109             build_drop_shim(tcx, &param_env, def_id, ty)
110         }
111         ty::InstanceDef::Intrinsic(_) => {
112             bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
113         }
114     };
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);
120
121     let result = tcx.alloc_mir(result);
122     // Perma-borrow MIR from shims to prevent mutation.
123     mem::forget(result.borrow());
124     result
125 }
126
127 #[derive(Copy, Clone, Debug, PartialEq)]
128 enum Adjustment {
129     Identity,
130     Deref,
131     RefMut,
132 }
133
134 #[derive(Copy, Clone, Debug, PartialEq)]
135 enum CallKind {
136     Indirect,
137     Direct(DefId),
138 }
139
140 fn temp_decl(mutability: Mutability, ty: Ty) -> LocalDecl {
141     LocalDecl { mutability, ty, name: None, source_info: None }
142 }
143
144 fn local_decls_for_sig<'tcx>(sig: &ty::FnSig<'tcx>)
145     -> IndexVec<Local, LocalDecl<'tcx>>
146 {
147     iter::once(temp_decl(Mutability::Mut, sig.output()))
148         .chain(sig.inputs().iter().map(
149             |ity| temp_decl(Mutability::Not, ity)))
150         .collect()
151 }
152
153 fn build_drop_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
154                              param_env: &ty::ParameterEnvironment<'tcx>,
155                              def_id: DefId,
156                              ty: Option<Ty<'tcx>>)
157                              -> Mir<'tcx>
158 {
159     debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
160
161     let substs = if let Some(ty) = ty {
162         tcx.mk_substs(iter::once(Kind::from(ty)))
163     } else {
164         param_env.free_substs
165     };
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);
169
170     let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
171
172     let return_block = BasicBlock::new(1);
173     let mut blocks = IndexVec::new();
174     let block = |blocks: &mut IndexVec<_, _>, kind| {
175         blocks.push(BasicBlockData {
176             statements: vec![],
177             terminator: Some(Terminator { source_info, kind }),
178             is_cleanup: false
179         })
180     };
181     block(&mut blocks, TerminatorKind::Goto { target: return_block });
182     block(&mut blocks, TerminatorKind::Return);
183
184     let mut mir = Mir::new(
185         blocks,
186         IndexVec::from_elem_n(
187             VisibilityScopeData { span: span, parent_scope: None }, 1
188         ),
189         IndexVec::new(),
190         sig.output(),
191         local_decls_for_sig(&sig),
192         sig.inputs().len(),
193         vec![],
194         span
195     );
196
197     if let Some(..) = ty {
198         let patch = {
199             let mut elaborator = DropShimElaborator {
200                 mir: &mir,
201                 patch: MirPatch::new(&mir),
202                 tcx, param_env
203             };
204             let dropee = Lvalue::Projection(
205                 box Projection {
206                     base: Lvalue::Local(Local::new(1+0)),
207                     elem: ProjectionElem::Deref
208                 }
209                 );
210             let resume_block = elaborator.patch.resume_block();
211             elaborate_drops::elaborate_drop(
212                 &mut elaborator,
213                 source_info,
214                 false,
215                 &dropee,
216                 (),
217                 return_block,
218                 Some(resume_block),
219                 START_BLOCK
220             );
221             elaborator.patch
222         };
223         patch.apply(&mut mir);
224     }
225
226     mir
227 }
228
229 pub struct DropShimElaborator<'a, 'tcx: 'a> {
230     mir: &'a Mir<'tcx>,
231     patch: MirPatch<'tcx>,
232     tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
233     param_env: &'a ty::ParameterEnvironment<'tcx>,
234 }
235
236 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
237     fn fmt(&self, _f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
238         Ok(())
239     }
240 }
241
242 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
243     type Path = ();
244
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 }
249
250     fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
251         if let DropFlagMode::Shallow = mode {
252             DropStyle::Static
253         } else {
254             DropStyle::Open
255         }
256     }
257
258     fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
259         None
260     }
261
262     fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {
263     }
264
265     fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
266         None
267     }
268     fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
269         None
270     }
271     fn downcast_subpath(&self, _path: Self::Path, _variant: usize) -> Option<Self::Path> {
272         Some(())
273     }
274 }
275
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`.
279 ///
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>,
284                              def_id: DefId,
285                              rcvr_adjustment: Adjustment,
286                              call_kind: CallKind,
287                              untuple_args: Option<&[Ty<'tcx>]>)
288                              -> Mir<'tcx>
289 {
290     debug!("build_call_shim(def_id={:?}, rcvr_adjustment={:?}, \
291             call_kind={:?}, untuple_args={:?})",
292            def_id, rcvr_adjustment, call_kind, untuple_args);
293
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);
297
298     debug!("build_call_shim: sig={:?}", sig);
299
300     let mut local_decls = local_decls_for_sig(&sig);
301     let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
302
303     let rcvr_arg = Local::new(1+0);
304     let rcvr_l = Lvalue::Local(rcvr_arg);
305     let mut statements = vec![];
306
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 }
311         )),
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(
316                 Mutability::Not,
317                 tcx.mk_ref(re_erased, ty::TypeAndMut {
318                     ty: sig.inputs()[0],
319                     mutbl: hir::Mutability::MutMutable
320                 })
321             ));
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)
327                 )
328             });
329             Operand::Consume(Lvalue::Local(ref_rcvr))
330         }
331     };
332
333     let (callee, mut args) = match call_kind {
334         CallKind::Indirect => (rcvr, vec![]),
335         CallKind::Direct(def_id) => (
336             Operand::Constant(Constant {
337                 span: span,
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),
341                 },
342             }),
343             vec![rcvr]
344         )
345     };
346
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 {
351                 base: arg_lv,
352                 elem: ProjectionElem::Field(Field::new(i), *ity)
353             }))
354         }));
355     } else {
356         args.extend((1..sig.inputs().len()).map(|i| {
357             Operand::Consume(Lvalue::Local(Local::new(1+i)))
358         }));
359     }
360
361     let mut blocks = IndexVec::new();
362     let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
363         blocks.push(BasicBlockData {
364             statements,
365             terminator: Some(Terminator { source_info, kind }),
366             is_cleanup
367         })
368     };
369
370     // BB #0
371     block(&mut blocks, statements, TerminatorKind::Call {
372         func: callee,
373         args: args,
374         destination: Some((Lvalue::Local(RETURN_POINTER),
375                            BasicBlock::new(1))),
376         cleanup: if let Adjustment::RefMut = rcvr_adjustment {
377             Some(BasicBlock::new(3))
378         } else {
379             None
380         }
381     }, false);
382
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),
388             unwind: None
389         }, false);
390     }
391     // BB #1/#2 - return
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),
398             unwind: None
399         }, true);
400
401         // BB #4 - resume
402         block(&mut blocks, vec![], TerminatorKind::Resume, true);
403     }
404
405     let mut mir = Mir::new(
406         blocks,
407         IndexVec::from_elem_n(
408             VisibilityScopeData { span: span, parent_scope: None }, 1
409         ),
410         IndexVec::new(),
411         sig.output(),
412         local_decls,
413         sig.inputs().len(),
414         vec![],
415         span
416     );
417     if let Abi::RustCall = sig.abi {
418         mir.spread_arg = Some(Local::new(sig.inputs().len()));
419     }
420     mir
421 }
422
423 pub fn build_adt_ctor<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
424                                       ctor_id: ast::NodeId,
425                                       fields: &[hir::StructField],
426                                       span: Span)
427                                       -> (Mir<'tcx>, MirSource)
428 {
429     let tcx = infcx.tcx;
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)
435     };
436     let sig = tcx.erase_regions(&sig);
437
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())
441     };
442
443     debug!("build_ctor: def_id={:?} sig={:?} fields={:?}", def_id, sig, fields);
444
445     let local_decls = local_decls_for_sig(&sig);
446
447     let source_info = SourceInfo {
448         span: span,
449         scope: ARGUMENT_VISIBILITY_SCOPE
450     };
451
452     let variant_no = if adt_def.is_enum() {
453         adt_def.variant_index_with_id(def_id)
454     } else {
455         0
456     };
457
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),
464                 Rvalue::Aggregate(
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)))
468                     }).collect()
469                 )
470             )
471         }],
472         terminator: Some(Terminator {
473             source_info: source_info,
474             kind: TerminatorKind::Return,
475         }),
476         is_cleanup: false
477     };
478
479     let mir = Mir::new(
480         IndexVec::from_elem_n(start_block, 1),
481         IndexVec::from_elem_n(
482             VisibilityScopeData { span: span, parent_scope: None }, 1
483         ),
484         IndexVec::new(),
485         sig.output(),
486         local_decls,
487         sig.inputs().len(),
488         vec![],
489         span
490     );
491     (mir, MirSource::Fn(ctor_id))
492 }