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