]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/mod.rs
Rollup merge of #101253 - lyming2007:issue-101163, r=Amanieu
[rust.git] / compiler / rustc_mir_build / src / build / mod.rs
1 use crate::build;
2 pub(crate) use crate::build::expr::as_constant::lit_to_mir_constant;
3 use crate::build::expr::as_place::PlaceBuilder;
4 use crate::build::scope::DropKind;
5 use crate::thir::pattern::pat_from_hir;
6 use rustc_apfloat::ieee::{Double, Single};
7 use rustc_apfloat::Float;
8 use rustc_data_structures::fx::FxHashMap;
9 use rustc_errors::ErrorGuaranteed;
10 use rustc_hir as hir;
11 use rustc_hir::def_id::{DefId, LocalDefId};
12 use rustc_hir::lang_items::LangItem;
13 use rustc_hir::{GeneratorKind, Node};
14 use rustc_index::vec::{Idx, IndexVec};
15 use rustc_infer::infer::{InferCtxt, TyCtxtInferExt};
16 use rustc_middle::hir::place::PlaceBase as HirPlaceBase;
17 use rustc_middle::middle::region;
18 use rustc_middle::mir::interpret::ConstValue;
19 use rustc_middle::mir::interpret::Scalar;
20 use rustc_middle::mir::*;
21 use rustc_middle::thir::{BindingMode, Expr, ExprId, LintLevel, LocalVarId, PatKind, Thir};
22 use rustc_middle::ty::subst::Subst;
23 use rustc_middle::ty::{self, Ty, TyCtxt, TypeVisitable, TypeckResults};
24 use rustc_span::symbol::sym;
25 use rustc_span::Span;
26 use rustc_span::Symbol;
27 use rustc_target::spec::abi::Abi;
28
29 use super::lints;
30
31 pub(crate) fn mir_built<'tcx>(
32     tcx: TyCtxt<'tcx>,
33     def: ty::WithOptConstParam<LocalDefId>,
34 ) -> &'tcx rustc_data_structures::steal::Steal<Body<'tcx>> {
35     if let Some(def) = def.try_upgrade(tcx) {
36         return tcx.mir_built(def);
37     }
38
39     let mut body = mir_build(tcx, def);
40     if def.const_param_did.is_some() {
41         assert!(matches!(body.source.instance, ty::InstanceDef::Item(_)));
42         body.source = MirSource::from_instance(ty::InstanceDef::Item(def.to_global()));
43     }
44
45     tcx.alloc_steal_mir(body)
46 }
47
48 /// Construct the MIR for a given `DefId`.
49 fn mir_build(tcx: TyCtxt<'_>, def: ty::WithOptConstParam<LocalDefId>) -> Body<'_> {
50     let id = tcx.hir().local_def_id_to_hir_id(def.did);
51     let body_owner_kind = tcx.hir().body_owner_kind(def.did);
52     let typeck_results = tcx.typeck_opt_const_arg(def);
53
54     // Ensure unsafeck and abstract const building is ran before we steal the THIR.
55     // We can't use `ensure()` for `thir_abstract_const` as it doesn't compute the query
56     // if inputs are green. This can cause ICEs when calling `thir_abstract_const` after
57     // THIR has been stolen if we haven't computed this query yet.
58     match def {
59         ty::WithOptConstParam { did, const_param_did: Some(const_param_did) } => {
60             tcx.ensure().thir_check_unsafety_for_const_arg((did, const_param_did));
61             drop(tcx.thir_abstract_const_of_const_arg((did, const_param_did)));
62         }
63         ty::WithOptConstParam { did, const_param_did: None } => {
64             tcx.ensure().thir_check_unsafety(did);
65             drop(tcx.thir_abstract_const(did));
66         }
67     }
68
69     // Figure out what primary body this item has.
70     let (body_id, return_ty_span, span_with_body) = match tcx.hir().get(id) {
71         Node::Expr(hir::Expr {
72             kind: hir::ExprKind::Closure(hir::Closure { fn_decl, body, .. }),
73             ..
74         }) => (*body, fn_decl.output.span(), None),
75         Node::Item(hir::Item {
76             kind: hir::ItemKind::Fn(hir::FnSig { decl, .. }, _, body_id),
77             span,
78             ..
79         })
80         | Node::ImplItem(hir::ImplItem {
81             kind: hir::ImplItemKind::Fn(hir::FnSig { decl, .. }, body_id),
82             span,
83             ..
84         })
85         | Node::TraitItem(hir::TraitItem {
86             kind: hir::TraitItemKind::Fn(hir::FnSig { decl, .. }, hir::TraitFn::Provided(body_id)),
87             span,
88             ..
89         }) => {
90             // Use the `Span` of the `Item/ImplItem/TraitItem` as the body span,
91             // since the def span of a function does not include the body
92             (*body_id, decl.output.span(), Some(*span))
93         }
94         Node::Item(hir::Item {
95             kind: hir::ItemKind::Static(ty, _, body_id) | hir::ItemKind::Const(ty, body_id),
96             ..
97         })
98         | Node::ImplItem(hir::ImplItem { kind: hir::ImplItemKind::Const(ty, body_id), .. })
99         | Node::TraitItem(hir::TraitItem {
100             kind: hir::TraitItemKind::Const(ty, Some(body_id)),
101             ..
102         }) => (*body_id, ty.span, None),
103         Node::AnonConst(hir::AnonConst { body, hir_id, .. }) => {
104             (*body, tcx.hir().span(*hir_id), None)
105         }
106
107         _ => span_bug!(tcx.hir().span(id), "can't build MIR for {:?}", def.did),
108     };
109
110     // If we don't have a specialized span for the body, just use the
111     // normal def span.
112     let span_with_body = span_with_body.unwrap_or_else(|| tcx.hir().span(id));
113
114     tcx.infer_ctxt().enter(|infcx| {
115         let body = if let Some(error_reported) = typeck_results.tainted_by_errors {
116             build::construct_error(&infcx, def, id, body_id, body_owner_kind, error_reported)
117         } else if body_owner_kind.is_fn_or_closure() {
118             // fetch the fully liberated fn signature (that is, all bound
119             // types/lifetimes replaced)
120             let fn_sig = typeck_results.liberated_fn_sigs()[id];
121             let fn_def_id = tcx.hir().local_def_id(id);
122
123             let safety = match fn_sig.unsafety {
124                 hir::Unsafety::Normal => Safety::Safe,
125                 hir::Unsafety::Unsafe => Safety::FnUnsafe,
126             };
127
128             let body = tcx.hir().body(body_id);
129             let (thir, expr) = tcx
130                 .thir_body(def)
131                 .unwrap_or_else(|_| (tcx.alloc_steal_thir(Thir::new()), ExprId::from_u32(0)));
132             // We ran all queries that depended on THIR at the beginning
133             // of `mir_build`, so now we can steal it
134             let thir = thir.steal();
135             let ty = tcx.type_of(fn_def_id);
136             let mut abi = fn_sig.abi;
137             let implicit_argument = match ty.kind() {
138                 ty::Closure(..) => {
139                     // HACK(eddyb) Avoid having RustCall on closures,
140                     // as it adds unnecessary (and wrong) auto-tupling.
141                     abi = Abi::Rust;
142                     vec![ArgInfo(liberated_closure_env_ty(tcx, id, body_id), None, None, None)]
143                 }
144                 ty::Generator(..) => {
145                     let gen_ty = tcx.typeck_body(body_id).node_type(id);
146
147                     // The resume argument may be missing, in that case we need to provide it here.
148                     // It will always be `()` in this case.
149                     if body.params.is_empty() {
150                         vec![
151                             ArgInfo(gen_ty, None, None, None),
152                             ArgInfo(tcx.mk_unit(), None, None, None),
153                         ]
154                     } else {
155                         vec![ArgInfo(gen_ty, None, None, None)]
156                     }
157                 }
158                 _ => vec![],
159             };
160
161             let explicit_arguments = body.params.iter().enumerate().map(|(index, arg)| {
162                 let owner_id = tcx.hir().body_owner(body_id);
163                 let opt_ty_info;
164                 let self_arg;
165                 if let Some(ref fn_decl) = tcx.hir().fn_decl_by_hir_id(owner_id) {
166                     opt_ty_info = fn_decl
167                         .inputs
168                         .get(index)
169                         // Make sure that inferred closure args have no type span
170                         .and_then(|ty| if arg.pat.span != ty.span { Some(ty.span) } else { None });
171                     self_arg = if index == 0 && fn_decl.implicit_self.has_implicit_self() {
172                         match fn_decl.implicit_self {
173                             hir::ImplicitSelfKind::Imm => Some(ImplicitSelfKind::Imm),
174                             hir::ImplicitSelfKind::Mut => Some(ImplicitSelfKind::Mut),
175                             hir::ImplicitSelfKind::ImmRef => Some(ImplicitSelfKind::ImmRef),
176                             hir::ImplicitSelfKind::MutRef => Some(ImplicitSelfKind::MutRef),
177                             _ => None,
178                         }
179                     } else {
180                         None
181                     };
182                 } else {
183                     opt_ty_info = None;
184                     self_arg = None;
185                 }
186
187                 // C-variadic fns also have a `VaList` input that's not listed in `fn_sig`
188                 // (as it's created inside the body itself, not passed in from outside).
189                 let ty = if fn_sig.c_variadic && index == fn_sig.inputs().len() {
190                     let va_list_did = tcx.require_lang_item(LangItem::VaList, Some(arg.span));
191
192                     tcx.bound_type_of(va_list_did).subst(tcx, &[tcx.lifetimes.re_erased.into()])
193                 } else {
194                     fn_sig.inputs()[index]
195                 };
196
197                 ArgInfo(ty, opt_ty_info, Some(&arg), self_arg)
198             });
199
200             let arguments = implicit_argument.into_iter().chain(explicit_arguments);
201
202             let (yield_ty, return_ty) = if body.generator_kind.is_some() {
203                 let gen_ty = tcx.typeck_body(body_id).node_type(id);
204                 let gen_sig = match gen_ty.kind() {
205                     ty::Generator(_, gen_substs, ..) => gen_substs.as_generator().sig(),
206                     _ => span_bug!(tcx.hir().span(id), "generator w/o generator type: {:?}", ty),
207                 };
208                 (Some(gen_sig.yield_ty), gen_sig.return_ty)
209             } else {
210                 (None, fn_sig.output())
211             };
212
213             let mut mir = build::construct_fn(
214                 &thir,
215                 &infcx,
216                 def,
217                 id,
218                 arguments,
219                 safety,
220                 abi,
221                 return_ty,
222                 return_ty_span,
223                 body,
224                 expr,
225                 span_with_body,
226             );
227             if yield_ty.is_some() {
228                 mir.generator.as_mut().unwrap().yield_ty = yield_ty;
229             }
230             mir
231         } else {
232             // Get the revealed type of this const. This is *not* the adjusted
233             // type of its body, which may be a subtype of this type. For
234             // example:
235             //
236             // fn foo(_: &()) {}
237             // static X: fn(&'static ()) = foo;
238             //
239             // The adjusted type of the body of X is `for<'a> fn(&'a ())` which
240             // is not the same as the type of X. We need the type of the return
241             // place to be the type of the constant because NLL typeck will
242             // equate them.
243
244             let return_ty = typeck_results.node_type(id);
245
246             let (thir, expr) = tcx
247                 .thir_body(def)
248                 .unwrap_or_else(|_| (tcx.alloc_steal_thir(Thir::new()), ExprId::from_u32(0)));
249             // We ran all queries that depended on THIR at the beginning
250             // of `mir_build`, so now we can steal it
251             let thir = thir.steal();
252
253             let span_with_body = span_with_body.to(tcx.hir().span(body_id.hir_id));
254
255             build::construct_const(
256                 &thir,
257                 &infcx,
258                 expr,
259                 def,
260                 id,
261                 return_ty,
262                 return_ty_span,
263                 span_with_body,
264             )
265         };
266
267         lints::check(tcx, &body);
268
269         // The borrow checker will replace all the regions here with its own
270         // inference variables. There's no point having non-erased regions here.
271         // The exception is `body.user_type_annotations`, which is used unmodified
272         // by borrow checking.
273         debug_assert!(
274             !(body.local_decls.has_free_regions()
275                 || body.basic_blocks.has_free_regions()
276                 || body.var_debug_info.has_free_regions()
277                 || body.yield_ty().has_free_regions()),
278             "Unexpected free regions in MIR: {:?}",
279             body,
280         );
281
282         body
283     })
284 }
285
286 ///////////////////////////////////////////////////////////////////////////
287 // BuildMir -- walks a crate, looking for fn items and methods to build MIR from
288
289 fn liberated_closure_env_ty(
290     tcx: TyCtxt<'_>,
291     closure_expr_id: hir::HirId,
292     body_id: hir::BodyId,
293 ) -> Ty<'_> {
294     let closure_ty = tcx.typeck_body(body_id).node_type(closure_expr_id);
295
296     let ty::Closure(closure_def_id, closure_substs) = *closure_ty.kind() else {
297         bug!("closure expr does not have closure type: {:?}", closure_ty);
298     };
299
300     let bound_vars =
301         tcx.mk_bound_variable_kinds(std::iter::once(ty::BoundVariableKind::Region(ty::BrEnv)));
302     let br =
303         ty::BoundRegion { var: ty::BoundVar::from_usize(bound_vars.len() - 1), kind: ty::BrEnv };
304     let env_region = ty::ReLateBound(ty::INNERMOST, br);
305     let closure_env_ty = tcx.closure_env_ty(closure_def_id, closure_substs, env_region).unwrap();
306     tcx.erase_late_bound_regions(ty::Binder::bind_with_vars(closure_env_ty, bound_vars))
307 }
308
309 #[derive(Debug, PartialEq, Eq)]
310 enum BlockFrame {
311     /// Evaluation is currently within a statement.
312     ///
313     /// Examples include:
314     /// 1. `EXPR;`
315     /// 2. `let _ = EXPR;`
316     /// 3. `let x = EXPR;`
317     Statement {
318         /// If true, then statement discards result from evaluating
319         /// the expression (such as examples 1 and 2 above).
320         ignores_expr_result: bool,
321     },
322
323     /// Evaluation is currently within the tail expression of a block.
324     ///
325     /// Example: `{ STMT_1; STMT_2; EXPR }`
326     TailExpr {
327         /// If true, then the surrounding context of the block ignores
328         /// the result of evaluating the block's tail expression.
329         ///
330         /// Example: `let _ = { STMT_1; EXPR };`
331         tail_result_is_ignored: bool,
332
333         /// `Span` of the tail expression.
334         span: Span,
335     },
336
337     /// Generic mark meaning that the block occurred as a subexpression
338     /// where the result might be used.
339     ///
340     /// Examples: `foo(EXPR)`, `match EXPR { ... }`
341     SubExpr,
342 }
343
344 impl BlockFrame {
345     fn is_tail_expr(&self) -> bool {
346         match *self {
347             BlockFrame::TailExpr { .. } => true,
348
349             BlockFrame::Statement { .. } | BlockFrame::SubExpr => false,
350         }
351     }
352     fn is_statement(&self) -> bool {
353         match *self {
354             BlockFrame::Statement { .. } => true,
355
356             BlockFrame::TailExpr { .. } | BlockFrame::SubExpr => false,
357         }
358     }
359 }
360
361 #[derive(Debug)]
362 struct BlockContext(Vec<BlockFrame>);
363
364 struct Builder<'a, 'tcx> {
365     tcx: TyCtxt<'tcx>,
366     infcx: &'a InferCtxt<'a, 'tcx>,
367     typeck_results: &'tcx TypeckResults<'tcx>,
368     region_scope_tree: &'tcx region::ScopeTree,
369     param_env: ty::ParamEnv<'tcx>,
370
371     thir: &'a Thir<'tcx>,
372     cfg: CFG<'tcx>,
373
374     def_id: DefId,
375     hir_id: hir::HirId,
376     parent_module: DefId,
377     check_overflow: bool,
378     fn_span: Span,
379     arg_count: usize,
380     generator_kind: Option<GeneratorKind>,
381
382     /// The current set of scopes, updated as we traverse;
383     /// see the `scope` module for more details.
384     scopes: scope::Scopes<'tcx>,
385
386     /// The block-context: each time we build the code within an thir::Block,
387     /// we push a frame here tracking whether we are building a statement or
388     /// if we are pushing the tail expression of the block. This is used to
389     /// embed information in generated temps about whether they were created
390     /// for a block tail expression or not.
391     ///
392     /// It would be great if we could fold this into `self.scopes`
393     /// somehow, but right now I think that is very tightly tied to
394     /// the code generation in ways that we cannot (or should not)
395     /// start just throwing new entries onto that vector in order to
396     /// distinguish the context of EXPR1 from the context of EXPR2 in
397     /// `{ STMTS; EXPR1 } + EXPR2`.
398     block_context: BlockContext,
399
400     /// The current unsafe block in scope
401     in_scope_unsafe: Safety,
402
403     /// The vector of all scopes that we have created thus far;
404     /// we track this for debuginfo later.
405     source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
406     source_scope: SourceScope,
407
408     /// The guard-context: each time we build the guard expression for
409     /// a match arm, we push onto this stack, and then pop when we
410     /// finish building it.
411     guard_context: Vec<GuardFrame>,
412
413     /// Maps `HirId`s of variable bindings to the `Local`s created for them.
414     /// (A match binding can have two locals; the 2nd is for the arm's guard.)
415     var_indices: FxHashMap<LocalVarId, LocalsForNode>,
416     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
417     canonical_user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
418     upvar_mutbls: Vec<Mutability>,
419     unit_temp: Option<Place<'tcx>>,
420
421     var_debug_info: Vec<VarDebugInfo<'tcx>>,
422 }
423
424 impl<'a, 'tcx> Builder<'a, 'tcx> {
425     fn is_bound_var_in_guard(&self, id: LocalVarId) -> bool {
426         self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
427     }
428
429     fn var_local_id(&self, id: LocalVarId, for_guard: ForGuard) -> Local {
430         self.var_indices[&id].local_id(for_guard)
431     }
432 }
433
434 impl BlockContext {
435     fn new() -> Self {
436         BlockContext(vec![])
437     }
438     fn push(&mut self, bf: BlockFrame) {
439         self.0.push(bf);
440     }
441     fn pop(&mut self) -> Option<BlockFrame> {
442         self.0.pop()
443     }
444
445     /// Traverses the frames on the `BlockContext`, searching for either
446     /// the first block-tail expression frame with no intervening
447     /// statement frame.
448     ///
449     /// Notably, this skips over `SubExpr` frames; this method is
450     /// meant to be used in the context of understanding the
451     /// relationship of a temp (created within some complicated
452     /// expression) with its containing expression, and whether the
453     /// value of that *containing expression* (not the temp!) is
454     /// ignored.
455     fn currently_in_block_tail(&self) -> Option<BlockTailInfo> {
456         for bf in self.0.iter().rev() {
457             match bf {
458                 BlockFrame::SubExpr => continue,
459                 BlockFrame::Statement { .. } => break,
460                 &BlockFrame::TailExpr { tail_result_is_ignored, span } => {
461                     return Some(BlockTailInfo { tail_result_is_ignored, span });
462                 }
463             }
464         }
465
466         None
467     }
468
469     /// Looks at the topmost frame on the BlockContext and reports
470     /// whether its one that would discard a block tail result.
471     ///
472     /// Unlike `currently_within_ignored_tail_expression`, this does
473     /// *not* skip over `SubExpr` frames: here, we want to know
474     /// whether the block result itself is discarded.
475     fn currently_ignores_tail_results(&self) -> bool {
476         match self.0.last() {
477             // no context: conservatively assume result is read
478             None => false,
479
480             // sub-expression: block result feeds into some computation
481             Some(BlockFrame::SubExpr) => false,
482
483             // otherwise: use accumulated is_ignored state.
484             Some(
485                 BlockFrame::TailExpr { tail_result_is_ignored: ignored, .. }
486                 | BlockFrame::Statement { ignores_expr_result: ignored },
487             ) => *ignored,
488         }
489     }
490 }
491
492 #[derive(Debug)]
493 enum LocalsForNode {
494     /// In the usual case, a `HirId` for an identifier maps to at most
495     /// one `Local` declaration.
496     One(Local),
497
498     /// The exceptional case is identifiers in a match arm's pattern
499     /// that are referenced in a guard of that match arm. For these,
500     /// we have `2` Locals.
501     ///
502     /// * `for_arm_body` is the Local used in the arm body (which is
503     ///   just like the `One` case above),
504     ///
505     /// * `ref_for_guard` is the Local used in the arm's guard (which
506     ///   is a reference to a temp that is an alias of
507     ///   `for_arm_body`).
508     ForGuard { ref_for_guard: Local, for_arm_body: Local },
509 }
510
511 #[derive(Debug)]
512 struct GuardFrameLocal {
513     id: LocalVarId,
514 }
515
516 impl GuardFrameLocal {
517     fn new(id: LocalVarId, _binding_mode: BindingMode) -> Self {
518         GuardFrameLocal { id }
519     }
520 }
521
522 #[derive(Debug)]
523 struct GuardFrame {
524     /// These are the id's of names that are bound by patterns of the
525     /// arm of *this* guard.
526     ///
527     /// (Frames higher up the stack will have the id's bound in arms
528     /// further out, such as in a case like:
529     ///
530     /// match E1 {
531     ///      P1(id1) if (... (match E2 { P2(id2) if ... => B2 })) => B1,
532     /// }
533     ///
534     /// here, when building for FIXME.
535     locals: Vec<GuardFrameLocal>,
536 }
537
538 /// `ForGuard` indicates whether we are talking about:
539 ///   1. The variable for use outside of guard expressions, or
540 ///   2. The temp that holds reference to (1.), which is actually what the
541 ///      guard expressions see.
542 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
543 enum ForGuard {
544     RefWithinGuard,
545     OutsideGuard,
546 }
547
548 impl LocalsForNode {
549     fn local_id(&self, for_guard: ForGuard) -> Local {
550         match (self, for_guard) {
551             (&LocalsForNode::One(local_id), ForGuard::OutsideGuard)
552             | (
553                 &LocalsForNode::ForGuard { ref_for_guard: local_id, .. },
554                 ForGuard::RefWithinGuard,
555             )
556             | (&LocalsForNode::ForGuard { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) => {
557                 local_id
558             }
559
560             (&LocalsForNode::One(_), ForGuard::RefWithinGuard) => {
561                 bug!("anything with one local should never be within a guard.")
562             }
563         }
564     }
565 }
566
567 struct CFG<'tcx> {
568     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
569 }
570
571 rustc_index::newtype_index! {
572     struct ScopeId { .. }
573 }
574
575 #[derive(Debug)]
576 enum NeedsTemporary {
577     /// Use this variant when whatever you are converting with `as_operand`
578     /// is the last thing you are converting. This means that if we introduced
579     /// an intermediate temporary, we'd only read it immediately after, so we can
580     /// also avoid it.
581     No,
582     /// For all cases where you aren't sure or that are too expensive to compute
583     /// for now. It is always safe to fall back to this.
584     Maybe,
585 }
586
587 ///////////////////////////////////////////////////////////////////////////
588 /// The `BlockAnd` "monad" packages up the new basic block along with a
589 /// produced value (sometimes just unit, of course). The `unpack!`
590 /// macro (and methods below) makes working with `BlockAnd` much more
591 /// convenient.
592
593 #[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
594 struct BlockAnd<T>(BasicBlock, T);
595
596 trait BlockAndExtension {
597     fn and<T>(self, v: T) -> BlockAnd<T>;
598     fn unit(self) -> BlockAnd<()>;
599 }
600
601 impl BlockAndExtension for BasicBlock {
602     fn and<T>(self, v: T) -> BlockAnd<T> {
603         BlockAnd(self, v)
604     }
605
606     fn unit(self) -> BlockAnd<()> {
607         BlockAnd(self, ())
608     }
609 }
610
611 /// Update a block pointer and return the value.
612 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
613 macro_rules! unpack {
614     ($x:ident = $c:expr) => {{
615         let BlockAnd(b, v) = $c;
616         $x = b;
617         v
618     }};
619
620     ($c:expr) => {{
621         let BlockAnd(b, ()) = $c;
622         b
623     }};
624 }
625
626 ///////////////////////////////////////////////////////////////////////////
627 /// the main entry point for building MIR for a function
628
629 struct ArgInfo<'tcx>(
630     Ty<'tcx>,
631     Option<Span>,
632     Option<&'tcx hir::Param<'tcx>>,
633     Option<ImplicitSelfKind>,
634 );
635
636 fn construct_fn<'tcx, A>(
637     thir: &Thir<'tcx>,
638     infcx: &InferCtxt<'_, 'tcx>,
639     fn_def: ty::WithOptConstParam<LocalDefId>,
640     fn_id: hir::HirId,
641     arguments: A,
642     safety: Safety,
643     abi: Abi,
644     return_ty: Ty<'tcx>,
645     return_ty_span: Span,
646     body: &'tcx hir::Body<'tcx>,
647     expr: ExprId,
648     span_with_body: Span,
649 ) -> Body<'tcx>
650 where
651     A: Iterator<Item = ArgInfo<'tcx>>,
652 {
653     let arguments: Vec<_> = arguments.collect();
654
655     let tcx = infcx.tcx;
656     let span = tcx.hir().span(fn_id);
657
658     let mut builder = Builder::new(
659         thir,
660         infcx,
661         fn_def,
662         fn_id,
663         span_with_body,
664         arguments.len(),
665         safety,
666         return_ty,
667         return_ty_span,
668         body.generator_kind,
669     );
670
671     let call_site_scope =
672         region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::CallSite };
673     let arg_scope =
674         region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::Arguments };
675     let source_info = builder.source_info(span);
676     let call_site_s = (call_site_scope, source_info);
677     unpack!(builder.in_scope(call_site_s, LintLevel::Inherited, |builder| {
678         let arg_scope_s = (arg_scope, source_info);
679         // Attribute epilogue to function's closing brace
680         let fn_end = span_with_body.shrink_to_hi();
681         let return_block =
682             unpack!(builder.in_breakable_scope(None, Place::return_place(), fn_end, |builder| {
683                 Some(builder.in_scope(arg_scope_s, LintLevel::Inherited, |builder| {
684                     builder.args_and_body(
685                         START_BLOCK,
686                         fn_def.did,
687                         &arguments,
688                         arg_scope,
689                         &thir[expr],
690                     )
691                 }))
692             }));
693         let source_info = builder.source_info(fn_end);
694         builder.cfg.terminate(return_block, source_info, TerminatorKind::Return);
695         builder.build_drop_trees();
696         return_block.unit()
697     }));
698
699     let spread_arg = if abi == Abi::RustCall {
700         // RustCall pseudo-ABI untuples the last argument.
701         Some(Local::new(arguments.len()))
702     } else {
703         None
704     };
705
706     let mut body = builder.finish();
707     body.spread_arg = spread_arg;
708     body
709 }
710
711 fn construct_const<'a, 'tcx>(
712     thir: &'a Thir<'tcx>,
713     infcx: &'a InferCtxt<'a, 'tcx>,
714     expr: ExprId,
715     def: ty::WithOptConstParam<LocalDefId>,
716     hir_id: hir::HirId,
717     const_ty: Ty<'tcx>,
718     const_ty_span: Span,
719     span: Span,
720 ) -> Body<'tcx> {
721     let mut builder = Builder::new(
722         thir,
723         infcx,
724         def,
725         hir_id,
726         span,
727         0,
728         Safety::Safe,
729         const_ty,
730         const_ty_span,
731         None,
732     );
733
734     let mut block = START_BLOCK;
735     unpack!(block = builder.expr_into_dest(Place::return_place(), block, &thir[expr]));
736
737     let source_info = builder.source_info(span);
738     builder.cfg.terminate(block, source_info, TerminatorKind::Return);
739
740     builder.build_drop_trees();
741
742     builder.finish()
743 }
744
745 /// Construct MIR for an item that has had errors in type checking.
746 ///
747 /// This is required because we may still want to run MIR passes on an item
748 /// with type errors, but normal MIR construction can't handle that in general.
749 fn construct_error<'a, 'tcx>(
750     infcx: &'a InferCtxt<'a, 'tcx>,
751     def: ty::WithOptConstParam<LocalDefId>,
752     hir_id: hir::HirId,
753     body_id: hir::BodyId,
754     body_owner_kind: hir::BodyOwnerKind,
755     err: ErrorGuaranteed,
756 ) -> Body<'tcx> {
757     let tcx = infcx.tcx;
758     let span = tcx.hir().span(hir_id);
759     let ty = tcx.ty_error();
760     let generator_kind = tcx.hir().body(body_id).generator_kind;
761     let num_params = match body_owner_kind {
762         hir::BodyOwnerKind::Fn => tcx.hir().fn_decl_by_hir_id(hir_id).unwrap().inputs.len(),
763         hir::BodyOwnerKind::Closure => {
764             if generator_kind.is_some() {
765                 // Generators have an implicit `self` parameter *and* a possibly
766                 // implicit resume parameter.
767                 2
768             } else {
769                 // The implicit self parameter adds another local in MIR.
770                 1 + tcx.hir().fn_decl_by_hir_id(hir_id).unwrap().inputs.len()
771             }
772         }
773         hir::BodyOwnerKind::Const => 0,
774         hir::BodyOwnerKind::Static(_) => 0,
775     };
776     let mut cfg = CFG { basic_blocks: IndexVec::new() };
777     let mut source_scopes = IndexVec::new();
778     let mut local_decls = IndexVec::from_elem_n(LocalDecl::new(ty, span), 1);
779
780     cfg.start_new_block();
781     source_scopes.push(SourceScopeData {
782         span,
783         parent_scope: None,
784         inlined: None,
785         inlined_parent_scope: None,
786         local_data: ClearCrossCrate::Set(SourceScopeLocalData {
787             lint_root: hir_id,
788             safety: Safety::Safe,
789         }),
790     });
791     let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
792
793     // Some MIR passes will expect the number of parameters to match the
794     // function declaration.
795     for _ in 0..num_params {
796         local_decls.push(LocalDecl::with_source_info(ty, source_info));
797     }
798     cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
799
800     let mut body = Body::new(
801         MirSource::item(def.did.to_def_id()),
802         cfg.basic_blocks,
803         source_scopes,
804         local_decls,
805         IndexVec::new(),
806         num_params,
807         vec![],
808         span,
809         generator_kind,
810         Some(err),
811     );
812     body.generator.as_mut().map(|gen| gen.yield_ty = Some(ty));
813     body
814 }
815
816 impl<'a, 'tcx> Builder<'a, 'tcx> {
817     fn new(
818         thir: &'a Thir<'tcx>,
819         infcx: &'a InferCtxt<'a, 'tcx>,
820         def: ty::WithOptConstParam<LocalDefId>,
821         hir_id: hir::HirId,
822         span: Span,
823         arg_count: usize,
824         safety: Safety,
825         return_ty: Ty<'tcx>,
826         return_span: Span,
827         generator_kind: Option<GeneratorKind>,
828     ) -> Builder<'a, 'tcx> {
829         let tcx = infcx.tcx;
830         let attrs = tcx.hir().attrs(hir_id);
831         // Some functions always have overflow checks enabled,
832         // however, they may not get codegen'd, depending on
833         // the settings for the crate they are codegened in.
834         let mut check_overflow = tcx.sess.contains_name(attrs, sym::rustc_inherit_overflow_checks);
835         // Respect -C overflow-checks.
836         check_overflow |= tcx.sess.overflow_checks();
837         // Constants always need overflow checks.
838         check_overflow |= matches!(
839             tcx.hir().body_owner_kind(def.did),
840             hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_)
841         );
842
843         let lint_level = LintLevel::Explicit(hir_id);
844         let param_env = tcx.param_env(def.did);
845         let mut builder = Builder {
846             thir,
847             tcx,
848             infcx,
849             typeck_results: tcx.typeck_opt_const_arg(def),
850             region_scope_tree: tcx.region_scope_tree(def.did),
851             param_env,
852             def_id: def.did.to_def_id(),
853             hir_id,
854             parent_module: tcx.parent_module(hir_id).to_def_id(),
855             check_overflow,
856             cfg: CFG { basic_blocks: IndexVec::new() },
857             fn_span: span,
858             arg_count,
859             generator_kind,
860             scopes: scope::Scopes::new(),
861             block_context: BlockContext::new(),
862             source_scopes: IndexVec::new(),
863             source_scope: OUTERMOST_SOURCE_SCOPE,
864             guard_context: vec![],
865             in_scope_unsafe: safety,
866             local_decls: IndexVec::from_elem_n(LocalDecl::new(return_ty, return_span), 1),
867             canonical_user_type_annotations: IndexVec::new(),
868             upvar_mutbls: vec![],
869             var_indices: Default::default(),
870             unit_temp: None,
871             var_debug_info: vec![],
872         };
873
874         assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
875         assert_eq!(
876             builder.new_source_scope(span, lint_level, Some(safety)),
877             OUTERMOST_SOURCE_SCOPE
878         );
879         builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
880
881         builder
882     }
883
884     fn finish(self) -> Body<'tcx> {
885         for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
886             if block.terminator.is_none() {
887                 span_bug!(self.fn_span, "no terminator on block {:?}", index);
888             }
889         }
890
891         Body::new(
892             MirSource::item(self.def_id),
893             self.cfg.basic_blocks,
894             self.source_scopes,
895             self.local_decls,
896             self.canonical_user_type_annotations,
897             self.arg_count,
898             self.var_debug_info,
899             self.fn_span,
900             self.generator_kind,
901             self.typeck_results.tainted_by_errors,
902         )
903     }
904
905     fn args_and_body(
906         &mut self,
907         mut block: BasicBlock,
908         fn_def_id: LocalDefId,
909         arguments: &[ArgInfo<'tcx>],
910         argument_scope: region::Scope,
911         expr: &Expr<'tcx>,
912     ) -> BlockAnd<()> {
913         // Allocate locals for the function arguments
914         for &ArgInfo(ty, _, arg_opt, _) in arguments.iter() {
915             let source_info =
916                 SourceInfo::outermost(arg_opt.map_or(self.fn_span, |arg| arg.pat.span));
917             let arg_local = self.local_decls.push(LocalDecl::with_source_info(ty, source_info));
918
919             // If this is a simple binding pattern, give debuginfo a nice name.
920             if let Some(arg) = arg_opt && let Some(ident) = arg.pat.simple_ident() {
921                 self.var_debug_info.push(VarDebugInfo {
922                     name: ident.name,
923                     source_info,
924                     value: VarDebugInfoContents::Place(arg_local.into()),
925                 });
926             }
927         }
928
929         let tcx = self.tcx;
930         let tcx_hir = tcx.hir();
931         let hir_typeck_results = self.typeck_results;
932
933         // In analyze_closure() in upvar.rs we gathered a list of upvars used by an
934         // indexed closure and we stored in a map called closure_min_captures in TypeckResults
935         // with the closure's DefId. Here, we run through that vec of UpvarIds for
936         // the given closure and use the necessary information to create upvar
937         // debuginfo and to fill `self.upvar_mutbls`.
938         if hir_typeck_results.closure_min_captures.get(&fn_def_id).is_some() {
939             let mut closure_env_projs = vec![];
940             let mut closure_ty = self.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty;
941             if let ty::Ref(_, ty, _) = closure_ty.kind() {
942                 closure_env_projs.push(ProjectionElem::Deref);
943                 closure_ty = *ty;
944             }
945             let upvar_substs = match closure_ty.kind() {
946                 ty::Closure(_, substs) => ty::UpvarSubsts::Closure(substs),
947                 ty::Generator(_, substs, _) => ty::UpvarSubsts::Generator(substs),
948                 _ => span_bug!(self.fn_span, "upvars with non-closure env ty {:?}", closure_ty),
949             };
950             let def_id = self.def_id.as_local().unwrap();
951             let capture_syms = tcx.symbols_for_closure_captures((def_id, fn_def_id));
952             let capture_tys = upvar_substs.upvar_tys();
953             let captures_with_tys = hir_typeck_results
954                 .closure_min_captures_flattened(fn_def_id)
955                 .zip(capture_tys.zip(capture_syms));
956
957             self.upvar_mutbls = captures_with_tys
958                 .enumerate()
959                 .map(|(i, (captured_place, (ty, sym)))| {
960                     let capture = captured_place.info.capture_kind;
961                     let var_id = match captured_place.place.base {
962                         HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
963                         _ => bug!("Expected an upvar"),
964                     };
965
966                     let mutability = captured_place.mutability;
967
968                     let mut projs = closure_env_projs.clone();
969                     projs.push(ProjectionElem::Field(Field::new(i), ty));
970                     match capture {
971                         ty::UpvarCapture::ByValue => {}
972                         ty::UpvarCapture::ByRef(..) => {
973                             projs.push(ProjectionElem::Deref);
974                         }
975                     };
976
977                     self.var_debug_info.push(VarDebugInfo {
978                         name: *sym,
979                         source_info: SourceInfo::outermost(tcx_hir.span(var_id)),
980                         value: VarDebugInfoContents::Place(Place {
981                             local: ty::CAPTURE_STRUCT_LOCAL,
982                             projection: tcx.intern_place_elems(&projs),
983                         }),
984                     });
985
986                     mutability
987                 })
988                 .collect();
989         }
990
991         let mut scope = None;
992         // Bind the argument patterns
993         for (index, arg_info) in arguments.iter().enumerate() {
994             // Function arguments always get the first Local indices after the return place
995             let local = Local::new(index + 1);
996             let place = Place::from(local);
997             let &ArgInfo(_, opt_ty_info, arg_opt, ref self_binding) = arg_info;
998
999             // Make sure we drop (parts of) the argument even when not matched on.
1000             self.schedule_drop(
1001                 arg_opt.as_ref().map_or(expr.span, |arg| arg.pat.span),
1002                 argument_scope,
1003                 local,
1004                 DropKind::Value,
1005             );
1006
1007             let Some(arg) = arg_opt else {
1008                 continue;
1009             };
1010             let pat = match tcx.hir().get(arg.pat.hir_id) {
1011                 Node::Pat(pat) => pat,
1012                 node => bug!("pattern became {:?}", node),
1013             };
1014             let pattern = pat_from_hir(tcx, self.param_env, self.typeck_results, pat);
1015             let original_source_scope = self.source_scope;
1016             let span = pattern.span;
1017             self.set_correct_source_scope_for_arg(arg.hir_id, original_source_scope, span);
1018             match pattern.kind {
1019                 // Don't introduce extra copies for simple bindings
1020                 PatKind::Binding {
1021                     mutability,
1022                     var,
1023                     mode: BindingMode::ByValue,
1024                     subpattern: None,
1025                     ..
1026                 } => {
1027                     self.local_decls[local].mutability = mutability;
1028                     self.local_decls[local].source_info.scope = self.source_scope;
1029                     self.local_decls[local].local_info = if let Some(kind) = self_binding {
1030                         Some(Box::new(LocalInfo::User(ClearCrossCrate::Set(
1031                             BindingForm::ImplicitSelf(*kind),
1032                         ))))
1033                     } else {
1034                         let binding_mode = ty::BindingMode::BindByValue(mutability);
1035                         Some(Box::new(LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
1036                             VarBindingForm {
1037                                 binding_mode,
1038                                 opt_ty_info,
1039                                 opt_match_place: Some((None, span)),
1040                                 pat_span: span,
1041                             },
1042                         )))))
1043                     };
1044                     self.var_indices.insert(var, LocalsForNode::One(local));
1045                 }
1046                 _ => {
1047                     scope = self.declare_bindings(
1048                         scope,
1049                         expr.span,
1050                         &pattern,
1051                         matches::ArmHasGuard(false),
1052                         Some((Some(&place), span)),
1053                     );
1054                     let place_builder = PlaceBuilder::from(local);
1055                     unpack!(
1056                         block =
1057                             self.place_into_pattern(block, pattern.as_ref(), place_builder, false)
1058                     );
1059                 }
1060             }
1061             self.source_scope = original_source_scope;
1062         }
1063
1064         // Enter the argument pattern bindings source scope, if it exists.
1065         if let Some(source_scope) = scope {
1066             self.source_scope = source_scope;
1067         }
1068
1069         self.expr_into_dest(Place::return_place(), block, &expr)
1070     }
1071
1072     fn set_correct_source_scope_for_arg(
1073         &mut self,
1074         arg_hir_id: hir::HirId,
1075         original_source_scope: SourceScope,
1076         pattern_span: Span,
1077     ) {
1078         let tcx = self.tcx;
1079         let current_root = tcx.maybe_lint_level_root_bounded(arg_hir_id, self.hir_id);
1080         let parent_root = tcx.maybe_lint_level_root_bounded(
1081             self.source_scopes[original_source_scope]
1082                 .local_data
1083                 .as_ref()
1084                 .assert_crate_local()
1085                 .lint_root,
1086             self.hir_id,
1087         );
1088         if current_root != parent_root {
1089             self.source_scope =
1090                 self.new_source_scope(pattern_span, LintLevel::Explicit(current_root), None);
1091         }
1092     }
1093
1094     fn get_unit_temp(&mut self) -> Place<'tcx> {
1095         match self.unit_temp {
1096             Some(tmp) => tmp,
1097             None => {
1098                 let ty = self.tcx.mk_unit();
1099                 let fn_span = self.fn_span;
1100                 let tmp = self.temp(ty, fn_span);
1101                 self.unit_temp = Some(tmp);
1102                 tmp
1103             }
1104         }
1105     }
1106 }
1107
1108 fn parse_float_into_constval<'tcx>(
1109     num: Symbol,
1110     float_ty: ty::FloatTy,
1111     neg: bool,
1112 ) -> Option<ConstValue<'tcx>> {
1113     parse_float_into_scalar(num, float_ty, neg).map(ConstValue::Scalar)
1114 }
1115
1116 pub(crate) fn parse_float_into_scalar(
1117     num: Symbol,
1118     float_ty: ty::FloatTy,
1119     neg: bool,
1120 ) -> Option<Scalar> {
1121     let num = num.as_str();
1122     match float_ty {
1123         ty::FloatTy::F32 => {
1124             let Ok(rust_f) = num.parse::<f32>() else { return None };
1125             let mut f = num.parse::<Single>().unwrap_or_else(|e| {
1126                 panic!("apfloat::ieee::Single failed to parse `{}`: {:?}", num, e)
1127             });
1128
1129             assert!(
1130                 u128::from(rust_f.to_bits()) == f.to_bits(),
1131                 "apfloat::ieee::Single gave different result for `{}`: \
1132                  {}({:#x}) vs Rust's {}({:#x})",
1133                 rust_f,
1134                 f,
1135                 f.to_bits(),
1136                 Single::from_bits(rust_f.to_bits().into()),
1137                 rust_f.to_bits()
1138             );
1139
1140             if neg {
1141                 f = -f;
1142             }
1143
1144             Some(Scalar::from_f32(f))
1145         }
1146         ty::FloatTy::F64 => {
1147             let Ok(rust_f) = num.parse::<f64>() else { return None };
1148             let mut f = num.parse::<Double>().unwrap_or_else(|e| {
1149                 panic!("apfloat::ieee::Double failed to parse `{}`: {:?}", num, e)
1150             });
1151
1152             assert!(
1153                 u128::from(rust_f.to_bits()) == f.to_bits(),
1154                 "apfloat::ieee::Double gave different result for `{}`: \
1155                  {}({:#x}) vs Rust's {}({:#x})",
1156                 rust_f,
1157                 f,
1158                 f.to_bits(),
1159                 Double::from_bits(rust_f.to_bits().into()),
1160                 rust_f.to_bits()
1161             );
1162
1163             if neg {
1164                 f = -f;
1165             }
1166
1167             Some(Scalar::from_f64(f))
1168         }
1169     }
1170 }
1171
1172 ///////////////////////////////////////////////////////////////////////////
1173 // Builder methods are broken up into modules, depending on what kind
1174 // of thing is being lowered. Note that they use the `unpack` macro
1175 // above extensively.
1176
1177 mod block;
1178 mod cfg;
1179 mod expr;
1180 mod matches;
1181 mod misc;
1182 mod scope;
1183
1184 pub(crate) use expr::category::Category as ExprCategory;