]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/shim.rs
Remove licenses
[rust.git] / src / librustc_mir / shim.rs
1 use rustc::hir;
2 use rustc::hir::def_id::DefId;
3 use rustc::infer;
4 use rustc::mir::*;
5 use rustc::ty::{self, Ty, TyCtxt, GenericParamDefKind};
6 use rustc::ty::layout::VariantIdx;
7 use rustc::ty::subst::{Subst, Substs};
8 use rustc::ty::query::Providers;
9
10 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
11
12 use rustc_target::spec::abi::Abi;
13 use syntax::ast;
14 use syntax_pos::Span;
15
16 use std::fmt;
17 use std::iter;
18
19 use transform::{add_moves_for_packed_drops, add_call_guards};
20 use transform::{remove_noop_landing_pads, no_landing_pads, simplify};
21 use util::elaborate_drops::{self, DropElaborator, DropStyle, DropFlagMode};
22 use util::patch::MirPatch;
23
24 pub fn provide(providers: &mut Providers) {
25     providers.mir_shims = make_shim;
26 }
27
28 fn make_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
29                        instance: ty::InstanceDef<'tcx>)
30                        -> &'tcx Mir<'tcx>
31 {
32     debug!("make_shim({:?})", instance);
33
34     let mut result = match instance {
35         ty::InstanceDef::Item(..) =>
36             bug!("item {:?} passed to make_shim", instance),
37         ty::InstanceDef::VtableShim(def_id) => {
38             build_call_shim(
39                 tcx,
40                 def_id,
41                 Adjustment::DerefMove,
42                 CallKind::Direct(def_id),
43                 None,
44             )
45         }
46         ty::InstanceDef::FnPtrShim(def_id, ty) => {
47             let trait_ = tcx.trait_of_item(def_id).unwrap();
48             let adjustment = match tcx.lang_items().fn_trait_kind(trait_) {
49                 Some(ty::ClosureKind::FnOnce) => Adjustment::Identity,
50                 Some(ty::ClosureKind::FnMut) |
51                 Some(ty::ClosureKind::Fn) => Adjustment::Deref,
52                 None => bug!("fn pointer {:?} is not an fn", ty)
53             };
54             // HACK: we need the "real" argument types for the MIR,
55             // but because our substs are (Self, Args), where Args
56             // is a tuple, we must include the *concrete* argument
57             // types in the MIR. They will be substituted again with
58             // the param-substs, but because they are concrete, this
59             // will not do any harm.
60             let sig = tcx.erase_late_bound_regions(&ty.fn_sig(tcx));
61             let arg_tys = sig.inputs();
62
63             build_call_shim(
64                 tcx,
65                 def_id,
66                 adjustment,
67                 CallKind::Indirect,
68                 Some(arg_tys)
69             )
70         }
71         ty::InstanceDef::Virtual(def_id, _) => {
72             // We are generating a call back to our def-id, which the
73             // codegen backend knows to turn to an actual virtual call.
74             build_call_shim(
75                 tcx,
76                 def_id,
77                 Adjustment::Identity,
78                 CallKind::Direct(def_id),
79                 None
80             )
81         }
82         ty::InstanceDef::ClosureOnceShim { call_once } => {
83             let fn_mut = tcx.lang_items().fn_mut_trait().unwrap();
84             let call_mut = tcx.global_tcx()
85                 .associated_items(fn_mut)
86                 .find(|it| it.kind == ty::AssociatedKind::Method)
87                 .unwrap().def_id;
88
89             build_call_shim(
90                 tcx,
91                 call_once,
92                 Adjustment::RefMut,
93                 CallKind::Direct(call_mut),
94                 None
95             )
96         }
97         ty::InstanceDef::DropGlue(def_id, ty) => {
98             build_drop_shim(tcx, def_id, ty)
99         }
100         ty::InstanceDef::CloneShim(def_id, ty) => {
101             let name = tcx.item_name(def_id);
102             if name == "clone" {
103                 build_clone_shim(tcx, def_id, ty)
104             } else if name == "clone_from" {
105                 debug!("make_shim({:?}: using default trait implementation", instance);
106                 return tcx.optimized_mir(def_id);
107             } else {
108                 bug!("builtin clone shim {:?} not supported", instance)
109             }
110         }
111         ty::InstanceDef::Intrinsic(_) => {
112             bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
113         }
114     };
115     debug!("make_shim({:?}) = untransformed {:?}", instance, result);
116     add_moves_for_packed_drops::add_moves_for_packed_drops(
117         tcx, &mut result, instance.def_id());
118     no_landing_pads::no_landing_pads(tcx, &mut result);
119     remove_noop_landing_pads::remove_noop_landing_pads(tcx, &mut result);
120     simplify::simplify_cfg(&mut result);
121     add_call_guards::CriticalCallEdges.add_call_guards(&mut result);
122     debug!("make_shim({:?}) = {:?}", instance, result);
123
124     tcx.alloc_mir(result)
125 }
126
127 #[derive(Copy, Clone, Debug, PartialEq)]
128 enum Adjustment {
129     Identity,
130     Deref,
131     DerefMove,
132     RefMut,
133 }
134
135 #[derive(Copy, Clone, Debug, PartialEq)]
136 enum CallKind {
137     Indirect,
138     Direct(DefId),
139 }
140
141 fn temp_decl(mutability: Mutability, ty: Ty, span: Span) -> LocalDecl {
142     let source_info = SourceInfo { scope: OUTERMOST_SOURCE_SCOPE, span };
143     LocalDecl {
144         mutability,
145         ty,
146         user_ty: UserTypeProjections::none(),
147         name: None,
148         source_info,
149         visibility_scope: source_info.scope,
150         internal: false,
151         is_user_variable: None,
152         is_block_tail: None,
153     }
154 }
155
156 fn local_decls_for_sig<'tcx>(sig: &ty::FnSig<'tcx>, span: Span)
157     -> IndexVec<Local, LocalDecl<'tcx>>
158 {
159     iter::once(temp_decl(Mutability::Mut, sig.output(), span))
160         .chain(sig.inputs().iter().map(
161             |ity| temp_decl(Mutability::Not, ity, span)))
162         .collect()
163 }
164
165 fn build_drop_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
166                              def_id: DefId,
167                              ty: Option<Ty<'tcx>>)
168                              -> Mir<'tcx>
169 {
170     debug!("build_drop_shim(def_id={:?}, ty={:?})", def_id, ty);
171
172     // Check if this is a generator, if so, return the drop glue for it
173     if let Some(&ty::TyS { sty: ty::Generator(gen_def_id, substs, _), .. }) = ty {
174         let mir = &**tcx.optimized_mir(gen_def_id).generator_drop.as_ref().unwrap();
175         return mir.subst(tcx, substs.substs);
176     }
177
178     let substs = if let Some(ty) = ty {
179         tcx.intern_substs(&[ty.into()])
180     } else {
181         Substs::identity_for_item(tcx, def_id)
182     };
183     let sig = tcx.fn_sig(def_id).subst(tcx, substs);
184     let sig = tcx.erase_late_bound_regions(&sig);
185     let span = tcx.def_span(def_id);
186
187     let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
188
189     let return_block = BasicBlock::new(1);
190     let mut blocks = IndexVec::with_capacity(2);
191     let block = |blocks: &mut IndexVec<_, _>, kind| {
192         blocks.push(BasicBlockData {
193             statements: vec![],
194             terminator: Some(Terminator { source_info, kind }),
195             is_cleanup: false
196         })
197     };
198     block(&mut blocks, TerminatorKind::Goto { target: return_block });
199     block(&mut blocks, TerminatorKind::Return);
200
201     let mut mir = Mir::new(
202         blocks,
203         IndexVec::from_elem_n(
204             SourceScopeData { span: span, parent_scope: None }, 1
205         ),
206         ClearCrossCrate::Clear,
207         IndexVec::new(),
208         None,
209         local_decls_for_sig(&sig, span),
210         sig.inputs().len(),
211         vec![],
212         span,
213         vec![],
214     );
215
216     if let Some(..) = ty {
217         // The first argument (index 0), but add 1 for the return value.
218         let dropee_ptr = Place::Local(Local::new(1+0));
219         if tcx.sess.opts.debugging_opts.mir_emit_retag {
220             // Function arguments should be retagged, and we make this one raw.
221             mir.basic_blocks_mut()[START_BLOCK].statements.insert(0, Statement {
222                 source_info,
223                 kind: StatementKind::Retag(RetagKind::Raw, dropee_ptr.clone()),
224             });
225         }
226         let patch = {
227             let param_env = tcx.param_env(def_id).with_reveal_all();
228             let mut elaborator = DropShimElaborator {
229                 mir: &mir,
230                 patch: MirPatch::new(&mir),
231                 tcx,
232                 param_env
233             };
234             let dropee = dropee_ptr.deref();
235             let resume_block = elaborator.patch.resume_block();
236             elaborate_drops::elaborate_drop(
237                 &mut elaborator,
238                 source_info,
239                 &dropee,
240                 (),
241                 return_block,
242                 elaborate_drops::Unwind::To(resume_block),
243                 START_BLOCK
244             );
245             elaborator.patch
246         };
247         patch.apply(&mut mir);
248     }
249
250     mir
251 }
252
253 pub struct DropShimElaborator<'a, 'tcx: 'a> {
254     pub mir: &'a Mir<'tcx>,
255     pub patch: MirPatch<'tcx>,
256     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
257     pub param_env: ty::ParamEnv<'tcx>,
258 }
259
260 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
261     fn fmt(&self, _f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
262         Ok(())
263     }
264 }
265
266 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
267     type Path = ();
268
269     fn patch(&mut self) -> &mut MirPatch<'tcx> { &mut self.patch }
270     fn mir(&self) -> &'a Mir<'tcx> { self.mir }
271     fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.tcx }
272     fn param_env(&self) -> ty::ParamEnv<'tcx> { self.param_env }
273
274     fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
275         if let DropFlagMode::Shallow = mode {
276             DropStyle::Static
277         } else {
278             DropStyle::Open
279         }
280     }
281
282     fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
283         None
284     }
285
286     fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {
287     }
288
289     fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
290         None
291     }
292     fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
293         None
294     }
295     fn downcast_subpath(&self, _path: Self::Path, _variant: VariantIdx) -> Option<Self::Path> {
296         Some(())
297     }
298     fn array_subpath(&self, _path: Self::Path, _index: u32, _size: u32) -> Option<Self::Path> {
299         None
300     }
301 }
302
303 /// Build a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`.
304 fn build_clone_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
305                               def_id: DefId,
306                               self_ty: Ty<'tcx>)
307                               -> Mir<'tcx>
308 {
309     debug!("build_clone_shim(def_id={:?})", def_id);
310
311     let mut builder = CloneShimBuilder::new(tcx, def_id, self_ty);
312     let is_copy = !self_ty.moves_by_default(tcx, tcx.param_env(def_id), builder.span);
313
314     let dest = Place::Local(RETURN_PLACE);
315     let src = Place::Local(Local::new(1+0)).deref();
316
317     match self_ty.sty {
318         _ if is_copy => builder.copy_shim(),
319         ty::Array(ty, len) => {
320             let len = len.unwrap_usize(tcx);
321             builder.array_shim(dest, src, ty, len)
322         }
323         ty::Closure(def_id, substs) => {
324             builder.tuple_like_shim(
325                 dest, src,
326                 substs.upvar_tys(def_id, tcx)
327             )
328         }
329         ty::Tuple(tys) => builder.tuple_like_shim(dest, src, tys.iter().cloned()),
330         _ => {
331             bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty)
332         }
333     };
334
335     builder.into_mir()
336 }
337
338 struct CloneShimBuilder<'a, 'tcx: 'a> {
339     tcx: TyCtxt<'a, 'tcx, 'tcx>,
340     def_id: DefId,
341     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
342     blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
343     span: Span,
344     sig: ty::FnSig<'tcx>,
345 }
346
347 impl<'a, 'tcx> CloneShimBuilder<'a, 'tcx> {
348     fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
349            def_id: DefId,
350            self_ty: Ty<'tcx>) -> Self {
351         // we must subst the self_ty because it's
352         // otherwise going to be TySelf and we can't index
353         // or access fields of a Place of type TySelf.
354         let substs = tcx.mk_substs_trait(self_ty, &[]);
355         let sig = tcx.fn_sig(def_id).subst(tcx, substs);
356         let sig = tcx.erase_late_bound_regions(&sig);
357         let span = tcx.def_span(def_id);
358
359         CloneShimBuilder {
360             tcx,
361             def_id,
362             local_decls: local_decls_for_sig(&sig, span),
363             blocks: IndexVec::new(),
364             span,
365             sig,
366         }
367     }
368
369     fn into_mir(self) -> Mir<'tcx> {
370         Mir::new(
371             self.blocks,
372             IndexVec::from_elem_n(
373                 SourceScopeData { span: self.span, parent_scope: None }, 1
374             ),
375             ClearCrossCrate::Clear,
376             IndexVec::new(),
377             None,
378             self.local_decls,
379             self.sig.inputs().len(),
380             vec![],
381             self.span,
382             vec![],
383         )
384     }
385
386     fn source_info(&self) -> SourceInfo {
387         SourceInfo { span: self.span, scope: OUTERMOST_SOURCE_SCOPE }
388     }
389
390     fn block(
391         &mut self,
392         statements: Vec<Statement<'tcx>>,
393         kind: TerminatorKind<'tcx>,
394         is_cleanup: bool
395     ) -> BasicBlock {
396         let source_info = self.source_info();
397         self.blocks.push(BasicBlockData {
398             statements,
399             terminator: Some(Terminator { source_info, kind }),
400             is_cleanup,
401         })
402     }
403
404     /// Gives the index of an upcoming BasicBlock, with an offset.
405     /// offset=0 will give you the index of the next BasicBlock,
406     /// offset=1 will give the index of the next-to-next block,
407     /// offset=-1 will give you the index of the last-created block
408     fn block_index_offset(&mut self, offset: usize) -> BasicBlock {
409         BasicBlock::new(self.blocks.len() + offset)
410     }
411
412     fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
413         Statement {
414             source_info: self.source_info(),
415             kind,
416         }
417     }
418
419     fn copy_shim(&mut self) {
420         let rcvr = Place::Local(Local::new(1+0)).deref();
421         let ret_statement = self.make_statement(
422             StatementKind::Assign(
423                 Place::Local(RETURN_PLACE),
424                 box Rvalue::Use(Operand::Copy(rcvr))
425             )
426         );
427         self.block(vec![ret_statement], TerminatorKind::Return, false);
428     }
429
430     fn make_place(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Place<'tcx> {
431         let span = self.span;
432         Place::Local(
433             self.local_decls.push(temp_decl(mutability, ty, span))
434         )
435     }
436
437     fn make_clone_call(
438         &mut self,
439         dest: Place<'tcx>,
440         src: Place<'tcx>,
441         ty: Ty<'tcx>,
442         next: BasicBlock,
443         cleanup: BasicBlock
444     ) {
445         let tcx = self.tcx;
446
447         let substs = Substs::for_item(tcx, self.def_id, |param, _| {
448             match param.kind {
449                 GenericParamDefKind::Lifetime => tcx.types.re_erased.into(),
450                 GenericParamDefKind::Type {..} => ty.into(),
451             }
452         });
453
454         // `func == Clone::clone(&ty) -> ty`
455         let func_ty = tcx.mk_fn_def(self.def_id, substs);
456         let func = Operand::Constant(box Constant {
457             span: self.span,
458             ty: func_ty,
459             user_ty: None,
460             literal: ty::Const::zero_sized(self.tcx, func_ty),
461         });
462
463         let ref_loc = self.make_place(
464             Mutability::Not,
465             tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
466                 ty,
467                 mutbl: hir::Mutability::MutImmutable,
468             })
469         );
470
471         // `let ref_loc: &ty = &src;`
472         let statement = self.make_statement(
473             StatementKind::Assign(
474                 ref_loc.clone(),
475                 box Rvalue::Ref(tcx.types.re_erased, BorrowKind::Shared, src)
476             )
477         );
478
479         // `let loc = Clone::clone(ref_loc);`
480         self.block(vec![statement], TerminatorKind::Call {
481             func,
482             args: vec![Operand::Move(ref_loc)],
483             destination: Some((dest, next)),
484             cleanup: Some(cleanup),
485             from_hir_call: true,
486         }, false);
487     }
488
489     fn loop_header(
490         &mut self,
491         beg: Place<'tcx>,
492         end: Place<'tcx>,
493         loop_body: BasicBlock,
494         loop_end: BasicBlock,
495         is_cleanup: bool
496     ) {
497         let tcx = self.tcx;
498
499         let cond = self.make_place(Mutability::Mut, tcx.types.bool);
500         let compute_cond = self.make_statement(
501             StatementKind::Assign(
502                 cond.clone(),
503                 box Rvalue::BinaryOp(BinOp::Ne, Operand::Copy(end), Operand::Copy(beg))
504             )
505         );
506
507         // `if end != beg { goto loop_body; } else { goto loop_end; }`
508         self.block(
509             vec![compute_cond],
510             TerminatorKind::if_(tcx, Operand::Move(cond), loop_body, loop_end),
511             is_cleanup
512         );
513     }
514
515     fn make_usize(&self, value: u64) -> Box<Constant<'tcx>> {
516         box Constant {
517             span: self.span,
518             ty: self.tcx.types.usize,
519             user_ty: None,
520             literal: ty::Const::from_usize(self.tcx, value),
521         }
522     }
523
524     fn array_shim(&mut self, dest: Place<'tcx>, src: Place<'tcx>, ty: Ty<'tcx>, len: u64) {
525         let tcx = self.tcx;
526         let span = self.span;
527
528         let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
529         let end = self.make_place(Mutability::Not, tcx.types.usize);
530
531         // BB #0
532         // `let mut beg = 0;`
533         // `let end = len;`
534         // `goto #1;`
535         let inits = vec![
536             self.make_statement(
537                 StatementKind::Assign(
538                     Place::Local(beg),
539                     box Rvalue::Use(Operand::Constant(self.make_usize(0)))
540                 )
541             ),
542             self.make_statement(
543                 StatementKind::Assign(
544                     end.clone(),
545                     box Rvalue::Use(Operand::Constant(self.make_usize(len)))
546                 )
547             )
548         ];
549         self.block(inits, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
550
551         // BB #1: loop {
552         //     BB #2;
553         //     BB #3;
554         // }
555         // BB #4;
556         self.loop_header(Place::Local(beg), end, BasicBlock::new(2), BasicBlock::new(4), false);
557
558         // BB #2
559         // `dest[i] = Clone::clone(src[beg])`;
560         // Goto #3 if ok, #5 if unwinding happens.
561         let dest_field = dest.clone().index(beg);
562         let src_field = src.index(beg);
563         self.make_clone_call(dest_field, src_field, ty, BasicBlock::new(3),
564                              BasicBlock::new(5));
565
566         // BB #3
567         // `beg = beg + 1;`
568         // `goto #1`;
569         let statements = vec![
570             self.make_statement(
571                 StatementKind::Assign(
572                     Place::Local(beg),
573                     box Rvalue::BinaryOp(
574                         BinOp::Add,
575                         Operand::Copy(Place::Local(beg)),
576                         Operand::Constant(self.make_usize(1))
577                     )
578                 )
579             )
580         ];
581         self.block(statements, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
582
583         // BB #4
584         // `return dest;`
585         self.block(vec![], TerminatorKind::Return, false);
586
587         // BB #5 (cleanup)
588         // `let end = beg;`
589         // `let mut beg = 0;`
590         // goto #6;
591         let end = beg;
592         let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
593         let init = self.make_statement(
594             StatementKind::Assign(
595                 Place::Local(beg),
596                 box Rvalue::Use(Operand::Constant(self.make_usize(0)))
597             )
598         );
599         self.block(vec![init], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
600
601         // BB #6 (cleanup): loop {
602         //     BB #7;
603         //     BB #8;
604         // }
605         // BB #9;
606         self.loop_header(Place::Local(beg), Place::Local(end),
607                          BasicBlock::new(7), BasicBlock::new(9), true);
608
609         // BB #7 (cleanup)
610         // `drop(dest[beg])`;
611         self.block(vec![], TerminatorKind::Drop {
612             location: dest.index(beg),
613             target: BasicBlock::new(8),
614             unwind: None,
615         }, true);
616
617         // BB #8 (cleanup)
618         // `beg = beg + 1;`
619         // `goto #6;`
620         let statement = self.make_statement(
621             StatementKind::Assign(
622                 Place::Local(beg),
623                 box Rvalue::BinaryOp(
624                     BinOp::Add,
625                     Operand::Copy(Place::Local(beg)),
626                     Operand::Constant(self.make_usize(1))
627                 )
628             )
629         );
630         self.block(vec![statement], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
631
632         // BB #9 (resume)
633         self.block(vec![], TerminatorKind::Resume, true);
634     }
635
636     fn tuple_like_shim<I>(&mut self, dest: Place<'tcx>,
637                           src: Place<'tcx>, tys: I)
638             where I: Iterator<Item = ty::Ty<'tcx>> {
639         let mut previous_field = None;
640         for (i, ity) in tys.enumerate() {
641             let field = Field::new(i);
642             let src_field = src.clone().field(field, ity);
643
644             let dest_field = dest.clone().field(field, ity);
645
646             // #(2i + 1) is the cleanup block for the previous clone operation
647             let cleanup_block = self.block_index_offset(1);
648             // #(2i + 2) is the next cloning block
649             // (or the Return terminator if this is the last block)
650             let next_block = self.block_index_offset(2);
651
652             // BB #(2i)
653             // `dest.i = Clone::clone(&src.i);`
654             // Goto #(2i + 2) if ok, #(2i + 1) if unwinding happens.
655             self.make_clone_call(
656                 dest_field.clone(),
657                 src_field,
658                 ity,
659                 next_block,
660                 cleanup_block,
661             );
662
663             // BB #(2i + 1) (cleanup)
664             if let Some((previous_field, previous_cleanup)) = previous_field.take() {
665                 // Drop previous field and goto previous cleanup block.
666                 self.block(vec![], TerminatorKind::Drop {
667                     location: previous_field,
668                     target: previous_cleanup,
669                     unwind: None,
670                 }, true);
671             } else {
672                 // Nothing to drop, just resume.
673                 self.block(vec![], TerminatorKind::Resume, true);
674             }
675
676             previous_field = Some((dest_field, cleanup_block));
677         }
678
679         self.block(vec![], TerminatorKind::Return, false);
680     }
681 }
682
683 /// Build a "call" shim for `def_id`. The shim calls the
684 /// function specified by `call_kind`, first adjusting its first
685 /// argument according to `rcvr_adjustment`.
686 ///
687 /// If `untuple_args` is a vec of types, the second argument of the
688 /// function will be untupled as these types.
689 fn build_call_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
690                              def_id: DefId,
691                              rcvr_adjustment: Adjustment,
692                              call_kind: CallKind,
693                              untuple_args: Option<&[Ty<'tcx>]>)
694                              -> Mir<'tcx>
695 {
696     debug!("build_call_shim(def_id={:?}, rcvr_adjustment={:?}, \
697             call_kind={:?}, untuple_args={:?})",
698            def_id, rcvr_adjustment, call_kind, untuple_args);
699
700     let sig = tcx.fn_sig(def_id);
701     let sig = tcx.erase_late_bound_regions(&sig);
702     let span = tcx.def_span(def_id);
703
704     debug!("build_call_shim: sig={:?}", sig);
705
706     let mut local_decls = local_decls_for_sig(&sig, span);
707     let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
708
709     let rcvr_arg = Local::new(1+0);
710     let rcvr_l = Place::Local(rcvr_arg);
711     let mut statements = vec![];
712
713     let rcvr = match rcvr_adjustment {
714         Adjustment::Identity => Operand::Move(rcvr_l),
715         Adjustment::Deref => Operand::Copy(rcvr_l.deref()),
716         Adjustment::DerefMove => {
717             // fn(Self, ...) -> fn(*mut Self, ...)
718             let arg_ty = local_decls[rcvr_arg].ty;
719             assert!(arg_ty.is_self());
720             local_decls[rcvr_arg].ty = tcx.mk_mut_ptr(arg_ty);
721
722             Operand::Move(rcvr_l.deref())
723         }
724         Adjustment::RefMut => {
725             // let rcvr = &mut rcvr;
726             let ref_rcvr = local_decls.push(temp_decl(
727                 Mutability::Not,
728                 tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
729                     ty: sig.inputs()[0],
730                     mutbl: hir::Mutability::MutMutable
731                 }),
732                 span
733             ));
734             let borrow_kind = BorrowKind::Mut {
735                 allow_two_phase_borrow: false,
736             };
737             statements.push(Statement {
738                 source_info,
739                 kind: StatementKind::Assign(
740                     Place::Local(ref_rcvr),
741                     box Rvalue::Ref(tcx.types.re_erased, borrow_kind, rcvr_l)
742                 )
743             });
744             Operand::Move(Place::Local(ref_rcvr))
745         }
746     };
747
748     let (callee, mut args) = match call_kind {
749         CallKind::Indirect => (rcvr, vec![]),
750         CallKind::Direct(def_id) => {
751             let ty = tcx.type_of(def_id);
752             (Operand::Constant(box Constant {
753                 span,
754                 ty,
755                 user_ty: None,
756                 literal: ty::Const::zero_sized(tcx, ty),
757              }),
758              vec![rcvr])
759         }
760     };
761
762     if let Some(untuple_args) = untuple_args {
763         args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
764             let arg_place = Place::Local(Local::new(1+1));
765             Operand::Move(arg_place.field(Field::new(i), *ity))
766         }));
767     } else {
768         args.extend((1..sig.inputs().len()).map(|i| {
769             Operand::Move(Place::Local(Local::new(1+i)))
770         }));
771     }
772
773     let n_blocks = if let Adjustment::RefMut = rcvr_adjustment { 5 } else { 2 };
774     let mut blocks = IndexVec::with_capacity(n_blocks);
775     let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
776         blocks.push(BasicBlockData {
777             statements,
778             terminator: Some(Terminator { source_info, kind }),
779             is_cleanup
780         })
781     };
782
783     // BB #0
784     block(&mut blocks, statements, TerminatorKind::Call {
785         func: callee,
786         args,
787         destination: Some((Place::Local(RETURN_PLACE),
788                            BasicBlock::new(1))),
789         cleanup: if let Adjustment::RefMut = rcvr_adjustment {
790             Some(BasicBlock::new(3))
791         } else {
792             None
793         },
794         from_hir_call: true,
795     }, false);
796
797     if let Adjustment::RefMut = rcvr_adjustment {
798         // BB #1 - drop for Self
799         block(&mut blocks, vec![], TerminatorKind::Drop {
800             location: Place::Local(rcvr_arg),
801             target: BasicBlock::new(2),
802             unwind: None
803         }, false);
804     }
805     // BB #1/#2 - return
806     block(&mut blocks, vec![], TerminatorKind::Return, false);
807     if let Adjustment::RefMut = rcvr_adjustment {
808         // BB #3 - drop if closure panics
809         block(&mut blocks, vec![], TerminatorKind::Drop {
810             location: Place::Local(rcvr_arg),
811             target: BasicBlock::new(4),
812             unwind: None
813         }, true);
814
815         // BB #4 - resume
816         block(&mut blocks, vec![], TerminatorKind::Resume, true);
817     }
818
819     let mut mir = Mir::new(
820         blocks,
821         IndexVec::from_elem_n(
822             SourceScopeData { span: span, parent_scope: None }, 1
823         ),
824         ClearCrossCrate::Clear,
825         IndexVec::new(),
826         None,
827         local_decls,
828         sig.inputs().len(),
829         vec![],
830         span,
831         vec![],
832     );
833     if let Abi::RustCall = sig.abi {
834         mir.spread_arg = Some(Local::new(sig.inputs().len()));
835     }
836     mir
837 }
838
839 pub fn build_adt_ctor<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
840                                       ctor_id: ast::NodeId,
841                                       fields: &[hir::StructField],
842                                       span: Span)
843                                       -> Mir<'tcx>
844 {
845     let tcx = infcx.tcx;
846     let gcx = tcx.global_tcx();
847     let def_id = tcx.hir().local_def_id(ctor_id);
848     let param_env = gcx.param_env(def_id);
849
850     // Normalize the sig.
851     let sig = gcx.fn_sig(def_id)
852         .no_bound_vars()
853         .expect("LBR in ADT constructor signature");
854     let sig = gcx.normalize_erasing_regions(param_env, sig);
855
856     let (adt_def, substs) = match sig.output().sty {
857         ty::Adt(adt_def, substs) => (adt_def, substs),
858         _ => bug!("unexpected type for ADT ctor {:?}", sig.output())
859     };
860
861     debug!("build_ctor: def_id={:?} sig={:?} fields={:?}", def_id, sig, fields);
862
863     let local_decls = local_decls_for_sig(&sig, span);
864
865     let source_info = SourceInfo {
866         span,
867         scope: OUTERMOST_SOURCE_SCOPE
868     };
869
870     let variant_no = if adt_def.is_enum() {
871         adt_def.variant_index_with_id(def_id)
872     } else {
873         VariantIdx::new(0)
874     };
875
876     // return = ADT(arg0, arg1, ...); return
877     let start_block = BasicBlockData {
878         statements: vec![Statement {
879             source_info,
880             kind: StatementKind::Assign(
881                 Place::Local(RETURN_PLACE),
882                 box Rvalue::Aggregate(
883                     box AggregateKind::Adt(adt_def, variant_no, substs, None, None),
884                     (1..sig.inputs().len()+1).map(|i| {
885                         Operand::Move(Place::Local(Local::new(i)))
886                     }).collect()
887                 )
888             )
889         }],
890         terminator: Some(Terminator {
891             source_info,
892             kind: TerminatorKind::Return,
893         }),
894         is_cleanup: false
895     };
896
897     Mir::new(
898         IndexVec::from_elem_n(start_block, 1),
899         IndexVec::from_elem_n(
900             SourceScopeData { span: span, parent_scope: None }, 1
901         ),
902         ClearCrossCrate::Clear,
903         IndexVec::new(),
904         None,
905         local_decls,
906         sig.inputs().len(),
907         vec![],
908         span,
909         vec![],
910     )
911 }