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