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