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