]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/shim.rs
Check for uninhabitedness instead of never
[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     );
224
225     if let Some(..) = ty {
226         // The first argument (index 0), but add 1 for the return value.
227         let dropee_ptr = Place::Local(Local::new(1+0));
228         if tcx.sess.opts.debugging_opts.mir_emit_retag {
229             // Function arguments should be retagged
230             mir.basic_blocks_mut()[START_BLOCK].statements.insert(0, Statement {
231                 source_info,
232                 kind: StatementKind::Retag {
233                     fn_entry: true,
234                     two_phase: false,
235                     place: dropee_ptr.clone(),
236                 },
237             });
238             // We use raw ptr operations, better prepare the alias tracking for that
239             mir.basic_blocks_mut()[START_BLOCK].statements.insert(1, Statement {
240                 source_info,
241                 kind: StatementKind::EscapeToRaw(Operand::Copy(dropee_ptr.clone())),
242             })
243         }
244         let patch = {
245             let param_env = tcx.param_env(def_id).with_reveal_all();
246             let mut elaborator = DropShimElaborator {
247                 mir: &mir,
248                 patch: MirPatch::new(&mir),
249                 tcx,
250                 param_env
251             };
252             let dropee = dropee_ptr.deref();
253             let resume_block = elaborator.patch.resume_block();
254             elaborate_drops::elaborate_drop(
255                 &mut elaborator,
256                 source_info,
257                 &dropee,
258                 (),
259                 return_block,
260                 elaborate_drops::Unwind::To(resume_block),
261                 START_BLOCK
262             );
263             elaborator.patch
264         };
265         patch.apply(&mut mir);
266     }
267
268     mir
269 }
270
271 pub struct DropShimElaborator<'a, 'tcx: 'a> {
272     pub mir: &'a Mir<'tcx>,
273     pub patch: MirPatch<'tcx>,
274     pub tcx: TyCtxt<'a, 'tcx, 'tcx>,
275     pub param_env: ty::ParamEnv<'tcx>,
276 }
277
278 impl<'a, 'tcx> fmt::Debug for DropShimElaborator<'a, 'tcx> {
279     fn fmt(&self, _f: &mut fmt::Formatter) -> Result<(), fmt::Error> {
280         Ok(())
281     }
282 }
283
284 impl<'a, 'tcx> DropElaborator<'a, 'tcx> for DropShimElaborator<'a, 'tcx> {
285     type Path = ();
286
287     fn patch(&mut self) -> &mut MirPatch<'tcx> { &mut self.patch }
288     fn mir(&self) -> &'a Mir<'tcx> { self.mir }
289     fn tcx(&self) -> TyCtxt<'a, 'tcx, 'tcx> { self.tcx }
290     fn param_env(&self) -> ty::ParamEnv<'tcx> { self.param_env }
291
292     fn drop_style(&self, _path: Self::Path, mode: DropFlagMode) -> DropStyle {
293         if let DropFlagMode::Shallow = mode {
294             DropStyle::Static
295         } else {
296             DropStyle::Open
297         }
298     }
299
300     fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
301         None
302     }
303
304     fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {
305     }
306
307     fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
308         None
309     }
310     fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
311         None
312     }
313     fn downcast_subpath(&self, _path: Self::Path, _variant: VariantIdx) -> Option<Self::Path> {
314         Some(())
315     }
316     fn array_subpath(&self, _path: Self::Path, _index: u32, _size: u32) -> Option<Self::Path> {
317         None
318     }
319 }
320
321 /// Build a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`.
322 fn build_clone_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
323                               def_id: DefId,
324                               self_ty: Ty<'tcx>)
325                               -> Mir<'tcx>
326 {
327     debug!("build_clone_shim(def_id={:?})", def_id);
328
329     let mut builder = CloneShimBuilder::new(tcx, def_id, self_ty);
330     let is_copy = !self_ty.moves_by_default(tcx, tcx.param_env(def_id), builder.span);
331
332     let dest = Place::Local(RETURN_PLACE);
333     let src = Place::Local(Local::new(1+0)).deref();
334
335     match self_ty.sty {
336         _ if is_copy => builder.copy_shim(),
337         ty::Array(ty, len) => {
338             let len = len.unwrap_usize(tcx);
339             builder.array_shim(dest, src, ty, len)
340         }
341         ty::Closure(def_id, substs) => {
342             builder.tuple_like_shim(
343                 dest, src,
344                 substs.upvar_tys(def_id, tcx)
345             )
346         }
347         ty::Tuple(tys) => builder.tuple_like_shim(dest, src, tys.iter().cloned()),
348         _ => {
349             bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty)
350         }
351     };
352
353     builder.into_mir()
354 }
355
356 struct CloneShimBuilder<'a, 'tcx: 'a> {
357     tcx: TyCtxt<'a, 'tcx, 'tcx>,
358     def_id: DefId,
359     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
360     blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
361     span: Span,
362     sig: ty::FnSig<'tcx>,
363 }
364
365 impl<'a, 'tcx> CloneShimBuilder<'a, 'tcx> {
366     fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
367            def_id: DefId,
368            self_ty: Ty<'tcx>) -> Self {
369         // we must subst the self_ty because it's
370         // otherwise going to be TySelf and we can't index
371         // or access fields of a Place of type TySelf.
372         let substs = tcx.mk_substs_trait(self_ty, &[]);
373         let sig = tcx.fn_sig(def_id).subst(tcx, substs);
374         let sig = tcx.erase_late_bound_regions(&sig);
375         let span = tcx.def_span(def_id);
376
377         CloneShimBuilder {
378             tcx,
379             def_id,
380             local_decls: local_decls_for_sig(&sig, span),
381             blocks: IndexVec::new(),
382             span,
383             sig,
384         }
385     }
386
387     fn into_mir(self) -> Mir<'tcx> {
388         Mir::new(
389             self.blocks,
390             IndexVec::from_elem_n(
391                 SourceScopeData { span: self.span, parent_scope: None }, 1
392             ),
393             ClearCrossCrate::Clear,
394             IndexVec::new(),
395             None,
396             self.local_decls,
397             self.sig.inputs().len(),
398             vec![],
399             self.span
400         )
401     }
402
403     fn source_info(&self) -> SourceInfo {
404         SourceInfo { span: self.span, scope: OUTERMOST_SOURCE_SCOPE }
405     }
406
407     fn block(
408         &mut self,
409         statements: Vec<Statement<'tcx>>,
410         kind: TerminatorKind<'tcx>,
411         is_cleanup: bool
412     ) -> BasicBlock {
413         let source_info = self.source_info();
414         self.blocks.push(BasicBlockData {
415             statements,
416             terminator: Some(Terminator { source_info, kind }),
417             is_cleanup,
418         })
419     }
420
421     /// Gives the index of an upcoming BasicBlock, with an offset.
422     /// offset=0 will give you the index of the next BasicBlock,
423     /// offset=1 will give the index of the next-to-next block,
424     /// offset=-1 will give you the index of the last-created block
425     fn block_index_offset(&mut self, offset: usize) -> BasicBlock {
426         BasicBlock::new(self.blocks.len() + offset)
427     }
428
429     fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
430         Statement {
431             source_info: self.source_info(),
432             kind,
433         }
434     }
435
436     fn copy_shim(&mut self) {
437         let rcvr = Place::Local(Local::new(1+0)).deref();
438         let ret_statement = self.make_statement(
439             StatementKind::Assign(
440                 Place::Local(RETURN_PLACE),
441                 box Rvalue::Use(Operand::Copy(rcvr))
442             )
443         );
444         self.block(vec![ret_statement], TerminatorKind::Return, false);
445     }
446
447     fn make_place(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Place<'tcx> {
448         let span = self.span;
449         Place::Local(
450             self.local_decls.push(temp_decl(mutability, ty, span))
451         )
452     }
453
454     fn make_clone_call(
455         &mut self,
456         dest: Place<'tcx>,
457         src: Place<'tcx>,
458         ty: Ty<'tcx>,
459         next: BasicBlock,
460         cleanup: BasicBlock
461     ) {
462         let tcx = self.tcx;
463
464         let substs = Substs::for_item(tcx, self.def_id, |param, _| {
465             match param.kind {
466                 GenericParamDefKind::Lifetime => tcx.types.re_erased.into(),
467                 GenericParamDefKind::Type {..} => ty.into(),
468             }
469         });
470
471         // `func == Clone::clone(&ty) -> ty`
472         let func_ty = tcx.mk_fn_def(self.def_id, substs);
473         let func = Operand::Constant(box Constant {
474             span: self.span,
475             ty: func_ty,
476             user_ty: None,
477             literal: ty::Const::zero_sized(self.tcx, func_ty),
478         });
479
480         let ref_loc = self.make_place(
481             Mutability::Not,
482             tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
483                 ty,
484                 mutbl: hir::Mutability::MutImmutable,
485             })
486         );
487
488         // `let ref_loc: &ty = &src;`
489         let statement = self.make_statement(
490             StatementKind::Assign(
491                 ref_loc.clone(),
492                 box Rvalue::Ref(tcx.types.re_erased, BorrowKind::Shared, src)
493             )
494         );
495
496         // `let loc = Clone::clone(ref_loc);`
497         self.block(vec![statement], TerminatorKind::Call {
498             func,
499             args: vec![Operand::Move(ref_loc)],
500             destination: Some((dest, next)),
501             cleanup: Some(cleanup),
502             from_hir_call: true,
503         }, false);
504     }
505
506     fn loop_header(
507         &mut self,
508         beg: Place<'tcx>,
509         end: Place<'tcx>,
510         loop_body: BasicBlock,
511         loop_end: BasicBlock,
512         is_cleanup: bool
513     ) {
514         let tcx = self.tcx;
515
516         let cond = self.make_place(Mutability::Mut, tcx.types.bool);
517         let compute_cond = self.make_statement(
518             StatementKind::Assign(
519                 cond.clone(),
520                 box Rvalue::BinaryOp(BinOp::Ne, Operand::Copy(end), Operand::Copy(beg))
521             )
522         );
523
524         // `if end != beg { goto loop_body; } else { goto loop_end; }`
525         self.block(
526             vec![compute_cond],
527             TerminatorKind::if_(tcx, Operand::Move(cond), loop_body, loop_end),
528             is_cleanup
529         );
530     }
531
532     fn make_usize(&self, value: u64) -> Box<Constant<'tcx>> {
533         box Constant {
534             span: self.span,
535             ty: self.tcx.types.usize,
536             user_ty: None,
537             literal: ty::Const::from_usize(self.tcx, value),
538         }
539     }
540
541     fn array_shim(&mut self, dest: Place<'tcx>, src: Place<'tcx>, ty: Ty<'tcx>, len: u64) {
542         let tcx = self.tcx;
543         let span = self.span;
544
545         let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
546         let end = self.make_place(Mutability::Not, tcx.types.usize);
547
548         // BB #0
549         // `let mut beg = 0;`
550         // `let end = len;`
551         // `goto #1;`
552         let inits = vec![
553             self.make_statement(
554                 StatementKind::Assign(
555                     Place::Local(beg),
556                     box Rvalue::Use(Operand::Constant(self.make_usize(0)))
557                 )
558             ),
559             self.make_statement(
560                 StatementKind::Assign(
561                     end.clone(),
562                     box Rvalue::Use(Operand::Constant(self.make_usize(len)))
563                 )
564             )
565         ];
566         self.block(inits, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
567
568         // BB #1: loop {
569         //     BB #2;
570         //     BB #3;
571         // }
572         // BB #4;
573         self.loop_header(Place::Local(beg), end, BasicBlock::new(2), BasicBlock::new(4), false);
574
575         // BB #2
576         // `dest[i] = Clone::clone(src[beg])`;
577         // Goto #3 if ok, #5 if unwinding happens.
578         let dest_field = dest.clone().index(beg);
579         let src_field = src.index(beg);
580         self.make_clone_call(dest_field, src_field, ty, BasicBlock::new(3),
581                              BasicBlock::new(5));
582
583         // BB #3
584         // `beg = beg + 1;`
585         // `goto #1`;
586         let statements = vec![
587             self.make_statement(
588                 StatementKind::Assign(
589                     Place::Local(beg),
590                     box Rvalue::BinaryOp(
591                         BinOp::Add,
592                         Operand::Copy(Place::Local(beg)),
593                         Operand::Constant(self.make_usize(1))
594                     )
595                 )
596             )
597         ];
598         self.block(statements, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
599
600         // BB #4
601         // `return dest;`
602         self.block(vec![], TerminatorKind::Return, false);
603
604         // BB #5 (cleanup)
605         // `let end = beg;`
606         // `let mut beg = 0;`
607         // goto #6;
608         let end = beg;
609         let beg = self.local_decls.push(temp_decl(Mutability::Mut, tcx.types.usize, span));
610         let init = self.make_statement(
611             StatementKind::Assign(
612                 Place::Local(beg),
613                 box Rvalue::Use(Operand::Constant(self.make_usize(0)))
614             )
615         );
616         self.block(vec![init], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
617
618         // BB #6 (cleanup): loop {
619         //     BB #7;
620         //     BB #8;
621         // }
622         // BB #9;
623         self.loop_header(Place::Local(beg), Place::Local(end),
624                          BasicBlock::new(7), BasicBlock::new(9), true);
625
626         // BB #7 (cleanup)
627         // `drop(dest[beg])`;
628         self.block(vec![], TerminatorKind::Drop {
629             location: dest.index(beg),
630             target: BasicBlock::new(8),
631             unwind: None,
632         }, true);
633
634         // BB #8 (cleanup)
635         // `beg = beg + 1;`
636         // `goto #6;`
637         let statement = self.make_statement(
638             StatementKind::Assign(
639                 Place::Local(beg),
640                 box Rvalue::BinaryOp(
641                     BinOp::Add,
642                     Operand::Copy(Place::Local(beg)),
643                     Operand::Constant(self.make_usize(1))
644                 )
645             )
646         );
647         self.block(vec![statement], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
648
649         // BB #9 (resume)
650         self.block(vec![], TerminatorKind::Resume, true);
651     }
652
653     fn tuple_like_shim<I>(&mut self, dest: Place<'tcx>,
654                           src: Place<'tcx>, tys: I)
655             where I: Iterator<Item = ty::Ty<'tcx>> {
656         let mut previous_field = None;
657         for (i, ity) in tys.enumerate() {
658             let field = Field::new(i);
659             let src_field = src.clone().field(field, ity);
660
661             let dest_field = dest.clone().field(field, ity);
662
663             // #(2i + 1) is the cleanup block for the previous clone operation
664             let cleanup_block = self.block_index_offset(1);
665             // #(2i + 2) is the next cloning block
666             // (or the Return terminator if this is the last block)
667             let next_block = self.block_index_offset(2);
668
669             // BB #(2i)
670             // `dest.i = Clone::clone(&src.i);`
671             // Goto #(2i + 2) if ok, #(2i + 1) if unwinding happens.
672             self.make_clone_call(
673                 dest_field.clone(),
674                 src_field,
675                 ity,
676                 next_block,
677                 cleanup_block,
678             );
679
680             // BB #(2i + 1) (cleanup)
681             if let Some((previous_field, previous_cleanup)) = previous_field.take() {
682                 // Drop previous field and goto previous cleanup block.
683                 self.block(vec![], TerminatorKind::Drop {
684                     location: previous_field,
685                     target: previous_cleanup,
686                     unwind: None,
687                 }, true);
688             } else {
689                 // Nothing to drop, just resume.
690                 self.block(vec![], TerminatorKind::Resume, true);
691             }
692
693             previous_field = Some((dest_field, cleanup_block));
694         }
695
696         self.block(vec![], TerminatorKind::Return, false);
697     }
698 }
699
700 /// Build a "call" shim for `def_id`. The shim calls the
701 /// function specified by `call_kind`, first adjusting its first
702 /// argument according to `rcvr_adjustment`.
703 ///
704 /// If `untuple_args` is a vec of types, the second argument of the
705 /// function will be untupled as these types.
706 fn build_call_shim<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
707                              def_id: DefId,
708                              rcvr_adjustment: Adjustment,
709                              call_kind: CallKind,
710                              untuple_args: Option<&[Ty<'tcx>]>)
711                              -> Mir<'tcx>
712 {
713     debug!("build_call_shim(def_id={:?}, rcvr_adjustment={:?}, \
714             call_kind={:?}, untuple_args={:?})",
715            def_id, rcvr_adjustment, call_kind, untuple_args);
716
717     let sig = tcx.fn_sig(def_id);
718     let sig = tcx.erase_late_bound_regions(&sig);
719     let span = tcx.def_span(def_id);
720
721     debug!("build_call_shim: sig={:?}", sig);
722
723     let mut local_decls = local_decls_for_sig(&sig, span);
724     let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
725
726     let rcvr_arg = Local::new(1+0);
727     let rcvr_l = Place::Local(rcvr_arg);
728     let mut statements = vec![];
729
730     let rcvr = match rcvr_adjustment {
731         Adjustment::Identity => Operand::Move(rcvr_l),
732         Adjustment::Deref => Operand::Copy(rcvr_l.deref()),
733         Adjustment::DerefMove => {
734             // fn(Self, ...) -> fn(*mut Self, ...)
735             let arg_ty = local_decls[rcvr_arg].ty;
736             assert!(arg_ty.is_self());
737             local_decls[rcvr_arg].ty = tcx.mk_mut_ptr(arg_ty);
738
739             Operand::Move(rcvr_l.deref())
740         }
741         Adjustment::RefMut => {
742             // let rcvr = &mut rcvr;
743             let ref_rcvr = local_decls.push(temp_decl(
744                 Mutability::Not,
745                 tcx.mk_ref(tcx.types.re_erased, ty::TypeAndMut {
746                     ty: sig.inputs()[0],
747                     mutbl: hir::Mutability::MutMutable
748                 }),
749                 span
750             ));
751             let borrow_kind = BorrowKind::Mut {
752                 allow_two_phase_borrow: false,
753             };
754             statements.push(Statement {
755                 source_info,
756                 kind: StatementKind::Assign(
757                     Place::Local(ref_rcvr),
758                     box Rvalue::Ref(tcx.types.re_erased, borrow_kind, rcvr_l)
759                 )
760             });
761             Operand::Move(Place::Local(ref_rcvr))
762         }
763     };
764
765     let (callee, mut args) = match call_kind {
766         CallKind::Indirect => (rcvr, vec![]),
767         CallKind::Direct(def_id) => {
768             let ty = tcx.type_of(def_id);
769             (Operand::Constant(box Constant {
770                 span,
771                 ty,
772                 user_ty: None,
773                 literal: ty::Const::zero_sized(tcx, ty),
774              }),
775              vec![rcvr])
776         }
777     };
778
779     if let Some(untuple_args) = untuple_args {
780         args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
781             let arg_place = Place::Local(Local::new(1+1));
782             Operand::Move(arg_place.field(Field::new(i), *ity))
783         }));
784     } else {
785         args.extend((1..sig.inputs().len()).map(|i| {
786             Operand::Move(Place::Local(Local::new(1+i)))
787         }));
788     }
789
790     let n_blocks = if let Adjustment::RefMut = rcvr_adjustment { 5 } else { 2 };
791     let mut blocks = IndexVec::with_capacity(n_blocks);
792     let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
793         blocks.push(BasicBlockData {
794             statements,
795             terminator: Some(Terminator { source_info, kind }),
796             is_cleanup
797         })
798     };
799
800     // BB #0
801     block(&mut blocks, statements, TerminatorKind::Call {
802         func: callee,
803         args,
804         destination: Some((Place::Local(RETURN_PLACE),
805                            BasicBlock::new(1))),
806         cleanup: if let Adjustment::RefMut = rcvr_adjustment {
807             Some(BasicBlock::new(3))
808         } else {
809             None
810         },
811         from_hir_call: true,
812     }, false);
813
814     if let Adjustment::RefMut = rcvr_adjustment {
815         // BB #1 - drop for Self
816         block(&mut blocks, vec![], TerminatorKind::Drop {
817             location: Place::Local(rcvr_arg),
818             target: BasicBlock::new(2),
819             unwind: None
820         }, false);
821     }
822     // BB #1/#2 - return
823     block(&mut blocks, vec![], TerminatorKind::Return, false);
824     if let Adjustment::RefMut = rcvr_adjustment {
825         // BB #3 - drop if closure panics
826         block(&mut blocks, vec![], TerminatorKind::Drop {
827             location: Place::Local(rcvr_arg),
828             target: BasicBlock::new(4),
829             unwind: None
830         }, true);
831
832         // BB #4 - resume
833         block(&mut blocks, vec![], TerminatorKind::Resume, true);
834     }
835
836     let mut mir = Mir::new(
837         blocks,
838         IndexVec::from_elem_n(
839             SourceScopeData { span: span, parent_scope: None }, 1
840         ),
841         ClearCrossCrate::Clear,
842         IndexVec::new(),
843         None,
844         local_decls,
845         sig.inputs().len(),
846         vec![],
847         span
848     );
849     if let Abi::RustCall = sig.abi {
850         mir.spread_arg = Some(Local::new(sig.inputs().len()));
851     }
852     mir
853 }
854
855 pub fn build_adt_ctor<'a, 'gcx, 'tcx>(infcx: &infer::InferCtxt<'a, 'gcx, 'tcx>,
856                                       ctor_id: ast::NodeId,
857                                       fields: &[hir::StructField],
858                                       span: Span)
859                                       -> Mir<'tcx>
860 {
861     let tcx = infcx.tcx;
862     let gcx = tcx.global_tcx();
863     let def_id = tcx.hir().local_def_id(ctor_id);
864     let param_env = gcx.param_env(def_id);
865
866     // Normalize the sig.
867     let sig = gcx.fn_sig(def_id)
868         .no_bound_vars()
869         .expect("LBR in ADT constructor signature");
870     let sig = gcx.normalize_erasing_regions(param_env, sig);
871
872     let (adt_def, substs) = match sig.output().sty {
873         ty::Adt(adt_def, substs) => (adt_def, substs),
874         _ => bug!("unexpected type for ADT ctor {:?}", sig.output())
875     };
876
877     debug!("build_ctor: def_id={:?} sig={:?} fields={:?}", def_id, sig, fields);
878
879     let local_decls = local_decls_for_sig(&sig, span);
880
881     let source_info = SourceInfo {
882         span,
883         scope: OUTERMOST_SOURCE_SCOPE
884     };
885
886     let variant_no = if adt_def.is_enum() {
887         adt_def.variant_index_with_id(def_id)
888     } else {
889         VariantIdx::new(0)
890     };
891
892     // return = ADT(arg0, arg1, ...); return
893     let start_block = BasicBlockData {
894         statements: vec![Statement {
895             source_info,
896             kind: StatementKind::Assign(
897                 Place::Local(RETURN_PLACE),
898                 box Rvalue::Aggregate(
899                     box AggregateKind::Adt(adt_def, variant_no, substs, None, None),
900                     (1..sig.inputs().len()+1).map(|i| {
901                         Operand::Move(Place::Local(Local::new(i)))
902                     }).collect()
903                 )
904             )
905         }],
906         terminator: Some(Terminator {
907             source_info,
908             kind: TerminatorKind::Return,
909         }),
910         is_cleanup: false
911     };
912
913     Mir::new(
914         IndexVec::from_elem_n(start_block, 1),
915         IndexVec::from_elem_n(
916             SourceScopeData { span: span, parent_scope: None }, 1
917         ),
918         ClearCrossCrate::Clear,
919         IndexVec::new(),
920         None,
921         local_decls,
922         sig.inputs().len(),
923         vec![],
924         span
925     )
926 }