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