]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/shim.rs
Rollup merge of #73578 - RalfJung:ty-ctxt-at, r=jonas-schievink
[rust.git] / src / librustc_mir / shim.rs
1 use rustc_hir as hir;
2 use rustc_hir::def_id::DefId;
3 use rustc_hir::lang_items::FnMutTraitLangItem;
4 use rustc_middle::mir::*;
5 use rustc_middle::ty::query::Providers;
6 use rustc_middle::ty::subst::{InternalSubsts, Subst};
7 use rustc_middle::ty::{self, Ty, TyCtxt, TypeFoldable};
8 use rustc_target::abi::VariantIdx;
9
10 use rustc_index::vec::{Idx, IndexVec};
11
12 use rustc_span::Span;
13 use rustc_target::spec::abi::Abi;
14
15 use std::fmt;
16 use std::iter;
17
18 use crate::transform::{
19     add_call_guards, add_moves_for_packed_drops, no_landing_pads, remove_noop_landing_pads,
20     run_passes, simplify,
21 };
22 use crate::util::elaborate_drops::{self, DropElaborator, DropFlagMode, DropStyle};
23 use crate::util::expand_aggregate;
24 use crate::util::patch::MirPatch;
25
26 pub fn provide(providers: &mut Providers<'_>) {
27     providers.mir_shims = make_shim;
28 }
29
30 fn make_shim<'tcx>(tcx: TyCtxt<'tcx>, instance: ty::InstanceDef<'tcx>) -> Body<'tcx> {
31     debug!("make_shim({:?})", instance);
32
33     let mut result = match instance {
34         ty::InstanceDef::Item(..) => bug!("item {:?} passed to make_shim", instance),
35         ty::InstanceDef::VtableShim(def_id) => {
36             build_call_shim(tcx, instance, Some(Adjustment::Deref), CallKind::Direct(def_id), None)
37         }
38         ty::InstanceDef::FnPtrShim(def_id, ty) => {
39             // FIXME(eddyb) support generating shims for a "shallow type",
40             // e.g. `Foo<_>` or `[_]` instead of requiring a fully monomorphic
41             // `Foo<Bar>` or `[String]` etc.
42             assert!(!ty.needs_subst());
43
44             let trait_ = tcx.trait_of_item(def_id).unwrap();
45             let adjustment = match tcx.fn_trait_kind_from_lang_item(trait_) {
46                 Some(ty::ClosureKind::FnOnce) => Adjustment::Identity,
47                 Some(ty::ClosureKind::FnMut | ty::ClosureKind::Fn) => Adjustment::Deref,
48                 None => bug!("fn pointer {:?} is not an fn", ty),
49             };
50             // HACK: we need the "real" argument types for the MIR,
51             // but because our substs are (Self, Args), where Args
52             // is a tuple, we must include the *concrete* argument
53             // types in the MIR. They will be substituted again with
54             // the param-substs, but because they are concrete, this
55             // will not do any harm.
56             let sig = tcx.erase_late_bound_regions(&ty.fn_sig(tcx));
57             let arg_tys = sig.inputs();
58
59             build_call_shim(tcx, instance, Some(adjustment), CallKind::Indirect(ty), Some(arg_tys))
60         }
61         // We are generating a call back to our def-id, which the
62         // codegen backend knows to turn to an actual call, be it
63         // a virtual call, or a direct call to a function for which
64         // indirect calls must be codegen'd differently than direct ones
65         // (such as `#[track_caller]`).
66         ty::InstanceDef::ReifyShim(def_id) => {
67             build_call_shim(tcx, instance, None, CallKind::Direct(def_id), None)
68         }
69         ty::InstanceDef::ClosureOnceShim { call_once: _ } => {
70             let fn_mut = tcx.require_lang_item(FnMutTraitLangItem, None);
71             let call_mut = tcx
72                 .associated_items(fn_mut)
73                 .in_definition_order()
74                 .find(|it| it.kind == ty::AssocKind::Fn)
75                 .unwrap()
76                 .def_id;
77
78             build_call_shim(
79                 tcx,
80                 instance,
81                 Some(Adjustment::RefMut),
82                 CallKind::Direct(call_mut),
83                 None,
84             )
85         }
86         ty::InstanceDef::DropGlue(def_id, ty) => {
87             // FIXME(eddyb) support generating shims for a "shallow type",
88             // e.g. `Foo<_>` or `[_]` instead of requiring a fully monomorphic
89             // `Foo<Bar>` or `[String]` etc.
90             assert!(!ty.needs_subst());
91
92             build_drop_shim(tcx, def_id, ty)
93         }
94         ty::InstanceDef::CloneShim(def_id, ty) => {
95             // FIXME(eddyb) support generating shims for a "shallow type",
96             // e.g. `Foo<_>` or `[_]` instead of requiring a fully monomorphic
97             // `Foo<Bar>` or `[String]` etc.
98             assert!(!ty.needs_subst());
99
100             build_clone_shim(tcx, def_id, ty)
101         }
102         ty::InstanceDef::Virtual(..) => {
103             bug!("InstanceDef::Virtual ({:?}) is for direct calls only", instance)
104         }
105         ty::InstanceDef::Intrinsic(_) => {
106             bug!("creating shims from intrinsics ({:?}) is unsupported", instance)
107         }
108     };
109     debug!("make_shim({:?}) = untransformed {:?}", instance, result);
110
111     run_passes(
112         tcx,
113         &mut result,
114         instance,
115         None,
116         MirPhase::Const,
117         &[&[
118             &add_moves_for_packed_drops::AddMovesForPackedDrops,
119             &no_landing_pads::NoLandingPads::new(tcx),
120             &remove_noop_landing_pads::RemoveNoopLandingPads,
121             &simplify::SimplifyCfg::new("make_shim"),
122             &add_call_guards::CriticalCallEdges,
123         ]],
124     );
125
126     debug!("make_shim({:?}) = {:?}", instance, result);
127
128     result
129 }
130
131 #[derive(Copy, Clone, Debug, PartialEq)]
132 enum Adjustment {
133     /// Pass the receiver as-is.
134     Identity,
135
136     /// We get passed `&[mut] self` and call the target with `*self`.
137     ///
138     /// This either copies `self` (if `Self: Copy`, eg. for function items), or moves out of it
139     /// (for `VtableShim`, which effectively is passed `&own Self`).
140     Deref,
141
142     /// We get passed `self: Self` and call the target with `&mut self`.
143     ///
144     /// In this case we need to ensure that the `Self` is dropped after the call, as the callee
145     /// won't do it for us.
146     RefMut,
147 }
148
149 #[derive(Copy, Clone, Debug, PartialEq)]
150 enum CallKind<'tcx> {
151     /// Call the `FnPtr` that was passed as the receiver.
152     Indirect(Ty<'tcx>),
153
154     /// Call a known `FnDef`.
155     Direct(DefId),
156 }
157
158 fn local_decls_for_sig<'tcx>(
159     sig: &ty::FnSig<'tcx>,
160     span: Span,
161 ) -> IndexVec<Local, LocalDecl<'tcx>> {
162     iter::once(LocalDecl::new(sig.output(), span))
163         .chain(sig.inputs().iter().map(|ity| LocalDecl::new(ity, span).immutable()))
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::outermost(span);
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(blocks, local_decls_for_sig(&sig, span), sig.inputs().len(), span);
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)),
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         match mode {
290             DropFlagMode::Shallow => {
291                 // Drops for the contained fields are "shallow" and "static" - they will simply call
292                 // the field's own drop glue.
293                 DropStyle::Static
294             }
295             DropFlagMode::Deep => {
296                 // The top-level drop is "deep" and "open" - it will be elaborated to a drop ladder
297                 // dropping each field contained in the value.
298                 DropStyle::Open
299             }
300         }
301     }
302
303     fn get_drop_flag(&mut self, _path: Self::Path) -> Option<Operand<'tcx>> {
304         None
305     }
306
307     fn clear_drop_flag(&mut self, _location: Location, _path: Self::Path, _mode: DropFlagMode) {}
308
309     fn field_subpath(&self, _path: Self::Path, _field: Field) -> Option<Self::Path> {
310         None
311     }
312     fn deref_subpath(&self, _path: Self::Path) -> Option<Self::Path> {
313         None
314     }
315     fn downcast_subpath(&self, _path: Self::Path, _variant: VariantIdx) -> Option<Self::Path> {
316         Some(())
317     }
318     fn array_subpath(&self, _path: Self::Path, _index: u32, _size: u32) -> Option<Self::Path> {
319         None
320     }
321 }
322
323 /// Builds a `Clone::clone` shim for `self_ty`. Here, `def_id` is `Clone::clone`.
324 fn build_clone_shim<'tcx>(tcx: TyCtxt<'tcx>, def_id: DefId, self_ty: Ty<'tcx>) -> Body<'tcx> {
325     debug!("build_clone_shim(def_id={:?})", def_id);
326
327     let param_env = tcx.param_env(def_id);
328
329     let mut builder = CloneShimBuilder::new(tcx, def_id, self_ty);
330     let is_copy = self_ty.is_copy_modulo_regions(tcx.at(builder.span), param_env);
331
332     let dest = Place::return_place();
333     let src = tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
334
335     match self_ty.kind {
336         _ if is_copy => builder.copy_shim(),
337         ty::Array(ty, len) => {
338             let len = len.eval_usize(tcx, param_env);
339             builder.array_shim(dest, src, ty, len)
340         }
341         ty::Closure(_, substs) => {
342             builder.tuple_like_shim(dest, src, substs.as_closure().upvar_tys())
343         }
344         ty::Tuple(..) => builder.tuple_like_shim(dest, src, self_ty.tuple_fields()),
345         _ => bug!("clone shim for `{:?}` which is not `Copy` and is not an aggregate", self_ty),
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(self.blocks, self.local_decls, self.sig.inputs().len(), self.span)
382     }
383
384     fn source_info(&self) -> SourceInfo {
385         SourceInfo::outermost(self.span)
386     }
387
388     fn block(
389         &mut self,
390         statements: Vec<Statement<'tcx>>,
391         kind: TerminatorKind<'tcx>,
392         is_cleanup: bool,
393     ) -> BasicBlock {
394         let source_info = self.source_info();
395         self.blocks.push(BasicBlockData {
396             statements,
397             terminator: Some(Terminator { source_info, kind }),
398             is_cleanup,
399         })
400     }
401
402     /// Gives the index of an upcoming BasicBlock, with an offset.
403     /// offset=0 will give you the index of the next BasicBlock,
404     /// offset=1 will give the index of the next-to-next block,
405     /// offset=-1 will give you the index of the last-created block
406     fn block_index_offset(&mut self, offset: usize) -> BasicBlock {
407         BasicBlock::new(self.blocks.len() + offset)
408     }
409
410     fn make_statement(&self, kind: StatementKind<'tcx>) -> Statement<'tcx> {
411         Statement { source_info: self.source_info(), kind }
412     }
413
414     fn copy_shim(&mut self) {
415         let rcvr = self.tcx.mk_place_deref(Place::from(Local::new(1 + 0)));
416         let ret_statement = self.make_statement(StatementKind::Assign(box (
417             Place::return_place(),
418             Rvalue::Use(Operand::Copy(rcvr)),
419         )));
420         self.block(vec![ret_statement], TerminatorKind::Return, false);
421     }
422
423     fn make_place(&mut self, mutability: Mutability, ty: Ty<'tcx>) -> Place<'tcx> {
424         let span = self.span;
425         let mut local = LocalDecl::new(ty, span);
426         if mutability == Mutability::Not {
427             local = local.immutable();
428         }
429         Place::from(self.local_decls.push(local))
430     }
431
432     fn make_clone_call(
433         &mut self,
434         dest: Place<'tcx>,
435         src: Place<'tcx>,
436         ty: Ty<'tcx>,
437         next: BasicBlock,
438         cleanup: BasicBlock,
439     ) {
440         let tcx = self.tcx;
441
442         let substs = tcx.mk_substs_trait(ty, &[]);
443
444         // `func == Clone::clone(&ty) -> ty`
445         let func_ty = tcx.mk_fn_def(self.def_id, substs);
446         let func = Operand::Constant(box Constant {
447             span: self.span,
448             user_ty: None,
449             literal: ty::Const::zero_sized(tcx, func_ty),
450         });
451
452         let ref_loc = self.make_place(
453             Mutability::Not,
454             tcx.mk_ref(tcx.lifetimes.re_erased, ty::TypeAndMut { ty, mutbl: hir::Mutability::Not }),
455         );
456
457         // `let ref_loc: &ty = &src;`
458         let statement = self.make_statement(StatementKind::Assign(box (
459             ref_loc,
460             Rvalue::Ref(tcx.lifetimes.re_erased, BorrowKind::Shared, src),
461         )));
462
463         // `let loc = Clone::clone(ref_loc);`
464         self.block(
465             vec![statement],
466             TerminatorKind::Call {
467                 func,
468                 args: vec![Operand::Move(ref_loc)],
469                 destination: Some((dest, next)),
470                 cleanup: Some(cleanup),
471                 from_hir_call: true,
472                 fn_span: self.span,
473             },
474             false,
475         );
476     }
477
478     fn loop_header(
479         &mut self,
480         beg: Place<'tcx>,
481         end: Place<'tcx>,
482         loop_body: BasicBlock,
483         loop_end: BasicBlock,
484         is_cleanup: bool,
485     ) {
486         let tcx = self.tcx;
487
488         let cond = self.make_place(Mutability::Mut, tcx.types.bool);
489         let compute_cond = self.make_statement(StatementKind::Assign(box (
490             cond,
491             Rvalue::BinaryOp(BinOp::Ne, Operand::Copy(end), Operand::Copy(beg)),
492         )));
493
494         // `if end != beg { goto loop_body; } else { goto loop_end; }`
495         self.block(
496             vec![compute_cond],
497             TerminatorKind::if_(tcx, Operand::Move(cond), loop_body, loop_end),
498             is_cleanup,
499         );
500     }
501
502     fn make_usize(&self, value: u64) -> Box<Constant<'tcx>> {
503         box Constant {
504             span: self.span,
505             user_ty: None,
506             literal: ty::Const::from_usize(self.tcx, value),
507         }
508     }
509
510     fn array_shim(&mut self, dest: Place<'tcx>, src: Place<'tcx>, ty: Ty<'tcx>, len: u64) {
511         let tcx = self.tcx;
512         let span = self.span;
513
514         let beg = self.local_decls.push(LocalDecl::new(tcx.types.usize, span));
515         let end = self.make_place(Mutability::Not, tcx.types.usize);
516
517         // BB #0
518         // `let mut beg = 0;`
519         // `let end = len;`
520         // `goto #1;`
521         let inits = vec![
522             self.make_statement(StatementKind::Assign(box (
523                 Place::from(beg),
524                 Rvalue::Use(Operand::Constant(self.make_usize(0))),
525             ))),
526             self.make_statement(StatementKind::Assign(box (
527                 end,
528                 Rvalue::Use(Operand::Constant(self.make_usize(len))),
529             ))),
530         ];
531         self.block(inits, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
532
533         // BB #1: loop {
534         //     BB #2;
535         //     BB #3;
536         // }
537         // BB #4;
538         self.loop_header(Place::from(beg), end, BasicBlock::new(2), BasicBlock::new(4), false);
539
540         // BB #2
541         // `dest[i] = Clone::clone(src[beg])`;
542         // Goto #3 if ok, #5 if unwinding happens.
543         let dest_field = self.tcx.mk_place_index(dest, beg);
544         let src_field = self.tcx.mk_place_index(src, beg);
545         self.make_clone_call(dest_field, src_field, ty, BasicBlock::new(3), BasicBlock::new(5));
546
547         // BB #3
548         // `beg = beg + 1;`
549         // `goto #1`;
550         let statements = vec![self.make_statement(StatementKind::Assign(box (
551             Place::from(beg),
552             Rvalue::BinaryOp(
553                 BinOp::Add,
554                 Operand::Copy(Place::from(beg)),
555                 Operand::Constant(self.make_usize(1)),
556             ),
557         )))];
558         self.block(statements, TerminatorKind::Goto { target: BasicBlock::new(1) }, false);
559
560         // BB #4
561         // `return dest;`
562         self.block(vec![], TerminatorKind::Return, false);
563
564         // BB #5 (cleanup)
565         // `let end = beg;`
566         // `let mut beg = 0;`
567         // goto #6;
568         let end = beg;
569         let beg = self.local_decls.push(LocalDecl::new(tcx.types.usize, span));
570         let init = self.make_statement(StatementKind::Assign(box (
571             Place::from(beg),
572             Rvalue::Use(Operand::Constant(self.make_usize(0))),
573         )));
574         self.block(vec![init], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
575
576         // BB #6 (cleanup): loop {
577         //     BB #7;
578         //     BB #8;
579         // }
580         // BB #9;
581         self.loop_header(
582             Place::from(beg),
583             Place::from(end),
584             BasicBlock::new(7),
585             BasicBlock::new(9),
586             true,
587         );
588
589         // BB #7 (cleanup)
590         // `drop(dest[beg])`;
591         self.block(
592             vec![],
593             TerminatorKind::Drop {
594                 place: self.tcx.mk_place_index(dest, beg),
595                 target: BasicBlock::new(8),
596                 unwind: None,
597             },
598             true,
599         );
600
601         // BB #8 (cleanup)
602         // `beg = beg + 1;`
603         // `goto #6;`
604         let statement = self.make_statement(StatementKind::Assign(box (
605             Place::from(beg),
606             Rvalue::BinaryOp(
607                 BinOp::Add,
608                 Operand::Copy(Place::from(beg)),
609                 Operand::Constant(self.make_usize(1)),
610             ),
611         )));
612         self.block(vec![statement], TerminatorKind::Goto { target: BasicBlock::new(6) }, true);
613
614         // BB #9 (resume)
615         self.block(vec![], TerminatorKind::Resume, true);
616     }
617
618     fn tuple_like_shim<I>(&mut self, dest: Place<'tcx>, src: Place<'tcx>, tys: I)
619     where
620         I: Iterator<Item = Ty<'tcx>>,
621     {
622         let mut previous_field = None;
623         for (i, ity) in tys.enumerate() {
624             let field = Field::new(i);
625             let src_field = self.tcx.mk_place_field(src, field, ity);
626
627             let dest_field = self.tcx.mk_place_field(dest, field, ity);
628
629             // #(2i + 1) is the cleanup block for the previous clone operation
630             let cleanup_block = self.block_index_offset(1);
631             // #(2i + 2) is the next cloning block
632             // (or the Return terminator if this is the last block)
633             let next_block = self.block_index_offset(2);
634
635             // BB #(2i)
636             // `dest.i = Clone::clone(&src.i);`
637             // Goto #(2i + 2) if ok, #(2i + 1) if unwinding happens.
638             self.make_clone_call(dest_field, src_field, ity, next_block, cleanup_block);
639
640             // BB #(2i + 1) (cleanup)
641             if let Some((previous_field, previous_cleanup)) = previous_field.take() {
642                 // Drop previous field and goto previous cleanup block.
643                 self.block(
644                     vec![],
645                     TerminatorKind::Drop {
646                         place: previous_field,
647                         target: previous_cleanup,
648                         unwind: None,
649                     },
650                     true,
651                 );
652             } else {
653                 // Nothing to drop, just resume.
654                 self.block(vec![], TerminatorKind::Resume, true);
655             }
656
657             previous_field = Some((dest_field, cleanup_block));
658         }
659
660         self.block(vec![], TerminatorKind::Return, false);
661     }
662 }
663
664 /// Builds a "call" shim for `instance`. The shim calls the
665 /// function specified by `call_kind`, first adjusting its first
666 /// argument according to `rcvr_adjustment`.
667 ///
668 /// If `untuple_args` is a vec of types, the second argument of the
669 /// function will be untupled as these types.
670 fn build_call_shim<'tcx>(
671     tcx: TyCtxt<'tcx>,
672     instance: ty::InstanceDef<'tcx>,
673     rcvr_adjustment: Option<Adjustment>,
674     call_kind: CallKind<'tcx>,
675     untuple_args: Option<&[Ty<'tcx>]>,
676 ) -> Body<'tcx> {
677     debug!(
678         "build_call_shim(instance={:?}, rcvr_adjustment={:?}, \
679             call_kind={:?}, untuple_args={:?})",
680         instance, rcvr_adjustment, call_kind, untuple_args
681     );
682
683     let def_id = instance.def_id();
684     let sig = tcx.fn_sig(def_id);
685     let mut sig = tcx.erase_late_bound_regions(&sig);
686
687     if let CallKind::Indirect(fnty) = call_kind {
688         // `sig` determines our local decls, and thus the callee type in the `Call` terminator. This
689         // can only be an `FnDef` or `FnPtr`, but currently will be `Self` since the types come from
690         // the implemented `FnX` trait.
691
692         // Apply the opposite adjustment to the MIR input.
693         let mut inputs_and_output = sig.inputs_and_output.to_vec();
694
695         // Initial signature is `fn(&? Self, Args) -> Self::Output` where `Args` is a tuple of the
696         // fn arguments. `Self` may be passed via (im)mutable reference or by-value.
697         assert_eq!(inputs_and_output.len(), 3);
698
699         // `Self` is always the original fn type `ty`. The MIR call terminator is only defined for
700         // `FnDef` and `FnPtr` callees, not the `Self` type param.
701         let self_arg = &mut inputs_and_output[0];
702         *self_arg = match rcvr_adjustment.unwrap() {
703             Adjustment::Identity => fnty,
704             Adjustment::Deref => tcx.mk_imm_ptr(fnty),
705             Adjustment::RefMut => tcx.mk_mut_ptr(fnty),
706         };
707         sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
708     }
709
710     // FIXME(eddyb) avoid having this snippet both here and in
711     // `Instance::fn_sig` (introduce `InstanceDef::fn_sig`?).
712     if let ty::InstanceDef::VtableShim(..) = instance {
713         // Modify fn(self, ...) to fn(self: *mut Self, ...)
714         let mut inputs_and_output = sig.inputs_and_output.to_vec();
715         let self_arg = &mut inputs_and_output[0];
716         debug_assert!(tcx.generics_of(def_id).has_self && *self_arg == tcx.types.self_param);
717         *self_arg = tcx.mk_mut_ptr(*self_arg);
718         sig.inputs_and_output = tcx.intern_type_list(&inputs_and_output);
719     }
720
721     let span = tcx.def_span(def_id);
722
723     debug!("build_call_shim: sig={:?}", sig);
724
725     let mut local_decls = local_decls_for_sig(&sig, span);
726     let source_info = SourceInfo::outermost(span);
727
728     let rcvr_place = || {
729         assert!(rcvr_adjustment.is_some());
730         Place::from(Local::new(1 + 0))
731     };
732     let mut statements = vec![];
733
734     let rcvr = rcvr_adjustment.map(|rcvr_adjustment| match rcvr_adjustment {
735         Adjustment::Identity => Operand::Move(rcvr_place()),
736         Adjustment::Deref => Operand::Move(tcx.mk_place_deref(rcvr_place())),
737         Adjustment::RefMut => {
738             // let rcvr = &mut rcvr;
739             let ref_rcvr = local_decls.push(
740                 LocalDecl::new(
741                     tcx.mk_ref(
742                         tcx.lifetimes.re_erased,
743                         ty::TypeAndMut { ty: sig.inputs()[0], mutbl: hir::Mutability::Mut },
744                     ),
745                     span,
746                 )
747                 .immutable(),
748             );
749             let borrow_kind = BorrowKind::Mut { allow_two_phase_borrow: false };
750             statements.push(Statement {
751                 source_info,
752                 kind: StatementKind::Assign(box (
753                     Place::from(ref_rcvr),
754                     Rvalue::Ref(tcx.lifetimes.re_erased, borrow_kind, rcvr_place()),
755                 )),
756             });
757             Operand::Move(Place::from(ref_rcvr))
758         }
759     });
760
761     let (callee, mut args) = match call_kind {
762         // `FnPtr` call has no receiver. Args are untupled below.
763         CallKind::Indirect(_) => (rcvr.unwrap(), vec![]),
764
765         // `FnDef` call with optional receiver.
766         CallKind::Direct(def_id) => {
767             let ty = tcx.type_of(def_id);
768             (
769                 Operand::Constant(box Constant {
770                     span,
771                     user_ty: None,
772                     literal: ty::Const::zero_sized(tcx, ty),
773                 }),
774                 rcvr.into_iter().collect::<Vec<_>>(),
775             )
776         }
777     };
778
779     let mut arg_range = 0..sig.inputs().len();
780
781     // Take the `self` ("receiver") argument out of the range (it's adjusted above).
782     if rcvr_adjustment.is_some() {
783         arg_range.start += 1;
784     }
785
786     // Take the last argument, if we need to untuple it (handled below).
787     if untuple_args.is_some() {
788         arg_range.end -= 1;
789     }
790
791     // Pass all of the non-special arguments directly.
792     args.extend(arg_range.map(|i| Operand::Move(Place::from(Local::new(1 + i)))));
793
794     // Untuple the last argument, if we have to.
795     if let Some(untuple_args) = untuple_args {
796         let tuple_arg = Local::new(1 + (sig.inputs().len() - 1));
797         args.extend(untuple_args.iter().enumerate().map(|(i, ity)| {
798             Operand::Move(tcx.mk_place_field(Place::from(tuple_arg), Field::new(i), *ity))
799         }));
800     }
801
802     let n_blocks = if let Some(Adjustment::RefMut) = rcvr_adjustment { 5 } else { 2 };
803     let mut blocks = IndexVec::with_capacity(n_blocks);
804     let block = |blocks: &mut IndexVec<_, _>, statements, kind, is_cleanup| {
805         blocks.push(BasicBlockData {
806             statements,
807             terminator: Some(Terminator { source_info, kind }),
808             is_cleanup,
809         })
810     };
811
812     // BB #0
813     block(
814         &mut blocks,
815         statements,
816         TerminatorKind::Call {
817             func: callee,
818             args,
819             destination: Some((Place::return_place(), BasicBlock::new(1))),
820             cleanup: if let Some(Adjustment::RefMut) = rcvr_adjustment {
821                 Some(BasicBlock::new(3))
822             } else {
823                 None
824             },
825             from_hir_call: true,
826             fn_span: span,
827         },
828         false,
829     );
830
831     if let Some(Adjustment::RefMut) = rcvr_adjustment {
832         // BB #1 - drop for Self
833         block(
834             &mut blocks,
835             vec![],
836             TerminatorKind::Drop { place: rcvr_place(), target: BasicBlock::new(2), unwind: None },
837             false,
838         );
839     }
840     // BB #1/#2 - return
841     block(&mut blocks, vec![], TerminatorKind::Return, false);
842     if let Some(Adjustment::RefMut) = rcvr_adjustment {
843         // BB #3 - drop if closure panics
844         block(
845             &mut blocks,
846             vec![],
847             TerminatorKind::Drop { place: rcvr_place(), target: BasicBlock::new(4), unwind: None },
848             true,
849         );
850
851         // BB #4 - resume
852         block(&mut blocks, vec![], TerminatorKind::Resume, true);
853     }
854
855     let mut body = new_body(blocks, local_decls, sig.inputs().len(), span);
856
857     if let Abi::RustCall = sig.abi {
858         body.spread_arg = Some(Local::new(sig.inputs().len()));
859     }
860
861     body
862 }
863
864 pub fn build_adt_ctor(tcx: TyCtxt<'_>, ctor_id: DefId) -> Body<'_> {
865     debug_assert!(tcx.is_constructor(ctor_id));
866
867     let span =
868         tcx.hir().span_if_local(ctor_id).unwrap_or_else(|| bug!("no span for ctor {:?}", ctor_id));
869
870     let param_env = tcx.param_env(ctor_id);
871
872     // Normalize the sig.
873     let sig = tcx.fn_sig(ctor_id).no_bound_vars().expect("LBR in ADT constructor signature");
874     let sig = tcx.normalize_erasing_regions(param_env, sig);
875
876     let (adt_def, substs) = match sig.output().kind {
877         ty::Adt(adt_def, substs) => (adt_def, substs),
878         _ => bug!("unexpected type for ADT ctor {:?}", sig.output()),
879     };
880
881     debug!("build_ctor: ctor_id={:?} sig={:?}", ctor_id, sig);
882
883     let local_decls = local_decls_for_sig(&sig, span);
884
885     let source_info = SourceInfo::outermost(span);
886
887     let variant_index = if adt_def.is_enum() {
888         adt_def.variant_index_with_ctor_id(ctor_id)
889     } else {
890         VariantIdx::new(0)
891     };
892
893     // Generate the following MIR:
894     //
895     // (return as Variant).field0 = arg0;
896     // (return as Variant).field1 = arg1;
897     //
898     // return;
899     debug!("build_ctor: variant_index={:?}", variant_index);
900
901     let statements = expand_aggregate(
902         Place::return_place(),
903         adt_def.variants[variant_index].fields.iter().enumerate().map(|(idx, field_def)| {
904             (Operand::Move(Place::from(Local::new(idx + 1))), field_def.ty(tcx, substs))
905         }),
906         AggregateKind::Adt(adt_def, variant_index, substs, None, None),
907         source_info,
908         tcx,
909     )
910     .collect();
911
912     let start_block = BasicBlockData {
913         statements,
914         terminator: Some(Terminator { source_info, kind: TerminatorKind::Return }),
915         is_cleanup: false,
916     };
917
918     let body =
919         new_body(IndexVec::from_elem_n(start_block, 1), local_decls, sig.inputs().len(), span);
920
921     crate::util::dump_mir(
922         tcx,
923         None,
924         "mir_map",
925         &0,
926         crate::transform::MirSource::item(ctor_id),
927         &body,
928         |_, _| Ok(()),
929     );
930
931     body
932 }