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