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