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