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