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