]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/shim.rs
More methods for str boxes.
[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, span: Span) -> LocalDecl {
141     LocalDecl {
142         mutability, ty, name: None,
143         source_info: SourceInfo { scope: ARGUMENT_VISIBILITY_SCOPE, span },
144         is_user_variable: false
145     }
146 }
147
148 fn local_decls_for_sig<'tcx>(sig: &ty::FnSig<'tcx>, span: Span)
149     -> IndexVec<Local, LocalDecl<'tcx>>
150 {
151     iter::once(temp_decl(Mutability::Mut, sig.output(), span))
152         .chain(sig.inputs().iter().map(
153             |ity| temp_decl(Mutability::Not, ity, span)))
154         .collect()
155 }
156
157 fn build_drop_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
158                              param_env: &ty::ParameterEnvironment<'tcx>,
159                              def_id: DefId,
160                              ty: Option<Ty<'tcx>>)
161                              -> Mir<'tcx>
162 {
163     debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
164
165     let substs = if let Some(ty) = ty {
166         tcx.mk_substs(iter::once(Kind::from(ty)))
167     } else {
168         param_env.free_substs
169     };
170     let fn_ty = tcx.item_type(def_id).subst(tcx, substs);
171     let sig = tcx.erase_late_bound_regions(&fn_ty.fn_sig());
172     let span = tcx.def_span(def_id);
173
174     let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
175
176     let return_block = BasicBlock::new(1);
177     let mut blocks = IndexVec::new();
178     let block = |blocks: &mut IndexVec<_, _>, kind| {
179         blocks.push(BasicBlockData {
180             statements: vec![],
181             terminator: Some(Terminator { source_info, kind }),
182             is_cleanup: false
183         })
184     };
185     block(&mut blocks, TerminatorKind::Goto { target: return_block });
186     block(&mut blocks, TerminatorKind::Return);
187
188     let mut mir = Mir::new(
189         blocks,
190         IndexVec::from_elem_n(
191             VisibilityScopeData { span: span, parent_scope: None }, 1
192         ),
193         IndexVec::new(),
194         sig.output(),
195         local_decls_for_sig(&sig, span),
196         sig.inputs().len(),
197         vec![],
198         span
199     );
200
201     if let Some(..) = ty {
202         let patch = {
203             let mut elaborator = DropShimElaborator {
204                 mir: &mir,
205                 patch: MirPatch::new(&mir),
206                 tcx, param_env
207             };
208             let dropee = Lvalue::Local(Local::new(1+0)).deref();
209             let resume_block = elaborator.patch.resume_block();
210             elaborate_drops::elaborate_drop(
211                 &mut elaborator,
212                 source_info,
213                 false,
214                 &dropee,
215                 (),
216                 return_block,
217                 Some(resume_block),
218                 START_BLOCK
219             );
220             elaborator.patch
221         };
222         patch.apply(&mut mir);
223     }
224
225     mir
226 }
227
228 pub struct DropShimElaborator<'a, 'tcx: 'a> {
229     mir: &'a Mir<'tcx>,
230     patch: MirPatch<'tcx>,
231     tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
232     param_env: &'a ty::ParameterEnvironment<'tcx>,
233 }
234
235 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
236     fn fmt(&self, _f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
237         Ok(())
238     }
239 }
240
241 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
242     type Path = ();
243
244     fn patch(&mut self) -> &mut MirPatch<'tcx> { &mut self.patch }
245     fn mir(&self) -> &'a Mir<'tcx> { self.mir }
246     fn tcx(&self) -> ty::TyCtxt<'a, 'tcx, 'tcx> { self.tcx }
247     fn param_env(&self) -> &'a ty::ParameterEnvironment<'tcx> { self.param_env }
248
249     fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
250         if let DropFlagMode::Shallow = mode {
251             DropStyle::Static
252         } else {
253             DropStyle::Open
254         }
255     }
256
257     fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
258         None
259     }
260
261     fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {
262     }
263
264     fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
265         None
266     }
267     fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
268         None
269     }
270     fn downcast_subpath(&self, _path: Self::Path, _variant: usize) -> Option<Self::Path> {
271         Some(())
272     }
273 }
274
275 /// Build a "call" shim for `def_id`. The shim calls the
276 /// function specified by `call_kind`, first adjusting its first
277 /// argument according to `rcvr_adjustment`.
278 ///
279 /// If `untuple_args` is a vec of types, the second argument of the
280 /// function will be untupled as these types.
281 fn build_call_shim<'a, 'tcx>(tcx: ty::TyCtxt<'a, 'tcx, 'tcx>,
282                              param_env: &ty::ParameterEnvironment<'tcx>,
283                              def_id: DefId,
284                              rcvr_adjustment: Adjustment,
285                              call_kind: CallKind,
286                              untuple_args: Option<&[Ty<'tcx>]>)
287                              -> Mir<'tcx>
288 {
289     debug!("build_call_shim(def_id={:?}, rcvr_adjustment={:?}, \
290             call_kind={:?}, untuple_args={:?})",
291            def_id, rcvr_adjustment, call_kind, untuple_args);
292
293     let fn_ty = tcx.item_type(def_id).subst(tcx, param_env.free_substs);
294     let sig = tcx.erase_late_bound_regions(&fn_ty.fn_sig());
295     let span = tcx.def_span(def_id);
296
297     debug!("build_call_shim: sig={:?}", sig);
298
299     let mut local_decls = local_decls_for_sig(&sig, span);
300     let source_info = SourceInfo { span, scope: ARGUMENT_VISIBILITY_SCOPE };
301
302     let rcvr_arg = Local::new(1+0);
303     let rcvr_l = Lvalue::Local(rcvr_arg);
304     let mut statements = vec![];
305
306     let rcvr = match rcvr_adjustment {
307         Adjustment::Identity => Operand::Consume(rcvr_l),
308         Adjustment::Deref => Operand::Consume(rcvr_l.deref()),
309         Adjustment::RefMut => {
310             // let rcvr = &mut rcvr;
311             let re_erased = tcx.mk_region(ty::ReErased);
312             let ref_rcvr = local_decls.push(temp_decl(
313                 Mutability::Not,
314                 tcx.mk_ref(re_erased, ty::TypeAndMut {
315                     ty: sig.inputs()[0],
316                     mutbl: hir::Mutability::MutMutable
317                 }),
318                 span
319             ));
320             statements.push(Statement {
321                 source_info: source_info,
322                 kind: StatementKind::Assign(
323                     Lvalue::Local(ref_rcvr),
324                     Rvalue::Ref(re_erased, BorrowKind::Mut, rcvr_l)
325                 )
326             });
327             Operand::Consume(Lvalue::Local(ref_rcvr))
328         }
329     };
330
331     let (callee, mut args) = match call_kind {
332         CallKind::Indirect => (rcvr, vec![]),
333         CallKind::Direct(def_id) => (
334             Operand::Constant(Constant {
335                 span: span,
336                 ty: tcx.item_type(def_id).subst(tcx, param_env.free_substs),
337                 literal: Literal::Value {
338                     value: ConstVal::Function(def_id, param_env.free_substs),
339                 },
340             }),
341             vec![rcvr]
342         )
343     };
344
345     if let Some(untuple_args) = untuple_args {
346         args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
347             let arg_lv = Lvalue::Local(Local::new(1+1));
348             Operand::Consume(arg_lv.field(Field::new(i), *ity))
349         }));
350     } else {
351         args.extend((1..sig.inputs().len()).map(|i| {
352             Operand::Consume(Lvalue::Local(Local::new(1+i)))
353         }));
354     }
355
356     let mut blocks = IndexVec::new();
357     let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
358         blocks.push(BasicBlockData {
359             statements,
360             terminator: Some(Terminator { source_info, kind }),
361             is_cleanup
362         })
363     };
364
365     // BB #0
366     block(&mut blocks, statements, TerminatorKind::Call {
367         func: callee,
368         args: args,
369         destination: Some((Lvalue::Local(RETURN_POINTER),
370                            BasicBlock::new(1))),
371         cleanup: if let Adjustment::RefMut = rcvr_adjustment {
372             Some(BasicBlock::new(3))
373         } else {
374             None
375         }
376     }, false);
377
378     if let Adjustment::RefMut = rcvr_adjustment {
379         // BB #1 - drop for Self
380         block(&mut blocks, vec![], TerminatorKind::Drop {
381             location: Lvalue::Local(rcvr_arg),
382             target: BasicBlock::new(2),
383             unwind: None
384         }, false);
385     }
386     // BB #1/#2 - return
387     block(&mut blocks, vec![], TerminatorKind::Return, false);
388     if let Adjustment::RefMut = rcvr_adjustment {
389         // BB #3 - drop if closure panics
390         block(&mut blocks, vec![], TerminatorKind::Drop {
391             location: Lvalue::Local(rcvr_arg),
392             target: BasicBlock::new(4),
393             unwind: None
394         }, true);
395
396         // BB #4 - resume
397         block(&mut blocks, vec![], TerminatorKind::Resume, true);
398     }
399
400     let mut mir = Mir::new(
401         blocks,
402         IndexVec::from_elem_n(
403             VisibilityScopeData { span: span, parent_scope: None }, 1
404         ),
405         IndexVec::new(),
406         sig.output(),
407         local_decls,
408         sig.inputs().len(),
409         vec![],
410         span
411     );
412     if let Abi::RustCall = sig.abi {
413         mir.spread_arg = Some(Local::new(sig.inputs().len()));
414     }
415     mir
416 }
417
418 pub fn build_adt_ctor<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
419                                       ctor_id: ast::NodeId,
420                                       fields: &[hir::StructField],
421                                       span: Span)
422                                       -> (Mir<'tcx>, MirSource)
423 {
424     let tcx = infcx.tcx;
425     let def_id = tcx.hir.local_def_id(ctor_id);
426     let sig = match tcx.item_type(def_id).sty {
427         ty::TyFnDef(_, _, fty) => tcx.no_late_bound_regions(&fty)
428             .expect("LBR in ADT constructor signature"),
429         _ => bug!("unexpected type for ctor {:?}", def_id)
430     };
431     let sig = tcx.erase_regions(&sig);
432
433     let (adt_def, substs) = match sig.output().sty {
434         ty::TyAdt(adt_def, substs) => (adt_def, substs),
435         _ => bug!("unexpected type for ADT ctor {:?}", sig.output())
436     };
437
438     debug!("build_ctor: def_id={:?} sig={:?} fields={:?}", def_id, sig, fields);
439
440     let local_decls = local_decls_for_sig(&sig, span);
441
442     let source_info = SourceInfo {
443         span: span,
444         scope: ARGUMENT_VISIBILITY_SCOPE
445     };
446
447     let variant_no = if adt_def.is_enum() {
448         adt_def.variant_index_with_id(def_id)
449     } else {
450         0
451     };
452
453     // return = ADT(arg0, arg1, ...); return
454     let start_block = BasicBlockData {
455         statements: vec![Statement {
456             source_info: source_info,
457             kind: StatementKind::Assign(
458                 Lvalue::Local(RETURN_POINTER),
459                 Rvalue::Aggregate(
460                     AggregateKind::Adt(adt_def, variant_no, substs, None),
461                     (1..sig.inputs().len()+1).map(|i| {
462                         Operand::Consume(Lvalue::Local(Local::new(i)))
463                     }).collect()
464                 )
465             )
466         }],
467         terminator: Some(Terminator {
468             source_info: source_info,
469             kind: TerminatorKind::Return,
470         }),
471         is_cleanup: false
472     };
473
474     let mir = Mir::new(
475         IndexVec::from_elem_n(start_block, 1),
476         IndexVec::from_elem_n(
477             VisibilityScopeData { span: span, parent_scope: None }, 1
478         ),
479         IndexVec::new(),
480         sig.output(),
481         local_decls,
482         sig.inputs().len(),
483         vec![],
484         span
485     );
486     (mir, MirSource::Fn(ctor_id))
487 }