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