]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_build/src/build/mod.rs
Add a query for `CapturedPlace::to_symbol`
[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::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
371     in_scope_unsafe: Safety,
372
373     /// The vector of all scopes that we have created thus far;
374     /// we track this for debuginfo later.
375     source_scopes: IndexVec<SourceScope, SourceScopeData<'tcx>>,
376     source_scope: SourceScope,
377
378     /// The guard-context: each time we build the guard expression for
379     /// a match arm, we push onto this stack, and then pop when we
380     /// finish building it.
381     guard_context: Vec<GuardFrame>,
382
383     /// Maps `HirId`s of variable bindings to the `Local`s created for them.
384     /// (A match binding can have two locals; the 2nd is for the arm's guard.)
385     var_indices: HirIdMap<LocalsForNode>,
386     local_decls: IndexVec<Local, LocalDecl<'tcx>>,
387     canonical_user_type_annotations: ty::CanonicalUserTypeAnnotations<'tcx>,
388     upvar_mutbls: Vec<Mutability>,
389     unit_temp: Option<Place<'tcx>>,
390
391     var_debug_info: Vec<VarDebugInfo<'tcx>>,
392 }
393
394 impl<'a, 'tcx> Builder<'a, 'tcx> {
395     fn is_bound_var_in_guard(&self, id: hir::HirId) -> bool {
396         self.guard_context.iter().any(|frame| frame.locals.iter().any(|local| local.id == id))
397     }
398
399     fn var_local_id(&self, id: hir::HirId, for_guard: ForGuard) -> Local {
400         self.var_indices[&id].local_id(for_guard)
401     }
402 }
403
404 impl BlockContext {
405     fn new() -> Self {
406         BlockContext(vec![])
407     }
408     fn push(&mut self, bf: BlockFrame) {
409         self.0.push(bf);
410     }
411     fn pop(&mut self) -> Option<BlockFrame> {
412         self.0.pop()
413     }
414
415     /// Traverses the frames on the `BlockContext`, searching for either
416     /// the first block-tail expression frame with no intervening
417     /// statement frame.
418     ///
419     /// Notably, this skips over `SubExpr` frames; this method is
420     /// meant to be used in the context of understanding the
421     /// relationship of a temp (created within some complicated
422     /// expression) with its containing expression, and whether the
423     /// value of that *containing expression* (not the temp!) is
424     /// ignored.
425     fn currently_in_block_tail(&self) -> Option<BlockTailInfo> {
426         for bf in self.0.iter().rev() {
427             match bf {
428                 BlockFrame::SubExpr => continue,
429                 BlockFrame::Statement { .. } => break,
430                 &BlockFrame::TailExpr { tail_result_is_ignored, span } => {
431                     return Some(BlockTailInfo { tail_result_is_ignored, span });
432                 }
433             }
434         }
435
436         None
437     }
438
439     /// Looks at the topmost frame on the BlockContext and reports
440     /// whether its one that would discard a block tail result.
441     ///
442     /// Unlike `currently_within_ignored_tail_expression`, this does
443     /// *not* skip over `SubExpr` frames: here, we want to know
444     /// whether the block result itself is discarded.
445     fn currently_ignores_tail_results(&self) -> bool {
446         match self.0.last() {
447             // no context: conservatively assume result is read
448             None => false,
449
450             // sub-expression: block result feeds into some computation
451             Some(BlockFrame::SubExpr) => false,
452
453             // otherwise: use accumulated is_ignored state.
454             Some(
455                 BlockFrame::TailExpr { tail_result_is_ignored: ignored, .. }
456                 | BlockFrame::Statement { ignores_expr_result: ignored },
457             ) => *ignored,
458         }
459     }
460 }
461
462 #[derive(Debug)]
463 enum LocalsForNode {
464     /// In the usual case, a `HirId` for an identifier maps to at most
465     /// one `Local` declaration.
466     One(Local),
467
468     /// The exceptional case is identifiers in a match arm's pattern
469     /// that are referenced in a guard of that match arm. For these,
470     /// we have `2` Locals.
471     ///
472     /// * `for_arm_body` is the Local used in the arm body (which is
473     ///   just like the `One` case above),
474     ///
475     /// * `ref_for_guard` is the Local used in the arm's guard (which
476     ///   is a reference to a temp that is an alias of
477     ///   `for_arm_body`).
478     ForGuard { ref_for_guard: Local, for_arm_body: Local },
479 }
480
481 #[derive(Debug)]
482 struct GuardFrameLocal {
483     id: hir::HirId,
484 }
485
486 impl GuardFrameLocal {
487     fn new(id: hir::HirId, _binding_mode: BindingMode) -> Self {
488         GuardFrameLocal { id }
489     }
490 }
491
492 #[derive(Debug)]
493 struct GuardFrame {
494     /// These are the id's of names that are bound by patterns of the
495     /// arm of *this* guard.
496     ///
497     /// (Frames higher up the stack will have the id's bound in arms
498     /// further out, such as in a case like:
499     ///
500     /// match E1 {
501     ///      P1(id1) if (... (match E2 { P2(id2) if ... => B2 })) => B1,
502     /// }
503     ///
504     /// here, when building for FIXME.
505     locals: Vec<GuardFrameLocal>,
506 }
507
508 /// `ForGuard` indicates whether we are talking about:
509 ///   1. The variable for use outside of guard expressions, or
510 ///   2. The temp that holds reference to (1.), which is actually what the
511 ///      guard expressions see.
512 #[derive(Copy, Clone, Debug, PartialEq, Eq)]
513 enum ForGuard {
514     RefWithinGuard,
515     OutsideGuard,
516 }
517
518 impl LocalsForNode {
519     fn local_id(&self, for_guard: ForGuard) -> Local {
520         match (self, for_guard) {
521             (&LocalsForNode::One(local_id), ForGuard::OutsideGuard)
522             | (
523                 &LocalsForNode::ForGuard { ref_for_guard: local_id, .. },
524                 ForGuard::RefWithinGuard,
525             )
526             | (&LocalsForNode::ForGuard { for_arm_body: local_id, .. }, ForGuard::OutsideGuard) => {
527                 local_id
528             }
529
530             (&LocalsForNode::One(_), ForGuard::RefWithinGuard) => {
531                 bug!("anything with one local should never be within a guard.")
532             }
533         }
534     }
535 }
536
537 struct CFG<'tcx> {
538     basic_blocks: IndexVec<BasicBlock, BasicBlockData<'tcx>>,
539 }
540
541 rustc_index::newtype_index! {
542     struct ScopeId { .. }
543 }
544
545 ///////////////////////////////////////////////////////////////////////////
546 /// The `BlockAnd` "monad" packages up the new basic block along with a
547 /// produced value (sometimes just unit, of course). The `unpack!`
548 /// macro (and methods below) makes working with `BlockAnd` much more
549 /// convenient.
550
551 #[must_use = "if you don't use one of these results, you're leaving a dangling edge"]
552 struct BlockAnd<T>(BasicBlock, T);
553
554 trait BlockAndExtension {
555     fn and<T>(self, v: T) -> BlockAnd<T>;
556     fn unit(self) -> BlockAnd<()>;
557 }
558
559 impl BlockAndExtension for BasicBlock {
560     fn and<T>(self, v: T) -> BlockAnd<T> {
561         BlockAnd(self, v)
562     }
563
564     fn unit(self) -> BlockAnd<()> {
565         BlockAnd(self, ())
566     }
567 }
568
569 /// Update a block pointer and return the value.
570 /// Use it like `let x = unpack!(block = self.foo(block, foo))`.
571 macro_rules! unpack {
572     ($x:ident = $c:expr) => {{
573         let BlockAnd(b, v) = $c;
574         $x = b;
575         v
576     }};
577
578     ($c:expr) => {{
579         let BlockAnd(b, ()) = $c;
580         b
581     }};
582 }
583
584 fn should_abort_on_panic(tcx: TyCtxt<'_>, fn_def_id: LocalDefId, abi: Abi) -> bool {
585     // Validate `#[unwind]` syntax regardless of platform-specific panic strategy.
586     let attrs = &tcx.get_attrs(fn_def_id.to_def_id());
587     let unwind_attr = attr::find_unwind_attr(&tcx.sess, attrs);
588
589     // We never unwind, so it's not relevant to stop an unwind.
590     if tcx.sess.panic_strategy() != PanicStrategy::Unwind {
591         return false;
592     }
593
594     match unwind_attr {
595         // If an `#[unwind]` attribute was found, we should adhere to it.
596         Some(UnwindAttr::Allowed) => false,
597         Some(UnwindAttr::Aborts) => true,
598         // If no attribute was found and the panic strategy is `unwind`, then we should examine
599         // the function's ABI string to determine whether it should abort upon panic.
600         None if tcx.features().c_unwind => {
601             use Abi::*;
602             match abi {
603                 // In the case of ABI's that have an `-unwind` equivalent, check whether the ABI
604                 // permits unwinding. If so, we should not abort. Otherwise, we should.
605                 C { unwind } | Stdcall { unwind } | System { unwind } | Thiscall { unwind } => {
606                     !unwind
607                 }
608                 // Rust and `rust-call` functions are allowed to unwind, and should not abort.
609                 Rust | RustCall => false,
610                 // Other ABI's should abort.
611                 Cdecl
612                 | Fastcall
613                 | Vectorcall
614                 | Aapcs
615                 | Win64
616                 | SysV64
617                 | PtxKernel
618                 | Msp430Interrupt
619                 | X86Interrupt
620                 | AmdGpuKernel
621                 | EfiApi
622                 | AvrInterrupt
623                 | AvrNonBlockingInterrupt
624                 | CCmseNonSecureCall
625                 | Wasm
626                 | RustIntrinsic
627                 | PlatformIntrinsic
628                 | Unadjusted => true,
629             }
630         }
631         // If the `c_unwind` feature gate is not active, follow the behavior that was in place
632         // prior to #76570. This is a special case: some functions have a C ABI but are meant to
633         // unwind anyway. Don't stop them.
634         None => false, // FIXME(#58794); should be `!(abi == Abi::Rust || abi == Abi::RustCall)`
635     }
636 }
637
638 ///////////////////////////////////////////////////////////////////////////
639 /// the main entry point for building MIR for a function
640
641 struct ArgInfo<'tcx>(
642     Ty<'tcx>,
643     Option<Span>,
644     Option<&'tcx hir::Param<'tcx>>,
645     Option<ImplicitSelfKind>,
646 );
647
648 fn construct_fn<'tcx, A>(
649     thir: &Thir<'tcx>,
650     infcx: &InferCtxt<'_, 'tcx>,
651     fn_def: ty::WithOptConstParam<LocalDefId>,
652     fn_id: hir::HirId,
653     arguments: A,
654     safety: Safety,
655     abi: Abi,
656     return_ty: Ty<'tcx>,
657     return_ty_span: Span,
658     body: &'tcx hir::Body<'tcx>,
659     expr: ExprId,
660     span_with_body: Span,
661 ) -> Body<'tcx>
662 where
663     A: Iterator<Item = ArgInfo<'tcx>>,
664 {
665     let arguments: Vec<_> = arguments.collect();
666
667     let tcx = infcx.tcx;
668     let span = tcx.hir().span(fn_id);
669
670     let mut builder = Builder::new(
671         thir,
672         infcx,
673         fn_def,
674         fn_id,
675         span_with_body,
676         arguments.len(),
677         safety,
678         return_ty,
679         return_ty_span,
680         body.generator_kind,
681     );
682
683     let call_site_scope =
684         region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::CallSite };
685     let arg_scope =
686         region::Scope { id: body.value.hir_id.local_id, data: region::ScopeData::Arguments };
687     let source_info = builder.source_info(span);
688     let call_site_s = (call_site_scope, source_info);
689     unpack!(builder.in_scope(call_site_s, LintLevel::Inherited, |builder| {
690         let arg_scope_s = (arg_scope, source_info);
691         // Attribute epilogue to function's closing brace
692         let fn_end = span_with_body.shrink_to_hi();
693         let return_block =
694             unpack!(builder.in_breakable_scope(None, Place::return_place(), fn_end, |builder| {
695                 Some(builder.in_scope(arg_scope_s, LintLevel::Inherited, |builder| {
696                     builder.args_and_body(
697                         START_BLOCK,
698                         fn_def.did.to_def_id(),
699                         &arguments,
700                         arg_scope,
701                         &thir[expr],
702                     )
703                 }))
704             }));
705         let source_info = builder.source_info(fn_end);
706         builder.cfg.terminate(return_block, source_info, TerminatorKind::Return);
707         let should_abort = should_abort_on_panic(tcx, fn_def.did, abi);
708         builder.build_drop_trees(should_abort);
709         return_block.unit()
710     }));
711
712     let spread_arg = if abi == Abi::RustCall {
713         // RustCall pseudo-ABI untuples the last argument.
714         Some(Local::new(arguments.len()))
715     } else {
716         None
717     };
718     debug!("fn_id {:?} has attrs {:?}", fn_def, tcx.get_attrs(fn_def.did.to_def_id()));
719
720     let mut body = builder.finish();
721     body.spread_arg = spread_arg;
722     body
723 }
724
725 fn construct_const<'a, 'tcx>(
726     thir: &'a Thir<'tcx>,
727     infcx: &'a InferCtxt<'a, 'tcx>,
728     expr: ExprId,
729     def: ty::WithOptConstParam<LocalDefId>,
730     hir_id: hir::HirId,
731     const_ty: Ty<'tcx>,
732     const_ty_span: Span,
733 ) -> Body<'tcx> {
734     let tcx = infcx.tcx;
735     let span = tcx.hir().span(hir_id);
736     let mut builder = Builder::new(
737         thir,
738         infcx,
739         def,
740         hir_id,
741         span,
742         0,
743         Safety::Safe,
744         const_ty,
745         const_ty_span,
746         None,
747     );
748
749     let mut block = START_BLOCK;
750     unpack!(block = builder.expr_into_dest(Place::return_place(), block, &thir[expr]));
751
752     let source_info = builder.source_info(span);
753     builder.cfg.terminate(block, source_info, TerminatorKind::Return);
754
755     builder.build_drop_trees(false);
756
757     builder.finish()
758 }
759
760 /// Construct MIR for a item that has had errors in type checking.
761 ///
762 /// This is required because we may still want to run MIR passes on an item
763 /// with type errors, but normal MIR construction can't handle that in general.
764 fn construct_error<'a, 'tcx>(
765     infcx: &'a InferCtxt<'a, 'tcx>,
766     def: ty::WithOptConstParam<LocalDefId>,
767     hir_id: hir::HirId,
768     body_id: hir::BodyId,
769     body_owner_kind: hir::BodyOwnerKind,
770 ) -> Body<'tcx> {
771     let tcx = infcx.tcx;
772     let span = tcx.hir().span(hir_id);
773     let ty = tcx.ty_error();
774     let generator_kind = tcx.hir().body(body_id).generator_kind;
775     let num_params = match body_owner_kind {
776         hir::BodyOwnerKind::Fn => tcx.hir().fn_decl_by_hir_id(hir_id).unwrap().inputs.len(),
777         hir::BodyOwnerKind::Closure => {
778             if generator_kind.is_some() {
779                 // Generators have an implicit `self` parameter *and* a possibly
780                 // implicit resume parameter.
781                 2
782             } else {
783                 // The implicit self parameter adds another local in MIR.
784                 1 + tcx.hir().fn_decl_by_hir_id(hir_id).unwrap().inputs.len()
785             }
786         }
787         hir::BodyOwnerKind::Const => 0,
788         hir::BodyOwnerKind::Static(_) => 0,
789     };
790     let mut cfg = CFG { basic_blocks: IndexVec::new() };
791     let mut source_scopes = IndexVec::new();
792     let mut local_decls = IndexVec::from_elem_n(LocalDecl::new(ty, span), 1);
793
794     cfg.start_new_block();
795     source_scopes.push(SourceScopeData {
796         span,
797         parent_scope: None,
798         inlined: None,
799         inlined_parent_scope: None,
800         local_data: ClearCrossCrate::Set(SourceScopeLocalData {
801             lint_root: hir_id,
802             safety: Safety::Safe,
803         }),
804     });
805     let source_info = SourceInfo { span, scope: OUTERMOST_SOURCE_SCOPE };
806
807     // Some MIR passes will expect the number of parameters to match the
808     // function declaration.
809     for _ in 0..num_params {
810         local_decls.push(LocalDecl::with_source_info(ty, source_info));
811     }
812     cfg.terminate(START_BLOCK, source_info, TerminatorKind::Unreachable);
813
814     let mut body = Body::new(
815         MirSource::item(def.did.to_def_id()),
816         cfg.basic_blocks,
817         source_scopes,
818         local_decls,
819         IndexVec::new(),
820         num_params,
821         vec![],
822         span,
823         generator_kind,
824     );
825     body.generator.as_mut().map(|gen| gen.yield_ty = Some(ty));
826     body
827 }
828
829 impl<'a, 'tcx> Builder<'a, 'tcx> {
830     fn new(
831         thir: &'a Thir<'tcx>,
832         infcx: &'a InferCtxt<'a, 'tcx>,
833         def: ty::WithOptConstParam<LocalDefId>,
834         hir_id: hir::HirId,
835         span: Span,
836         arg_count: usize,
837         safety: Safety,
838         return_ty: Ty<'tcx>,
839         return_span: Span,
840         generator_kind: Option<GeneratorKind>,
841     ) -> Builder<'a, 'tcx> {
842         let tcx = infcx.tcx;
843         let attrs = tcx.hir().attrs(hir_id);
844         // Some functions always have overflow checks enabled,
845         // however, they may not get codegen'd, depending on
846         // the settings for the crate they are codegened in.
847         let mut check_overflow = tcx.sess.contains_name(attrs, sym::rustc_inherit_overflow_checks);
848         // Respect -C overflow-checks.
849         check_overflow |= tcx.sess.overflow_checks();
850         // Constants always need overflow checks.
851         check_overflow |= matches!(
852             tcx.hir().body_owner_kind(hir_id),
853             hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_)
854         );
855
856         let lint_level = LintLevel::Explicit(hir_id);
857         let mut builder = Builder {
858             thir,
859             tcx,
860             infcx,
861             typeck_results: tcx.typeck_opt_const_arg(def),
862             region_scope_tree: tcx.region_scope_tree(def.did),
863             param_env: tcx.param_env(def.did),
864             def_id: def.did.to_def_id(),
865             hir_id,
866             check_overflow,
867             cfg: CFG { basic_blocks: IndexVec::new() },
868             fn_span: span,
869             arg_count,
870             generator_kind,
871             scopes: scope::Scopes::new(),
872             block_context: BlockContext::new(),
873             source_scopes: IndexVec::new(),
874             source_scope: OUTERMOST_SOURCE_SCOPE,
875             guard_context: vec![],
876             in_scope_unsafe: safety,
877             local_decls: IndexVec::from_elem_n(LocalDecl::new(return_ty, return_span), 1),
878             canonical_user_type_annotations: IndexVec::new(),
879             upvar_mutbls: vec![],
880             var_indices: Default::default(),
881             unit_temp: None,
882             var_debug_info: vec![],
883         };
884
885         assert_eq!(builder.cfg.start_new_block(), START_BLOCK);
886         assert_eq!(
887             builder.new_source_scope(span, lint_level, Some(safety)),
888             OUTERMOST_SOURCE_SCOPE
889         );
890         builder.source_scopes[OUTERMOST_SOURCE_SCOPE].parent_scope = None;
891
892         builder
893     }
894
895     fn finish(self) -> Body<'tcx> {
896         for (index, block) in self.cfg.basic_blocks.iter().enumerate() {
897             if block.terminator.is_none() {
898                 span_bug!(self.fn_span, "no terminator on block {:?}", index);
899             }
900         }
901
902         Body::new(
903             MirSource::item(self.def_id),
904             self.cfg.basic_blocks,
905             self.source_scopes,
906             self.local_decls,
907             self.canonical_user_type_annotations,
908             self.arg_count,
909             self.var_debug_info,
910             self.fn_span,
911             self.generator_kind,
912         )
913     }
914
915     fn args_and_body(
916         &mut self,
917         mut block: BasicBlock,
918         fn_def_id: DefId,
919         arguments: &[ArgInfo<'tcx>],
920         argument_scope: region::Scope,
921         expr: &Expr<'tcx>,
922     ) -> BlockAnd<()> {
923         // Allocate locals for the function arguments
924         for &ArgInfo(ty, _, arg_opt, _) in arguments.iter() {
925             let source_info =
926                 SourceInfo::outermost(arg_opt.map_or(self.fn_span, |arg| arg.pat.span));
927             let arg_local = self.local_decls.push(LocalDecl::with_source_info(ty, source_info));
928
929             // If this is a simple binding pattern, give debuginfo a nice name.
930             if let Some(arg) = arg_opt {
931                 if let Some(ident) = arg.pat.simple_ident() {
932                     self.var_debug_info.push(VarDebugInfo {
933                         name: ident.name,
934                         source_info,
935                         value: VarDebugInfoContents::Place(arg_local.into()),
936                     });
937                 }
938             }
939         }
940
941         let tcx = self.tcx;
942         let tcx_hir = tcx.hir();
943         let hir_typeck_results = self.typeck_results;
944
945         // In analyze_closure() in upvar.rs we gathered a list of upvars used by a
946         // indexed closure and we stored in a map called closure_min_captures in TypeckResults
947         // with the closure's DefId. Here, we run through that vec of UpvarIds for
948         // the given closure and use the necessary information to create upvar
949         // debuginfo and to fill `self.upvar_mutbls`.
950         if hir_typeck_results.closure_min_captures.get(&fn_def_id).is_some() {
951             let mut closure_env_projs = vec![];
952             let mut closure_ty = self.local_decls[ty::CAPTURE_STRUCT_LOCAL].ty;
953             if let ty::Ref(_, ty, _) = closure_ty.kind() {
954                 closure_env_projs.push(ProjectionElem::Deref);
955                 closure_ty = ty;
956             }
957             let upvar_substs = match closure_ty.kind() {
958                 ty::Closure(_, substs) => ty::UpvarSubsts::Closure(substs),
959                 ty::Generator(_, substs, _) => ty::UpvarSubsts::Generator(substs),
960                 _ => span_bug!(self.fn_span, "upvars with non-closure env ty {:?}", closure_ty),
961             };
962             let def_id = self.def_id.as_local().unwrap();
963             let capture_syms = tcx.symbols_for_closure_captures((def_id, fn_def_id));
964             let capture_tys = upvar_substs.upvar_tys();
965             let captures_with_tys = hir_typeck_results
966                 .closure_min_captures_flattened(fn_def_id)
967                 .zip(capture_tys.zip(capture_syms));
968
969             self.upvar_mutbls = captures_with_tys
970                 .enumerate()
971                 .map(|(i, (captured_place, (ty, sym)))| {
972                     let capture = captured_place.info.capture_kind;
973                     let var_id = match captured_place.place.base {
974                         HirPlaceBase::Upvar(upvar_id) => upvar_id.var_path.hir_id,
975                         _ => bug!("Expected an upvar"),
976                     };
977
978                     let mutability = captured_place.mutability;
979
980                     let mut projs = closure_env_projs.clone();
981                     projs.push(ProjectionElem::Field(Field::new(i), ty));
982                     match capture {
983                         ty::UpvarCapture::ByValue(_) => {}
984                         ty::UpvarCapture::ByRef(..) => {
985                             projs.push(ProjectionElem::Deref);
986                         }
987                     };
988
989                     self.var_debug_info.push(VarDebugInfo {
990                         name: sym,
991                         source_info: SourceInfo::outermost(tcx_hir.span(var_id)),
992                         value: VarDebugInfoContents::Place(Place {
993                             local: ty::CAPTURE_STRUCT_LOCAL,
994                             projection: tcx.intern_place_elems(&projs),
995                         }),
996                     });
997
998                     mutability
999                 })
1000                 .collect();
1001         }
1002
1003         let mut scope = None;
1004         // Bind the argument patterns
1005         for (index, arg_info) in arguments.iter().enumerate() {
1006             // Function arguments always get the first Local indices after the return place
1007             let local = Local::new(index + 1);
1008             let place = Place::from(local);
1009             let &ArgInfo(_, opt_ty_info, arg_opt, ref self_binding) = arg_info;
1010
1011             // Make sure we drop (parts of) the argument even when not matched on.
1012             self.schedule_drop(
1013                 arg_opt.as_ref().map_or(expr.span, |arg| arg.pat.span),
1014                 argument_scope,
1015                 local,
1016                 DropKind::Value,
1017             );
1018
1019             if let Some(arg) = arg_opt {
1020                 let pat = match tcx.hir().get(arg.pat.hir_id) {
1021                     Node::Pat(pat) | Node::Binding(pat) => pat,
1022                     node => bug!("pattern became {:?}", node),
1023                 };
1024                 let pattern = pat_from_hir(tcx, self.param_env, self.typeck_results, pat);
1025                 let original_source_scope = self.source_scope;
1026                 let span = pattern.span;
1027                 self.set_correct_source_scope_for_arg(arg.hir_id, original_source_scope, span);
1028                 match *pattern.kind {
1029                     // Don't introduce extra copies for simple bindings
1030                     PatKind::Binding {
1031                         mutability,
1032                         var,
1033                         mode: BindingMode::ByValue,
1034                         subpattern: None,
1035                         ..
1036                     } => {
1037                         self.local_decls[local].mutability = mutability;
1038                         self.local_decls[local].source_info.scope = self.source_scope;
1039                         self.local_decls[local].local_info = if let Some(kind) = self_binding {
1040                             Some(box LocalInfo::User(ClearCrossCrate::Set(
1041                                 BindingForm::ImplicitSelf(*kind),
1042                             )))
1043                         } else {
1044                             let binding_mode = ty::BindingMode::BindByValue(mutability);
1045                             Some(box LocalInfo::User(ClearCrossCrate::Set(BindingForm::Var(
1046                                 VarBindingForm {
1047                                     binding_mode,
1048                                     opt_ty_info,
1049                                     opt_match_place: Some((Some(place), span)),
1050                                     pat_span: span,
1051                                 },
1052                             ))))
1053                         };
1054                         self.var_indices.insert(var, LocalsForNode::One(local));
1055                     }
1056                     _ => {
1057                         scope = self.declare_bindings(
1058                             scope,
1059                             expr.span,
1060                             &pattern,
1061                             matches::ArmHasGuard(false),
1062                             Some((Some(&place), span)),
1063                         );
1064                         let place_builder = PlaceBuilder::from(local);
1065                         unpack!(
1066                             block = self.place_into_pattern(block, pattern, place_builder, false)
1067                         );
1068                     }
1069                 }
1070                 self.source_scope = original_source_scope;
1071             }
1072         }
1073
1074         // Enter the argument pattern bindings source scope, if it exists.
1075         if let Some(source_scope) = scope {
1076             self.source_scope = source_scope;
1077         }
1078
1079         self.expr_into_dest(Place::return_place(), block, &expr)
1080     }
1081
1082     fn set_correct_source_scope_for_arg(
1083         &mut self,
1084         arg_hir_id: hir::HirId,
1085         original_source_scope: SourceScope,
1086         pattern_span: Span,
1087     ) {
1088         let tcx = self.tcx;
1089         let current_root = tcx.maybe_lint_level_root_bounded(arg_hir_id, self.hir_id);
1090         let parent_root = tcx.maybe_lint_level_root_bounded(
1091             self.source_scopes[original_source_scope]
1092                 .local_data
1093                 .as_ref()
1094                 .assert_crate_local()
1095                 .lint_root,
1096             self.hir_id,
1097         );
1098         if current_root != parent_root {
1099             self.source_scope =
1100                 self.new_source_scope(pattern_span, LintLevel::Explicit(current_root), None);
1101         }
1102     }
1103
1104     fn get_unit_temp(&mut self) -> Place<'tcx> {
1105         match self.unit_temp {
1106             Some(tmp) => tmp,
1107             None => {
1108                 let ty = self.tcx.mk_unit();
1109                 let fn_span = self.fn_span;
1110                 let tmp = self.temp(ty, fn_span);
1111                 self.unit_temp = Some(tmp);
1112                 tmp
1113             }
1114         }
1115     }
1116 }
1117
1118 ///////////////////////////////////////////////////////////////////////////
1119 // Builder methods are broken up into modules, depending on what kind
1120 // of thing is being lowered. Note that they use the `unpack` macro
1121 // above extensively.
1122
1123 mod block;
1124 mod cfg;
1125 mod expr;
1126 mod matches;
1127 mod misc;
1128 mod scope;