]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/inline.rs
Rollup merge of #93392 - GKFX:char-docs, r=scottmcm
[rust.git] / compiler / rustc_mir_transform / src / inline.rs
1 //! Inlining pass for MIR functions
2
3 use rustc_attr::InlineAttr;
4 use rustc_hir as hir;
5 use rustc_index::bit_set::BitSet;
6 use rustc_index::vec::Idx;
7 use rustc_middle::middle::codegen_fn_attrs::{CodegenFnAttrFlags, CodegenFnAttrs};
8 use rustc_middle::mir::visit::*;
9 use rustc_middle::mir::*;
10 use rustc_middle::ty::subst::Subst;
11 use rustc_middle::ty::{self, ConstKind, Instance, InstanceDef, ParamEnv, Ty, TyCtxt};
12 use rustc_span::{hygiene::ExpnKind, ExpnData, Span};
13 use rustc_target::spec::abi::Abi;
14
15 use super::simplify::{remove_dead_blocks, CfgSimplifier};
16 use crate::MirPass;
17 use std::iter;
18 use std::ops::{Range, RangeFrom};
19
20 crate mod cycle;
21
22 const INSTR_COST: usize = 5;
23 const CALL_PENALTY: usize = 25;
24 const LANDINGPAD_PENALTY: usize = 50;
25 const RESUME_PENALTY: usize = 45;
26
27 const UNKNOWN_SIZE_COST: usize = 10;
28
29 pub struct Inline;
30
31 #[derive(Copy, Clone, Debug)]
32 struct CallSite<'tcx> {
33     callee: Instance<'tcx>,
34     fn_sig: ty::PolyFnSig<'tcx>,
35     block: BasicBlock,
36     target: Option<BasicBlock>,
37     source_info: SourceInfo,
38 }
39
40 impl<'tcx> MirPass<'tcx> for Inline {
41     fn is_enabled(&self, sess: &rustc_session::Session) -> bool {
42         if let Some(enabled) = sess.opts.debugging_opts.inline_mir {
43             return enabled;
44         }
45
46         sess.opts.mir_opt_level() >= 3
47     }
48
49     fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) {
50         let span = trace_span!("inline", body = %tcx.def_path_str(body.source.def_id()));
51         let _guard = span.enter();
52         if inline(tcx, body) {
53             debug!("running simplify cfg on {:?}", body.source);
54             CfgSimplifier::new(body).simplify();
55             remove_dead_blocks(tcx, body);
56         }
57     }
58 }
59
60 fn inline<'tcx>(tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) -> bool {
61     let def_id = body.source.def_id();
62     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id.expect_local());
63
64     // Only do inlining into fn bodies.
65     if !tcx.hir().body_owner_kind(hir_id).is_fn_or_closure() {
66         return false;
67     }
68     if body.source.promoted.is_some() {
69         return false;
70     }
71     // Avoid inlining into generators, since their `optimized_mir` is used for layout computation,
72     // which can create a cycle, even when no attempt is made to inline the function in the other
73     // direction.
74     if body.generator.is_some() {
75         return false;
76     }
77
78     let mut this = Inliner {
79         tcx,
80         param_env: tcx.param_env_reveal_all_normalized(body.source.def_id()),
81         codegen_fn_attrs: tcx.codegen_fn_attrs(body.source.def_id()),
82         hir_id,
83         history: Vec::new(),
84         changed: false,
85     };
86     let blocks = BasicBlock::new(0)..body.basic_blocks().next_index();
87     this.process_blocks(body, blocks);
88     this.changed
89 }
90
91 struct Inliner<'tcx> {
92     tcx: TyCtxt<'tcx>,
93     param_env: ParamEnv<'tcx>,
94     /// Caller codegen attributes.
95     codegen_fn_attrs: &'tcx CodegenFnAttrs,
96     /// Caller HirID.
97     hir_id: hir::HirId,
98     /// Stack of inlined Instances.
99     history: Vec<ty::Instance<'tcx>>,
100     /// Indicates that the caller body has been modified.
101     changed: bool,
102 }
103
104 impl<'tcx> Inliner<'tcx> {
105     fn process_blocks(&mut self, caller_body: &mut Body<'tcx>, blocks: Range<BasicBlock>) {
106         for bb in blocks {
107             let bb_data = &caller_body[bb];
108             if bb_data.is_cleanup {
109                 continue;
110             }
111
112             let callsite = match self.resolve_callsite(caller_body, bb, bb_data) {
113                 None => continue,
114                 Some(it) => it,
115             };
116
117             let span = trace_span!("process_blocks", %callsite.callee, ?bb);
118             let _guard = span.enter();
119
120             match self.try_inlining(caller_body, &callsite) {
121                 Err(reason) => {
122                     debug!("not-inlined {} [{}]", callsite.callee, reason);
123                     continue;
124                 }
125                 Ok(new_blocks) => {
126                     debug!("inlined {}", callsite.callee);
127                     self.changed = true;
128                     self.history.push(callsite.callee);
129                     self.process_blocks(caller_body, new_blocks);
130                     self.history.pop();
131                 }
132             }
133         }
134     }
135
136     /// Attempts to inline a callsite into the caller body. When successful returns basic blocks
137     /// containing the inlined body. Otherwise returns an error describing why inlining didn't take
138     /// place.
139     fn try_inlining(
140         &self,
141         caller_body: &mut Body<'tcx>,
142         callsite: &CallSite<'tcx>,
143     ) -> Result<std::ops::Range<BasicBlock>, &'static str> {
144         let callee_attrs = self.tcx.codegen_fn_attrs(callsite.callee.def_id());
145         self.check_codegen_attributes(callsite, callee_attrs)?;
146         self.check_mir_is_available(caller_body, &callsite.callee)?;
147         let callee_body = self.tcx.instance_mir(callsite.callee.def);
148         self.check_mir_body(callsite, callee_body, callee_attrs)?;
149
150         if !self.tcx.consider_optimizing(|| {
151             format!("Inline {:?} into {:?}", callsite.callee, caller_body.source)
152         }) {
153             return Err("optimization fuel exhausted");
154         }
155
156         let callee_body = callsite.callee.subst_mir_and_normalize_erasing_regions(
157             self.tcx,
158             self.param_env,
159             callee_body.clone(),
160         );
161
162         let old_blocks = caller_body.basic_blocks().next_index();
163         self.inline_call(caller_body, &callsite, callee_body);
164         let new_blocks = old_blocks..caller_body.basic_blocks().next_index();
165
166         Ok(new_blocks)
167     }
168
169     fn check_mir_is_available(
170         &self,
171         caller_body: &Body<'tcx>,
172         callee: &Instance<'tcx>,
173     ) -> Result<(), &'static str> {
174         if callee.def_id() == caller_body.source.def_id() {
175             return Err("self-recursion");
176         }
177
178         match callee.def {
179             InstanceDef::Item(_) => {
180                 // If there is no MIR available (either because it was not in metadata or
181                 // because it has no MIR because it's an extern function), then the inliner
182                 // won't cause cycles on this.
183                 if !self.tcx.is_mir_available(callee.def_id()) {
184                     return Err("item MIR unavailable");
185                 }
186             }
187             // These have no own callable MIR.
188             InstanceDef::Intrinsic(_) | InstanceDef::Virtual(..) => {
189                 return Err("instance without MIR (intrinsic / virtual)");
190             }
191             // This cannot result in an immediate cycle since the callee MIR is a shim, which does
192             // not get any optimizations run on it. Any subsequent inlining may cause cycles, but we
193             // do not need to catch this here, we can wait until the inliner decides to continue
194             // inlining a second time.
195             InstanceDef::VtableShim(_)
196             | InstanceDef::ReifyShim(_)
197             | InstanceDef::FnPtrShim(..)
198             | InstanceDef::ClosureOnceShim { .. }
199             | InstanceDef::DropGlue(..)
200             | InstanceDef::CloneShim(..) => return Ok(()),
201         }
202
203         if self.tcx.is_constructor(callee.def_id()) {
204             trace!("constructors always have MIR");
205             // Constructor functions cannot cause a query cycle.
206             return Ok(());
207         }
208
209         if let Some(callee_def_id) = callee.def_id().as_local() {
210             let callee_hir_id = self.tcx.hir().local_def_id_to_hir_id(callee_def_id);
211             // Avoid a cycle here by only using `instance_mir` only if we have
212             // a lower `HirId` than the callee. This ensures that the callee will
213             // not inline us. This trick only works without incremental compilation.
214             // So don't do it if that is enabled.
215             if !self.tcx.dep_graph.is_fully_enabled() && self.hir_id.index() < callee_hir_id.index()
216             {
217                 return Ok(());
218             }
219
220             // If we know for sure that the function we're calling will itself try to
221             // call us, then we avoid inlining that function.
222             if self
223                 .tcx
224                 .mir_callgraph_reachable((*callee, caller_body.source.def_id().expect_local()))
225             {
226                 return Err("caller might be reachable from callee (query cycle avoidance)");
227             }
228
229             Ok(())
230         } else {
231             // This cannot result in an immediate cycle since the callee MIR is from another crate
232             // and is already optimized. Any subsequent inlining may cause cycles, but we do
233             // not need to catch this here, we can wait until the inliner decides to continue
234             // inlining a second time.
235             trace!("functions from other crates always have MIR");
236             Ok(())
237         }
238     }
239
240     fn resolve_callsite(
241         &self,
242         caller_body: &Body<'tcx>,
243         bb: BasicBlock,
244         bb_data: &BasicBlockData<'tcx>,
245     ) -> Option<CallSite<'tcx>> {
246         // Only consider direct calls to functions
247         let terminator = bb_data.terminator();
248         if let TerminatorKind::Call { ref func, ref destination, .. } = terminator.kind {
249             let func_ty = func.ty(caller_body, self.tcx);
250             if let ty::FnDef(def_id, substs) = *func_ty.kind() {
251                 // To resolve an instance its substs have to be fully normalized.
252                 let substs = self.tcx.normalize_erasing_regions(self.param_env, substs);
253                 let callee =
254                     Instance::resolve(self.tcx, self.param_env, def_id, substs).ok().flatten()?;
255
256                 if let InstanceDef::Virtual(..) | InstanceDef::Intrinsic(_) = callee.def {
257                     return None;
258                 }
259
260                 let fn_sig = self.tcx.fn_sig(def_id).subst(self.tcx, substs);
261
262                 return Some(CallSite {
263                     callee,
264                     fn_sig,
265                     block: bb,
266                     target: destination.map(|(_, target)| target),
267                     source_info: terminator.source_info,
268                 });
269             }
270         }
271
272         None
273     }
274
275     /// Returns an error if inlining is not possible based on codegen attributes alone. A success
276     /// indicates that inlining decision should be based on other criteria.
277     fn check_codegen_attributes(
278         &self,
279         callsite: &CallSite<'tcx>,
280         callee_attrs: &CodegenFnAttrs,
281     ) -> Result<(), &'static str> {
282         if let InlineAttr::Never = callee_attrs.inline {
283             return Err("never inline hint");
284         }
285
286         // Only inline local functions if they would be eligible for cross-crate
287         // inlining. This is to ensure that the final crate doesn't have MIR that
288         // reference unexported symbols
289         if callsite.callee.def_id().is_local() {
290             let is_generic = callsite.callee.substs.non_erasable_generics().next().is_some();
291             if !is_generic && !callee_attrs.requests_inline() {
292                 return Err("not exported");
293             }
294         }
295
296         if callsite.fn_sig.c_variadic() {
297             return Err("C variadic");
298         }
299
300         if callee_attrs.flags.contains(CodegenFnAttrFlags::NAKED) {
301             return Err("naked");
302         }
303
304         if callee_attrs.flags.contains(CodegenFnAttrFlags::COLD) {
305             return Err("cold");
306         }
307
308         if callee_attrs.no_sanitize != self.codegen_fn_attrs.no_sanitize {
309             return Err("incompatible sanitizer set");
310         }
311
312         if callee_attrs.instruction_set != self.codegen_fn_attrs.instruction_set {
313             return Err("incompatible instruction set");
314         }
315
316         for feature in &callee_attrs.target_features {
317             if !self.codegen_fn_attrs.target_features.contains(feature) {
318                 return Err("incompatible target feature");
319             }
320         }
321
322         Ok(())
323     }
324
325     /// Returns inlining decision that is based on the examination of callee MIR body.
326     /// Assumes that codegen attributes have been checked for compatibility already.
327     #[instrument(level = "debug", skip(self, callee_body))]
328     fn check_mir_body(
329         &self,
330         callsite: &CallSite<'tcx>,
331         callee_body: &Body<'tcx>,
332         callee_attrs: &CodegenFnAttrs,
333     ) -> Result<(), &'static str> {
334         let tcx = self.tcx;
335
336         let mut threshold = if callee_attrs.requests_inline() {
337             self.tcx.sess.opts.debugging_opts.inline_mir_hint_threshold.unwrap_or(100)
338         } else {
339             self.tcx.sess.opts.debugging_opts.inline_mir_threshold.unwrap_or(50)
340         };
341
342         // Give a bonus functions with a small number of blocks,
343         // We normally have two or three blocks for even
344         // very small functions.
345         if callee_body.basic_blocks().len() <= 3 {
346             threshold += threshold / 4;
347         }
348         debug!("    final inline threshold = {}", threshold);
349
350         // FIXME: Give a bonus to functions with only a single caller
351         let mut first_block = true;
352         let mut cost = 0;
353
354         // Traverse the MIR manually so we can account for the effects of
355         // inlining on the CFG.
356         let mut work_list = vec![START_BLOCK];
357         let mut visited = BitSet::new_empty(callee_body.basic_blocks().len());
358         while let Some(bb) = work_list.pop() {
359             if !visited.insert(bb.index()) {
360                 continue;
361             }
362             let blk = &callee_body.basic_blocks()[bb];
363
364             for stmt in &blk.statements {
365                 // Don't count StorageLive/StorageDead in the inlining cost.
366                 match stmt.kind {
367                     StatementKind::StorageLive(_)
368                     | StatementKind::StorageDead(_)
369                     | StatementKind::Nop => {}
370                     _ => cost += INSTR_COST,
371                 }
372             }
373             let term = blk.terminator();
374             let mut is_drop = false;
375             match term.kind {
376                 TerminatorKind::Drop { ref place, target, unwind }
377                 | TerminatorKind::DropAndReplace { ref place, target, unwind, .. } => {
378                     is_drop = true;
379                     work_list.push(target);
380                     // If the place doesn't actually need dropping, treat it like
381                     // a regular goto.
382                     let ty = callsite.callee.subst_mir(self.tcx, &place.ty(callee_body, tcx).ty);
383                     if ty.needs_drop(tcx, self.param_env) {
384                         cost += CALL_PENALTY;
385                         if let Some(unwind) = unwind {
386                             cost += LANDINGPAD_PENALTY;
387                             work_list.push(unwind);
388                         }
389                     } else {
390                         cost += INSTR_COST;
391                     }
392                 }
393
394                 TerminatorKind::Unreachable | TerminatorKind::Call { destination: None, .. }
395                     if first_block =>
396                 {
397                     // If the function always diverges, don't inline
398                     // unless the cost is zero
399                     threshold = 0;
400                 }
401
402                 TerminatorKind::Call { func: Operand::Constant(ref f), cleanup, .. } => {
403                     if let ty::FnDef(def_id, substs) =
404                         *callsite.callee.subst_mir(self.tcx, &f.literal.ty()).kind()
405                     {
406                         let substs = self.tcx.normalize_erasing_regions(self.param_env, substs);
407                         if let Ok(Some(instance)) =
408                             Instance::resolve(self.tcx, self.param_env, def_id, substs)
409                         {
410                             if callsite.callee.def_id() == instance.def_id() {
411                                 return Err("self-recursion");
412                             } else if self.history.contains(&instance) {
413                                 return Err("already inlined");
414                             }
415                         }
416                         // Don't give intrinsics the extra penalty for calls
417                         let f = tcx.fn_sig(def_id);
418                         if f.abi() == Abi::RustIntrinsic || f.abi() == Abi::PlatformIntrinsic {
419                             cost += INSTR_COST;
420                         } else {
421                             cost += CALL_PENALTY;
422                         }
423                     } else {
424                         cost += CALL_PENALTY;
425                     }
426                     if cleanup.is_some() {
427                         cost += LANDINGPAD_PENALTY;
428                     }
429                 }
430                 TerminatorKind::Assert { cleanup, .. } => {
431                     cost += CALL_PENALTY;
432
433                     if cleanup.is_some() {
434                         cost += LANDINGPAD_PENALTY;
435                     }
436                 }
437                 TerminatorKind::Resume => cost += RESUME_PENALTY,
438                 TerminatorKind::InlineAsm { cleanup, .. } => {
439                     cost += INSTR_COST;
440
441                     if cleanup.is_some() {
442                         cost += LANDINGPAD_PENALTY;
443                     }
444                 }
445                 _ => cost += INSTR_COST,
446             }
447
448             if !is_drop {
449                 for &succ in term.successors() {
450                     work_list.push(succ);
451                 }
452             }
453
454             first_block = false;
455         }
456
457         // Count up the cost of local variables and temps, if we know the size
458         // use that, otherwise we use a moderately-large dummy cost.
459
460         let ptr_size = tcx.data_layout.pointer_size.bytes();
461
462         for v in callee_body.vars_and_temps_iter() {
463             let ty = callsite.callee.subst_mir(self.tcx, &callee_body.local_decls[v].ty);
464             // Cost of the var is the size in machine-words, if we know
465             // it.
466             if let Some(size) = type_size_of(tcx, self.param_env, ty) {
467                 cost += ((size + ptr_size - 1) / ptr_size) as usize;
468             } else {
469                 cost += UNKNOWN_SIZE_COST;
470             }
471         }
472
473         if let InlineAttr::Always = callee_attrs.inline {
474             debug!("INLINING {:?} because inline(always) [cost={}]", callsite, cost);
475             Ok(())
476         } else {
477             if cost <= threshold {
478                 debug!("INLINING {:?} [cost={} <= threshold={}]", callsite, cost, threshold);
479                 Ok(())
480             } else {
481                 debug!("NOT inlining {:?} [cost={} > threshold={}]", callsite, cost, threshold);
482                 Err("cost above threshold")
483             }
484         }
485     }
486
487     fn inline_call(
488         &self,
489         caller_body: &mut Body<'tcx>,
490         callsite: &CallSite<'tcx>,
491         mut callee_body: Body<'tcx>,
492     ) {
493         let terminator = caller_body[callsite.block].terminator.take().unwrap();
494         match terminator.kind {
495             TerminatorKind::Call { args, destination, cleanup, .. } => {
496                 // If the call is something like `a[*i] = f(i)`, where
497                 // `i : &mut usize`, then just duplicating the `a[*i]`
498                 // Place could result in two different locations if `f`
499                 // writes to `i`. To prevent this we need to create a temporary
500                 // borrow of the place and pass the destination as `*temp` instead.
501                 fn dest_needs_borrow(place: Place<'_>) -> bool {
502                     for elem in place.projection.iter() {
503                         match elem {
504                             ProjectionElem::Deref | ProjectionElem::Index(_) => return true,
505                             _ => {}
506                         }
507                     }
508
509                     false
510                 }
511
512                 let dest = if let Some((destination_place, _)) = destination {
513                     if dest_needs_borrow(destination_place) {
514                         trace!("creating temp for return destination");
515                         let dest = Rvalue::Ref(
516                             self.tcx.lifetimes.re_erased,
517                             BorrowKind::Mut { allow_two_phase_borrow: false },
518                             destination_place,
519                         );
520                         let dest_ty = dest.ty(caller_body, self.tcx);
521                         let temp = Place::from(self.new_call_temp(caller_body, &callsite, dest_ty));
522                         caller_body[callsite.block].statements.push(Statement {
523                             source_info: callsite.source_info,
524                             kind: StatementKind::Assign(Box::new((temp, dest))),
525                         });
526                         self.tcx.mk_place_deref(temp)
527                     } else {
528                         destination_place
529                     }
530                 } else {
531                     trace!("creating temp for return place");
532                     Place::from(self.new_call_temp(caller_body, &callsite, callee_body.return_ty()))
533                 };
534
535                 // Copy the arguments if needed.
536                 let args: Vec<_> = self.make_call_args(args, &callsite, caller_body, &callee_body);
537
538                 let mut integrator = Integrator {
539                     args: &args,
540                     new_locals: Local::new(caller_body.local_decls.len())..,
541                     new_scopes: SourceScope::new(caller_body.source_scopes.len())..,
542                     new_blocks: BasicBlock::new(caller_body.basic_blocks().len())..,
543                     destination: dest,
544                     return_block: callsite.target,
545                     cleanup_block: cleanup,
546                     in_cleanup_block: false,
547                     tcx: self.tcx,
548                     callsite_span: callsite.source_info.span,
549                     body_span: callee_body.span,
550                     always_live_locals: BitSet::new_filled(callee_body.local_decls.len()),
551                 };
552
553                 // Map all `Local`s, `SourceScope`s and `BasicBlock`s to new ones
554                 // (or existing ones, in a few special cases) in the caller.
555                 integrator.visit_body(&mut callee_body);
556
557                 for scope in &mut callee_body.source_scopes {
558                     // FIXME(eddyb) move this into a `fn visit_scope_data` in `Integrator`.
559                     if scope.parent_scope.is_none() {
560                         let callsite_scope = &caller_body.source_scopes[callsite.source_info.scope];
561
562                         // Attach the outermost callee scope as a child of the callsite
563                         // scope, via the `parent_scope` and `inlined_parent_scope` chains.
564                         scope.parent_scope = Some(callsite.source_info.scope);
565                         assert_eq!(scope.inlined_parent_scope, None);
566                         scope.inlined_parent_scope = if callsite_scope.inlined.is_some() {
567                             Some(callsite.source_info.scope)
568                         } else {
569                             callsite_scope.inlined_parent_scope
570                         };
571
572                         // Mark the outermost callee scope as an inlined one.
573                         assert_eq!(scope.inlined, None);
574                         scope.inlined = Some((callsite.callee, callsite.source_info.span));
575                     } else if scope.inlined_parent_scope.is_none() {
576                         // Make it easy to find the scope with `inlined` set above.
577                         scope.inlined_parent_scope =
578                             Some(integrator.map_scope(OUTERMOST_SOURCE_SCOPE));
579                     }
580                 }
581
582                 // If there are any locals without storage markers, give them storage only for the
583                 // duration of the call.
584                 for local in callee_body.vars_and_temps_iter() {
585                     if integrator.always_live_locals.contains(local) {
586                         let new_local = integrator.map_local(local);
587                         caller_body[callsite.block].statements.push(Statement {
588                             source_info: callsite.source_info,
589                             kind: StatementKind::StorageLive(new_local),
590                         });
591                     }
592                 }
593                 if let Some(block) = callsite.target {
594                     // To avoid repeated O(n) insert, push any new statements to the end and rotate
595                     // the slice once.
596                     let mut n = 0;
597                     for local in callee_body.vars_and_temps_iter().rev() {
598                         if integrator.always_live_locals.contains(local) {
599                             let new_local = integrator.map_local(local);
600                             caller_body[block].statements.push(Statement {
601                                 source_info: callsite.source_info,
602                                 kind: StatementKind::StorageDead(new_local),
603                             });
604                             n += 1;
605                         }
606                     }
607                     caller_body[block].statements.rotate_right(n);
608                 }
609
610                 // Insert all of the (mapped) parts of the callee body into the caller.
611                 caller_body.local_decls.extend(callee_body.drain_vars_and_temps());
612                 caller_body.source_scopes.extend(&mut callee_body.source_scopes.drain(..));
613                 caller_body.var_debug_info.append(&mut callee_body.var_debug_info);
614                 caller_body.basic_blocks_mut().extend(callee_body.basic_blocks_mut().drain(..));
615
616                 caller_body[callsite.block].terminator = Some(Terminator {
617                     source_info: callsite.source_info,
618                     kind: TerminatorKind::Goto { target: integrator.map_block(START_BLOCK) },
619                 });
620
621                 // Copy only unevaluated constants from the callee_body into the caller_body.
622                 // Although we are only pushing `ConstKind::Unevaluated` consts to
623                 // `required_consts`, here we may not only have `ConstKind::Unevaluated`
624                 // because we are calling `subst_and_normalize_erasing_regions`.
625                 caller_body.required_consts.extend(
626                     callee_body.required_consts.iter().copied().filter(|&ct| {
627                         match ct.literal.const_for_ty() {
628                             Some(ct) => matches!(ct.val, ConstKind::Unevaluated(_)),
629                             None => true,
630                         }
631                     }),
632                 );
633             }
634             kind => bug!("unexpected terminator kind {:?}", kind),
635         }
636     }
637
638     fn make_call_args(
639         &self,
640         args: Vec<Operand<'tcx>>,
641         callsite: &CallSite<'tcx>,
642         caller_body: &mut Body<'tcx>,
643         callee_body: &Body<'tcx>,
644     ) -> Vec<Local> {
645         let tcx = self.tcx;
646
647         // There is a bit of a mismatch between the *caller* of a closure and the *callee*.
648         // The caller provides the arguments wrapped up in a tuple:
649         //
650         //     tuple_tmp = (a, b, c)
651         //     Fn::call(closure_ref, tuple_tmp)
652         //
653         // meanwhile the closure body expects the arguments (here, `a`, `b`, and `c`)
654         // as distinct arguments. (This is the "rust-call" ABI hack.) Normally, codegen has
655         // the job of unpacking this tuple. But here, we are codegen. =) So we want to create
656         // a vector like
657         //
658         //     [closure_ref, tuple_tmp.0, tuple_tmp.1, tuple_tmp.2]
659         //
660         // Except for one tiny wrinkle: we don't actually want `tuple_tmp.0`. It's more convenient
661         // if we "spill" that into *another* temporary, so that we can map the argument
662         // variable in the callee MIR directly to an argument variable on our side.
663         // So we introduce temporaries like:
664         //
665         //     tmp0 = tuple_tmp.0
666         //     tmp1 = tuple_tmp.1
667         //     tmp2 = tuple_tmp.2
668         //
669         // and the vector is `[closure_ref, tmp0, tmp1, tmp2]`.
670         if callsite.fn_sig.abi() == Abi::RustCall && callee_body.spread_arg.is_none() {
671             let mut args = args.into_iter();
672             let self_ = self.create_temp_if_necessary(args.next().unwrap(), callsite, caller_body);
673             let tuple = self.create_temp_if_necessary(args.next().unwrap(), callsite, caller_body);
674             assert!(args.next().is_none());
675
676             let tuple = Place::from(tuple);
677             let ty::Tuple(tuple_tys) = tuple.ty(caller_body, tcx).ty.kind() else {
678                 bug!("Closure arguments are not passed as a tuple");
679             };
680
681             // The `closure_ref` in our example above.
682             let closure_ref_arg = iter::once(self_);
683
684             // The `tmp0`, `tmp1`, and `tmp2` in our example abonve.
685             let tuple_tmp_args = tuple_tys.iter().enumerate().map(|(i, ty)| {
686                 // This is e.g., `tuple_tmp.0` in our example above.
687                 let tuple_field =
688                     Operand::Move(tcx.mk_place_field(tuple, Field::new(i), ty.expect_ty()));
689
690                 // Spill to a local to make e.g., `tmp0`.
691                 self.create_temp_if_necessary(tuple_field, callsite, caller_body)
692             });
693
694             closure_ref_arg.chain(tuple_tmp_args).collect()
695         } else {
696             args.into_iter()
697                 .map(|a| self.create_temp_if_necessary(a, callsite, caller_body))
698                 .collect()
699         }
700     }
701
702     /// If `arg` is already a temporary, returns it. Otherwise, introduces a fresh
703     /// temporary `T` and an instruction `T = arg`, and returns `T`.
704     fn create_temp_if_necessary(
705         &self,
706         arg: Operand<'tcx>,
707         callsite: &CallSite<'tcx>,
708         caller_body: &mut Body<'tcx>,
709     ) -> Local {
710         // Reuse the operand if it is a moved temporary.
711         if let Operand::Move(place) = &arg {
712             if let Some(local) = place.as_local() {
713                 if caller_body.local_kind(local) == LocalKind::Temp {
714                     return local;
715                 }
716             }
717         }
718
719         // Otherwise, create a temporary for the argument.
720         trace!("creating temp for argument {:?}", arg);
721         let arg_ty = arg.ty(caller_body, self.tcx);
722         let local = self.new_call_temp(caller_body, callsite, arg_ty);
723         caller_body[callsite.block].statements.push(Statement {
724             source_info: callsite.source_info,
725             kind: StatementKind::Assign(Box::new((Place::from(local), Rvalue::Use(arg)))),
726         });
727         local
728     }
729
730     /// Introduces a new temporary into the caller body that is live for the duration of the call.
731     fn new_call_temp(
732         &self,
733         caller_body: &mut Body<'tcx>,
734         callsite: &CallSite<'tcx>,
735         ty: Ty<'tcx>,
736     ) -> Local {
737         let local = caller_body.local_decls.push(LocalDecl::new(ty, callsite.source_info.span));
738
739         caller_body[callsite.block].statements.push(Statement {
740             source_info: callsite.source_info,
741             kind: StatementKind::StorageLive(local),
742         });
743
744         if let Some(block) = callsite.target {
745             caller_body[block].statements.insert(
746                 0,
747                 Statement {
748                     source_info: callsite.source_info,
749                     kind: StatementKind::StorageDead(local),
750                 },
751             );
752         }
753
754         local
755     }
756 }
757
758 fn type_size_of<'tcx>(
759     tcx: TyCtxt<'tcx>,
760     param_env: ty::ParamEnv<'tcx>,
761     ty: Ty<'tcx>,
762 ) -> Option<u64> {
763     tcx.layout_of(param_env.and(ty)).ok().map(|layout| layout.size.bytes())
764 }
765
766 /**
767  * Integrator.
768  *
769  * Integrates blocks from the callee function into the calling function.
770  * Updates block indices, references to locals and other control flow
771  * stuff.
772 */
773 struct Integrator<'a, 'tcx> {
774     args: &'a [Local],
775     new_locals: RangeFrom<Local>,
776     new_scopes: RangeFrom<SourceScope>,
777     new_blocks: RangeFrom<BasicBlock>,
778     destination: Place<'tcx>,
779     return_block: Option<BasicBlock>,
780     cleanup_block: Option<BasicBlock>,
781     in_cleanup_block: bool,
782     tcx: TyCtxt<'tcx>,
783     callsite_span: Span,
784     body_span: Span,
785     always_live_locals: BitSet<Local>,
786 }
787
788 impl Integrator<'_, '_> {
789     fn map_local(&self, local: Local) -> Local {
790         let new = if local == RETURN_PLACE {
791             self.destination.local
792         } else {
793             let idx = local.index() - 1;
794             if idx < self.args.len() {
795                 self.args[idx]
796             } else {
797                 Local::new(self.new_locals.start.index() + (idx - self.args.len()))
798             }
799         };
800         trace!("mapping local `{:?}` to `{:?}`", local, new);
801         new
802     }
803
804     fn map_scope(&self, scope: SourceScope) -> SourceScope {
805         let new = SourceScope::new(self.new_scopes.start.index() + scope.index());
806         trace!("mapping scope `{:?}` to `{:?}`", scope, new);
807         new
808     }
809
810     fn map_block(&self, block: BasicBlock) -> BasicBlock {
811         let new = BasicBlock::new(self.new_blocks.start.index() + block.index());
812         trace!("mapping block `{:?}` to `{:?}`", block, new);
813         new
814     }
815 }
816
817 impl<'tcx> MutVisitor<'tcx> for Integrator<'_, 'tcx> {
818     fn tcx(&self) -> TyCtxt<'tcx> {
819         self.tcx
820     }
821
822     fn visit_local(&mut self, local: &mut Local, _ctxt: PlaceContext, _location: Location) {
823         *local = self.map_local(*local);
824     }
825
826     fn visit_source_scope(&mut self, scope: &mut SourceScope) {
827         *scope = self.map_scope(*scope);
828     }
829
830     fn visit_span(&mut self, span: &mut Span) {
831         let mut expn_data =
832             ExpnData::default(ExpnKind::Inlined, *span, self.tcx.sess.edition(), None, None);
833         expn_data.def_site = self.body_span;
834         // Make sure that all spans track the fact that they were inlined.
835         *span =
836             self.callsite_span.fresh_expansion(expn_data, self.tcx.create_stable_hashing_context());
837     }
838
839     fn visit_place(&mut self, place: &mut Place<'tcx>, context: PlaceContext, location: Location) {
840         for elem in place.projection {
841             // FIXME: Make sure that return place is not used in an indexing projection, since it
842             // won't be rebased as it is supposed to be.
843             assert_ne!(ProjectionElem::Index(RETURN_PLACE), elem);
844         }
845
846         // If this is the `RETURN_PLACE`, we need to rebase any projections onto it.
847         let dest_proj_len = self.destination.projection.len();
848         if place.local == RETURN_PLACE && dest_proj_len > 0 {
849             let mut projs = Vec::with_capacity(dest_proj_len + place.projection.len());
850             projs.extend(self.destination.projection);
851             projs.extend(place.projection);
852
853             place.projection = self.tcx.intern_place_elems(&*projs);
854         }
855         // Handles integrating any locals that occur in the base
856         // or projections
857         self.super_place(place, context, location)
858     }
859
860     fn visit_basic_block_data(&mut self, block: BasicBlock, data: &mut BasicBlockData<'tcx>) {
861         self.in_cleanup_block = data.is_cleanup;
862         self.super_basic_block_data(block, data);
863         self.in_cleanup_block = false;
864     }
865
866     fn visit_retag(&mut self, kind: &mut RetagKind, place: &mut Place<'tcx>, loc: Location) {
867         self.super_retag(kind, place, loc);
868
869         // We have to patch all inlined retags to be aware that they are no longer
870         // happening on function entry.
871         if *kind == RetagKind::FnEntry {
872             *kind = RetagKind::Default;
873         }
874     }
875
876     fn visit_statement(&mut self, statement: &mut Statement<'tcx>, location: Location) {
877         if let StatementKind::StorageLive(local) | StatementKind::StorageDead(local) =
878             statement.kind
879         {
880             self.always_live_locals.remove(local);
881         }
882         self.super_statement(statement, location);
883     }
884
885     fn visit_terminator(&mut self, terminator: &mut Terminator<'tcx>, loc: Location) {
886         // Don't try to modify the implicit `_0` access on return (`return` terminators are
887         // replaced down below anyways).
888         if !matches!(terminator.kind, TerminatorKind::Return) {
889             self.super_terminator(terminator, loc);
890         }
891
892         match terminator.kind {
893             TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => bug!(),
894             TerminatorKind::Goto { ref mut target } => {
895                 *target = self.map_block(*target);
896             }
897             TerminatorKind::SwitchInt { ref mut targets, .. } => {
898                 for tgt in targets.all_targets_mut() {
899                     *tgt = self.map_block(*tgt);
900                 }
901             }
902             TerminatorKind::Drop { ref mut target, ref mut unwind, .. }
903             | TerminatorKind::DropAndReplace { ref mut target, ref mut unwind, .. } => {
904                 *target = self.map_block(*target);
905                 if let Some(tgt) = *unwind {
906                     *unwind = Some(self.map_block(tgt));
907                 } else if !self.in_cleanup_block {
908                     // Unless this drop is in a cleanup block, add an unwind edge to
909                     // the original call's cleanup block
910                     *unwind = self.cleanup_block;
911                 }
912             }
913             TerminatorKind::Call { ref mut destination, ref mut cleanup, .. } => {
914                 if let Some((_, ref mut tgt)) = *destination {
915                     *tgt = self.map_block(*tgt);
916                 }
917                 if let Some(tgt) = *cleanup {
918                     *cleanup = Some(self.map_block(tgt));
919                 } else if !self.in_cleanup_block {
920                     // Unless this call is in a cleanup block, add an unwind edge to
921                     // the original call's cleanup block
922                     *cleanup = self.cleanup_block;
923                 }
924             }
925             TerminatorKind::Assert { ref mut target, ref mut cleanup, .. } => {
926                 *target = self.map_block(*target);
927                 if let Some(tgt) = *cleanup {
928                     *cleanup = Some(self.map_block(tgt));
929                 } else if !self.in_cleanup_block {
930                     // Unless this assert is in a cleanup block, add an unwind edge to
931                     // the original call's cleanup block
932                     *cleanup = self.cleanup_block;
933                 }
934             }
935             TerminatorKind::Return => {
936                 terminator.kind = if let Some(tgt) = self.return_block {
937                     TerminatorKind::Goto { target: tgt }
938                 } else {
939                     TerminatorKind::Unreachable
940                 }
941             }
942             TerminatorKind::Resume => {
943                 if let Some(tgt) = self.cleanup_block {
944                     terminator.kind = TerminatorKind::Goto { target: tgt }
945                 }
946             }
947             TerminatorKind::Abort => {}
948             TerminatorKind::Unreachable => {}
949             TerminatorKind::FalseEdge { ref mut real_target, ref mut imaginary_target } => {
950                 *real_target = self.map_block(*real_target);
951                 *imaginary_target = self.map_block(*imaginary_target);
952             }
953             TerminatorKind::FalseUnwind { real_target: _, unwind: _ } =>
954             // see the ordering of passes in the optimized_mir query.
955             {
956                 bug!("False unwinds should have been removed before inlining")
957             }
958             TerminatorKind::InlineAsm { ref mut destination, ref mut cleanup, .. } => {
959                 if let Some(ref mut tgt) = *destination {
960                     *tgt = self.map_block(*tgt);
961                 } else if !self.in_cleanup_block {
962                     // Unless this inline asm is in a cleanup block, add an unwind edge to
963                     // the original call's cleanup block
964                     *cleanup = self.cleanup_block;
965                 }
966             }
967         }
968     }
969 }