]>
Commit | Line | Data |
---|---|---|
a7813a04 XL |
1 | //! A pass that promotes borrows of constant rvalues. |
2 | //! | |
3 | //! The rvalues considered constant are trees of temps, | |
4 | //! each with exactly one initialization, and holding | |
5 | //! a constant value with no interior mutability. | |
6 | //! They are placed into a new MIR constant body in | |
7 | //! `promoted` and the borrow rvalue is replaced with | |
8 | //! a `Literal::Promoted` using the index into `promoted` | |
9 | //! of that constant MIR. | |
10 | //! | |
11 | //! This pass assumes that every use is dominated by an | |
12 | //! initialization and can otherwise silence errors, if | |
13 | //! move analysis runs after promotion on broken MIR. | |
14 | ||
f9f354fc | 15 | use rustc_hir as hir; |
ba9703b0 XL |
16 | use rustc_middle::mir::traversal::ReversePostorder; |
17 | use rustc_middle::mir::visit::{MutVisitor, MutatingUseContext, PlaceContext, Visitor}; | |
18 | use rustc_middle::mir::*; | |
19 | use rustc_middle::ty::cast::CastTy; | |
20 | use rustc_middle::ty::subst::InternalSubsts; | |
21 | use rustc_middle::ty::{self, List, TyCtxt, TypeFoldable}; | |
fc512014 | 22 | use rustc_span::Span; |
a7813a04 | 23 | |
dfeec247 | 24 | use rustc_index::vec::{Idx, IndexVec}; |
a7813a04 | 25 | |
60c5eb7d | 26 | use std::cell::Cell; |
ba9703b0 | 27 | use std::{cmp, iter, mem}; |
a7813a04 | 28 | |
3c0e092e | 29 | use crate::transform::check_consts::{qualifs, ConstCx}; |
29967ef6 | 30 | use crate::transform::MirPass; |
e74abb32 | 31 | |
60c5eb7d XL |
32 | /// A `MirPass` for promotion. |
33 | /// | |
17df50a5 XL |
34 | /// Promotion is the extraction of promotable temps into separate MIR bodies so they can have |
35 | /// `'static` lifetime. | |
60c5eb7d XL |
36 | /// |
37 | /// After this pass is run, `promoted_fragments` will hold the MIR body corresponding to each | |
dfeec247 | 38 | /// newly created `Constant`. |
60c5eb7d XL |
39 | #[derive(Default)] |
40 | pub struct PromoteTemps<'tcx> { | |
f9f354fc | 41 | pub promoted_fragments: Cell<IndexVec<Promoted, Body<'tcx>>>, |
60c5eb7d XL |
42 | } |
43 | ||
44 | impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> { | |
29967ef6 | 45 | fn run_pass(&self, tcx: TyCtxt<'tcx>, body: &mut Body<'tcx>) { |
60c5eb7d XL |
46 | // There's not really any point in promoting errorful MIR. |
47 | // | |
48 | // This does not include MIR that failed const-checking, which we still try to promote. | |
49 | if body.return_ty().references_error() { | |
50 | tcx.sess.delay_span_bug(body.span, "PromoteTemps: MIR had errors"); | |
51 | return; | |
52 | } | |
53 | ||
29967ef6 | 54 | if body.source.promoted.is_some() { |
60c5eb7d XL |
55 | return; |
56 | } | |
57 | ||
60c5eb7d | 58 | let mut rpo = traversal::reverse_postorder(body); |
29967ef6 | 59 | let ccx = ConstCx::new(tcx, body); |
f9f354fc | 60 | let (temps, all_candidates) = collect_temps_and_candidates(&ccx, &mut rpo); |
60c5eb7d | 61 | |
f9f354fc | 62 | let promotable_candidates = validate_candidates(&ccx, &temps, &all_candidates); |
60c5eb7d | 63 | |
29967ef6 | 64 | let promoted = promote_candidates(body, tcx, temps, promotable_candidates); |
60c5eb7d XL |
65 | self.promoted_fragments.set(promoted); |
66 | } | |
67 | } | |
68 | ||
a7813a04 XL |
69 | /// State of a temporary during collection and promotion. |
70 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] | |
71 | pub enum TempState { | |
72 | /// No references to this temp. | |
73 | Undefined, | |
74 | /// One direct assignment and any number of direct uses. | |
75 | /// A borrow of this temp is promotable if the assigned | |
76 | /// value is qualified as constant. | |
dfeec247 | 77 | Defined { location: Location, uses: usize }, |
a7813a04 XL |
78 | /// Any other combination of assignments/uses. |
79 | Unpromotable, | |
80 | /// This temp was part of an rvalue which got extracted | |
81 | /// during promotion and needs cleanup. | |
dfeec247 | 82 | PromotedOut, |
a7813a04 XL |
83 | } |
84 | ||
85 | impl TempState { | |
86 | pub fn is_promotable(&self) -> bool { | |
13cf67c4 | 87 | debug!("is_promotable: self={:?}", self); |
5869c6ff | 88 | matches!(self, TempState::Defined { .. }) |
a7813a04 XL |
89 | } |
90 | } | |
91 | ||
92 | /// A "root candidate" for promotion, which will become the | |
93 | /// returned value in a promoted MIR, unless it's a subset | |
94 | /// of a larger candidate. | |
e74abb32 | 95 | #[derive(Copy, Clone, PartialEq, Eq, Debug)] |
3c0e092e XL |
96 | pub struct Candidate { |
97 | location: Location, | |
e74abb32 XL |
98 | } |
99 | ||
e74abb32 | 100 | struct Collector<'a, 'tcx> { |
f9f354fc | 101 | ccx: &'a ConstCx<'a, 'tcx>, |
c30ab7b3 | 102 | temps: IndexVec<Local, TempState>, |
e74abb32 | 103 | candidates: Vec<Candidate>, |
a7813a04 XL |
104 | } |
105 | ||
e74abb32 | 106 | impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> { |
dfeec247 | 107 | fn visit_local(&mut self, &index: &Local, context: PlaceContext, location: Location) { |
13cf67c4 | 108 | debug!("visit_local: index={:?} context={:?} location={:?}", index, context, location); |
48663c56 | 109 | // We're only interested in temporaries and the return place |
f9f354fc | 110 | match self.ccx.body.local_kind(index) { |
dfeec247 XL |
111 | LocalKind::Temp | LocalKind::ReturnPointer => {} |
112 | LocalKind::Arg | LocalKind::Var => return, | |
ea8adc8c | 113 | } |
c30ab7b3 | 114 | |
ea8adc8c XL |
115 | // Ignore drops, if the temp gets promoted, |
116 | // then it's constant and thus drop is noop. | |
60c5eb7d | 117 | // Non-uses are also irrelevant. |
13cf67c4 XL |
118 | if context.is_drop() || !context.is_use() { |
119 | debug!( | |
120 | "visit_local: context.is_drop={:?} context.is_use={:?}", | |
dfeec247 XL |
121 | context.is_drop(), |
122 | context.is_use(), | |
13cf67c4 | 123 | ); |
ea8adc8c XL |
124 | return; |
125 | } | |
a7813a04 | 126 | |
ea8adc8c | 127 | let temp = &mut self.temps[index]; |
13cf67c4 | 128 | debug!("visit_local: temp={:?}", temp); |
ea8adc8c XL |
129 | if *temp == TempState::Undefined { |
130 | match context { | |
dfeec247 XL |
131 | PlaceContext::MutatingUse(MutatingUseContext::Store) |
132 | | PlaceContext::MutatingUse(MutatingUseContext::Call) => { | |
133 | *temp = TempState::Defined { location, uses: 0 }; | |
32a655c1 | 134 | return; |
a7813a04 | 135 | } |
ea8adc8c | 136 | _ => { /* mark as unpromotable below */ } |
a7813a04 | 137 | } |
ea8adc8c XL |
138 | } else if let TempState::Defined { ref mut uses, .. } = *temp { |
139 | // We always allow borrows, even mutable ones, as we need | |
0731742a | 140 | // to promote mutable borrows of some ZSTs e.g., `&mut []`. |
dfeec247 XL |
141 | let allowed_use = match context { |
142 | PlaceContext::MutatingUse(MutatingUseContext::Borrow) | |
143 | | PlaceContext::NonMutatingUse(_) => true, | |
144 | PlaceContext::MutatingUse(_) | PlaceContext::NonUse(_) => false, | |
145 | }; | |
13cf67c4 | 146 | debug!("visit_local: allowed_use={:?}", allowed_use); |
ea8adc8c XL |
147 | if allowed_use { |
148 | *uses += 1; | |
149 | return; | |
150 | } | |
151 | /* mark as unpromotable below */ | |
a7813a04 | 152 | } |
ea8adc8c | 153 | *temp = TempState::Unpromotable; |
a7813a04 XL |
154 | } |
155 | ||
e74abb32 XL |
156 | fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) { |
157 | self.super_rvalue(rvalue, location); | |
158 | ||
159 | match *rvalue { | |
160 | Rvalue::Ref(..) => { | |
3c0e092e | 161 | self.candidates.push(Candidate { location }); |
e74abb32 | 162 | } |
e74abb32 XL |
163 | _ => {} |
164 | } | |
165 | } | |
a7813a04 XL |
166 | } |
167 | ||
e74abb32 | 168 | pub fn collect_temps_and_candidates( |
f9f354fc | 169 | ccx: &ConstCx<'mir, 'tcx>, |
e74abb32 XL |
170 | rpo: &mut ReversePostorder<'_, 'tcx>, |
171 | ) -> (IndexVec<Local, TempState>, Vec<Candidate>) { | |
172 | let mut collector = Collector { | |
f9f354fc | 173 | temps: IndexVec::from_elem(TempState::Undefined, &ccx.body.local_decls), |
e74abb32 | 174 | candidates: vec![], |
f9f354fc | 175 | ccx, |
a7813a04 XL |
176 | }; |
177 | for (bb, data) in rpo { | |
178 | collector.visit_basic_block_data(bb, data); | |
179 | } | |
e74abb32 XL |
180 | (collector.temps, collector.candidates) |
181 | } | |
182 | ||
183 | /// Checks whether locals that appear in a promotion context (`Candidate`) are actually promotable. | |
184 | /// | |
185 | /// This wraps an `Item`, and has access to all fields of that `Item` via `Deref` coercion. | |
186 | struct Validator<'a, 'tcx> { | |
f9f354fc | 187 | ccx: &'a ConstCx<'a, 'tcx>, |
e74abb32 | 188 | temps: &'a IndexVec<Local, TempState>, |
e74abb32 XL |
189 | } |
190 | ||
191 | impl std::ops::Deref for Validator<'a, 'tcx> { | |
f9f354fc | 192 | type Target = ConstCx<'a, 'tcx>; |
e74abb32 XL |
193 | |
194 | fn deref(&self) -> &Self::Target { | |
f9f354fc | 195 | &self.ccx |
e74abb32 XL |
196 | } |
197 | } | |
198 | ||
199 | struct Unpromotable; | |
200 | ||
201 | impl<'tcx> Validator<'_, 'tcx> { | |
202 | fn validate_candidate(&self, candidate: Candidate) -> Result<(), Unpromotable> { | |
3c0e092e XL |
203 | let loc = candidate.location; |
204 | let statement = &self.body[loc.block].statements[loc.statement_index]; | |
205 | match &statement.kind { | |
206 | StatementKind::Assign(box (_, Rvalue::Ref(_, kind, place))) => { | |
207 | // We can only promote interior borrows of promotable temps (non-temps | |
208 | // don't get promoted anyway). | |
209 | self.validate_local(place.local)?; | |
210 | ||
211 | // The reference operation itself must be promotable. | |
212 | // (Needs to come after `validate_local` to avoid ICEs.) | |
213 | self.validate_ref(*kind, place)?; | |
e74abb32 | 214 | |
3c0e092e XL |
215 | // We do not check all the projections (they do not get promoted anyway), |
216 | // but we do stay away from promoting anything involving a dereference. | |
217 | if place.projection.contains(&ProjectionElem::Deref) { | |
218 | return Err(Unpromotable); | |
219 | } | |
e74abb32 | 220 | |
3c0e092e XL |
221 | // We cannot promote things that need dropping, since the promoted value |
222 | // would not get dropped. | |
223 | if self.qualif_local::<qualifs::NeedsDrop>(place.local) { | |
224 | return Err(Unpromotable); | |
e74abb32 | 225 | } |
3c0e092e XL |
226 | |
227 | Ok(()) | |
e74abb32 | 228 | } |
3c0e092e | 229 | _ => bug!(), |
e74abb32 XL |
230 | } |
231 | } | |
232 | ||
233 | // FIXME(eddyb) maybe cache this? | |
234 | fn qualif_local<Q: qualifs::Qualif>(&self, local: Local) -> bool { | |
e74abb32 XL |
235 | if let TempState::Defined { location: loc, .. } = self.temps[local] { |
236 | let num_stmts = self.body[loc.block].statements.len(); | |
237 | ||
238 | if loc.statement_index < num_stmts { | |
239 | let statement = &self.body[loc.block].statements[loc.statement_index]; | |
240 | match &statement.kind { | |
ba9703b0 | 241 | StatementKind::Assign(box (_, rhs)) => qualifs::in_rvalue::<Q, _>( |
f9f354fc | 242 | &self.ccx, |
ba9703b0 XL |
243 | &mut |l| self.qualif_local::<Q>(l), |
244 | rhs, | |
245 | ), | |
e74abb32 | 246 | _ => { |
dfeec247 XL |
247 | span_bug!( |
248 | statement.source_info.span, | |
249 | "{:?} is not an assignment", | |
250 | statement | |
251 | ); | |
e74abb32 XL |
252 | } |
253 | } | |
254 | } else { | |
255 | let terminator = self.body[loc.block].terminator(); | |
256 | match &terminator.kind { | |
ba9703b0 | 257 | TerminatorKind::Call { .. } => { |
e74abb32 | 258 | let return_ty = self.body.local_decls[local].ty; |
f9f354fc | 259 | Q::in_any_value_of_ty(&self.ccx, return_ty) |
e74abb32 XL |
260 | } |
261 | kind => { | |
262 | span_bug!(terminator.source_info.span, "{:?} not promotable", kind); | |
263 | } | |
264 | } | |
265 | } | |
266 | } else { | |
267 | let span = self.body.local_decls[local].source_info.span; | |
268 | span_bug!(span, "{:?} not promotable, qualif_local shouldn't have been called", local); | |
269 | } | |
270 | } | |
271 | ||
272 | // FIXME(eddyb) maybe cache this? | |
273 | fn validate_local(&self, local: Local) -> Result<(), Unpromotable> { | |
274 | if let TempState::Defined { location: loc, .. } = self.temps[local] { | |
5869c6ff XL |
275 | let block = &self.body[loc.block]; |
276 | let num_stmts = block.statements.len(); | |
e74abb32 XL |
277 | |
278 | if loc.statement_index < num_stmts { | |
5869c6ff | 279 | let statement = &block.statements[loc.statement_index]; |
e74abb32 | 280 | match &statement.kind { |
dfeec247 | 281 | StatementKind::Assign(box (_, rhs)) => self.validate_rvalue(rhs), |
e74abb32 | 282 | _ => { |
dfeec247 XL |
283 | span_bug!( |
284 | statement.source_info.span, | |
285 | "{:?} is not an assignment", | |
286 | statement | |
287 | ); | |
e74abb32 XL |
288 | } |
289 | } | |
290 | } else { | |
5869c6ff | 291 | let terminator = block.terminator(); |
e74abb32 XL |
292 | match &terminator.kind { |
293 | TerminatorKind::Call { func, args, .. } => self.validate_call(func, args), | |
74b04a01 | 294 | TerminatorKind::Yield { .. } => Err(Unpromotable), |
e74abb32 XL |
295 | kind => { |
296 | span_bug!(terminator.source_info.span, "{:?} not promotable", kind); | |
297 | } | |
298 | } | |
299 | } | |
300 | } else { | |
301 | Err(Unpromotable) | |
302 | } | |
303 | } | |
304 | ||
74b04a01 | 305 | fn validate_place(&self, place: PlaceRef<'tcx>) -> Result<(), Unpromotable> { |
5869c6ff XL |
306 | match place.last_projection() { |
307 | None => self.validate_local(place.local), | |
308 | Some((place_base, elem)) => { | |
1b1a35ee | 309 | // Validate topmost projection, then recurse. |
5869c6ff | 310 | match elem { |
3dfed10e | 311 | ProjectionElem::Deref => { |
1b1a35ee | 312 | let mut promotable = false; |
5869c6ff XL |
313 | // We need to make sure this is a `Deref` of a local with no further projections. |
314 | // Discussion can be found at | |
315 | // https://github.com/rust-lang/rust/pull/74945#discussion_r463063247 | |
316 | if let Some(local) = place_base.as_local() { | |
317 | // This is a special treatment for cases like *&STATIC where STATIC is a | |
318 | // global static variable. | |
319 | // This pattern is generated only when global static variables are directly | |
320 | // accessed and is qualified for promotion safely. | |
321 | if let TempState::Defined { location, .. } = self.temps[local] { | |
322 | let def_stmt = self.body[location.block] | |
323 | .statements | |
324 | .get(location.statement_index); | |
325 | if let Some(Statement { | |
326 | kind: | |
327 | StatementKind::Assign(box ( | |
328 | _, | |
329 | Rvalue::Use(Operand::Constant(c)), | |
330 | )), | |
331 | .. | |
332 | }) = def_stmt | |
333 | { | |
334 | if let Some(did) = c.check_static_ptr(self.tcx) { | |
335 | // Evaluating a promoted may not read statics except if it got | |
336 | // promoted from a static (this is a CTFE check). So we | |
337 | // can only promote static accesses inside statics. | |
338 | if let Some(hir::ConstContext::Static(..)) = self.const_kind | |
3dfed10e | 339 | { |
5869c6ff XL |
340 | if !self.tcx.is_thread_local_static(did) { |
341 | promotable = true; | |
342 | } | |
3dfed10e XL |
343 | } |
344 | } | |
345 | } | |
346 | } | |
347 | } | |
1b1a35ee | 348 | if !promotable { |
3dfed10e XL |
349 | return Err(Unpromotable); |
350 | } | |
351 | } | |
352 | ProjectionElem::Downcast(..) => { | |
dfeec247 XL |
353 | return Err(Unpromotable); |
354 | } | |
e74abb32 | 355 | |
dfeec247 | 356 | ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. } => {} |
e74abb32 XL |
357 | |
358 | ProjectionElem::Index(local) => { | |
17df50a5 XL |
359 | let mut promotable = false; |
360 | // Only accept if we can predict the index and are indexing an array. | |
361 | let val = | |
362 | if let TempState::Defined { location: loc, .. } = self.temps[local] { | |
5869c6ff XL |
363 | let block = &self.body[loc.block]; |
364 | if loc.statement_index < block.statements.len() { | |
365 | let statement = &block.statements[loc.statement_index]; | |
366 | match &statement.kind { | |
367 | StatementKind::Assign(box ( | |
368 | _, | |
369 | Rvalue::Use(Operand::Constant(c)), | |
370 | )) => c.literal.try_eval_usize(self.tcx, self.param_env), | |
371 | _ => None, | |
372 | } | |
373 | } else { | |
374 | None | |
375 | } | |
376 | } else { | |
377 | None | |
378 | }; | |
17df50a5 XL |
379 | if let Some(idx) = val { |
380 | // Determine the type of the thing we are indexing. | |
381 | let ty = place_base.ty(self.body, self.tcx).ty; | |
382 | match ty.kind() { | |
383 | ty::Array(_, len) => { | |
384 | // It's an array; determine its length. | |
385 | if let Some(len) = len.try_eval_usize(self.tcx, self.param_env) | |
386 | { | |
387 | // If the index is in-bounds, go ahead. | |
388 | if idx < len { | |
389 | promotable = true; | |
5869c6ff XL |
390 | } |
391 | } | |
5869c6ff | 392 | } |
17df50a5 | 393 | _ => {} |
5869c6ff XL |
394 | } |
395 | } | |
17df50a5 XL |
396 | if !promotable { |
397 | return Err(Unpromotable); | |
398 | } | |
399 | ||
e74abb32 XL |
400 | self.validate_local(local)?; |
401 | } | |
402 | ||
403 | ProjectionElem::Field(..) => { | |
5869c6ff | 404 | let base_ty = place_base.ty(self.body, self.tcx).ty; |
17df50a5 | 405 | if base_ty.is_union() { |
29967ef6 | 406 | // No promotion of union field accesses. |
17df50a5 | 407 | return Err(Unpromotable); |
e74abb32 XL |
408 | } |
409 | } | |
410 | } | |
411 | ||
5869c6ff | 412 | self.validate_place(place_base) |
e74abb32 XL |
413 | } |
414 | } | |
415 | } | |
416 | ||
417 | fn validate_operand(&self, operand: &Operand<'tcx>) -> Result<(), Unpromotable> { | |
418 | match operand { | |
dfeec247 | 419 | Operand::Copy(place) | Operand::Move(place) => self.validate_place(place.as_ref()), |
e74abb32 | 420 | |
60c5eb7d XL |
421 | // The qualifs for a constant (e.g. `HasMutInterior`) are checked in |
422 | // `validate_rvalue` upon access. | |
423 | Operand::Constant(c) => { | |
424 | if let Some(def_id) = c.check_static_ptr(self.tcx) { | |
425 | // Only allow statics (not consts) to refer to other statics. | |
426 | // FIXME(eddyb) does this matter at all for promotion? | |
1b1a35ee XL |
427 | // FIXME(RalfJung) it makes little sense to not promote this in `fn`/`const fn`, |
428 | // and in `const` this cannot occur anyway. The only concern is that we might | |
429 | // promote even `let x = &STATIC` which would be useless, but this applies to | |
430 | // promotion inside statics as well. | |
f9f354fc | 431 | let is_static = matches!(self.const_kind, Some(hir::ConstContext::Static(_))); |
60c5eb7d XL |
432 | if !is_static { |
433 | return Err(Unpromotable); | |
434 | } | |
435 | ||
f9f354fc | 436 | let is_thread_local = self.tcx.is_thread_local_static(def_id); |
60c5eb7d XL |
437 | if is_thread_local { |
438 | return Err(Unpromotable); | |
e74abb32 XL |
439 | } |
440 | } | |
441 | ||
442 | Ok(()) | |
dfeec247 | 443 | } |
e74abb32 XL |
444 | } |
445 | } | |
446 | ||
5869c6ff XL |
447 | fn validate_ref(&self, kind: BorrowKind, place: &Place<'tcx>) -> Result<(), Unpromotable> { |
448 | match kind { | |
449 | // Reject these borrow types just to be safe. | |
450 | // FIXME(RalfJung): could we allow them? Should we? No point in it until we have a usecase. | |
451 | BorrowKind::Shallow | BorrowKind::Unique => return Err(Unpromotable), | |
452 | ||
453 | BorrowKind::Shared => { | |
454 | let has_mut_interior = self.qualif_local::<qualifs::HasMutInterior>(place.local); | |
455 | if has_mut_interior { | |
1b1a35ee | 456 | return Err(Unpromotable); |
e74abb32 XL |
457 | } |
458 | } | |
459 | ||
5869c6ff XL |
460 | BorrowKind::Mut { .. } => { |
461 | let ty = place.ty(self.body, self.tcx).ty; | |
462 | ||
463 | // In theory, any zero-sized value could be borrowed | |
464 | // mutably without consequences. However, only &mut [] | |
465 | // is allowed right now. | |
466 | if let ty::Array(_, len) = ty.kind() { | |
467 | match len.try_eval_usize(self.tcx, self.param_env) { | |
468 | Some(0) => {} | |
469 | _ => return Err(Unpromotable), | |
470 | } | |
471 | } else { | |
e74abb32 XL |
472 | return Err(Unpromotable); |
473 | } | |
474 | } | |
e74abb32 XL |
475 | } |
476 | ||
5869c6ff XL |
477 | Ok(()) |
478 | } | |
479 | ||
480 | fn validate_rvalue(&self, rvalue: &Rvalue<'tcx>) -> Result<(), Unpromotable> { | |
e74abb32 | 481 | match rvalue { |
5869c6ff XL |
482 | Rvalue::Use(operand) | Rvalue::Repeat(operand, _) => { |
483 | self.validate_operand(operand)?; | |
484 | } | |
485 | ||
486 | Rvalue::Discriminant(place) | Rvalue::Len(place) => { | |
487 | self.validate_place(place.as_ref())? | |
488 | } | |
489 | ||
490 | Rvalue::ThreadLocalRef(_) => return Err(Unpromotable), | |
491 | ||
492 | Rvalue::Cast(kind, operand, cast_ty) => { | |
493 | if matches!(kind, CastKind::Misc) { | |
494 | let operand_ty = operand.ty(self.body, self.tcx); | |
495 | let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast"); | |
496 | let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast"); | |
497 | if let (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) = (cast_in, cast_out) { | |
498 | // ptr-to-int casts are not possible in consts and thus not promotable | |
499 | return Err(Unpromotable); | |
500 | } | |
501 | // int-to-ptr casts are fine, they just use the integer value at pointer type. | |
502 | } | |
503 | ||
504 | self.validate_operand(operand)?; | |
505 | } | |
506 | ||
507 | Rvalue::NullaryOp(op, _) => match op { | |
508 | NullOp::Box => return Err(Unpromotable), | |
509 | NullOp::SizeOf => {} | |
c295e0f8 | 510 | NullOp::AlignOf => {} |
5869c6ff | 511 | }, |
f9f354fc | 512 | |
c295e0f8 XL |
513 | Rvalue::ShallowInitBox(_, _) => return Err(Unpromotable), |
514 | ||
5869c6ff XL |
515 | Rvalue::UnaryOp(op, operand) => { |
516 | match op { | |
517 | // These operations can never fail. | |
518 | UnOp::Neg | UnOp::Not => {} | |
519 | } | |
e74abb32 | 520 | |
5869c6ff XL |
521 | self.validate_operand(operand)?; |
522 | } | |
523 | ||
6a06907d | 524 | Rvalue::BinaryOp(op, box (lhs, rhs)) | Rvalue::CheckedBinaryOp(op, box (lhs, rhs)) => { |
5869c6ff XL |
525 | let op = *op; |
526 | let lhs_ty = lhs.ty(self.body, self.tcx); | |
527 | ||
528 | if let ty::RawPtr(_) | ty::FnPtr(..) = lhs_ty.kind() { | |
529 | // Raw and fn pointer operations are not allowed inside consts and thus not promotable. | |
530 | assert!(matches!( | |
531 | op, | |
532 | BinOp::Eq | |
533 | | BinOp::Ne | |
534 | | BinOp::Le | |
535 | | BinOp::Lt | |
536 | | BinOp::Ge | |
537 | | BinOp::Gt | |
538 | | BinOp::Offset | |
539 | )); | |
540 | return Err(Unpromotable); | |
541 | } | |
e74abb32 | 542 | |
5869c6ff XL |
543 | match op { |
544 | BinOp::Div | BinOp::Rem => { | |
17df50a5 | 545 | if lhs_ty.is_integral() { |
5869c6ff XL |
546 | // Integer division: the RHS must be a non-zero const. |
547 | let const_val = match rhs { | |
548 | Operand::Constant(c) => { | |
549 | c.literal.try_eval_bits(self.tcx, self.param_env, lhs_ty) | |
550 | } | |
551 | _ => None, | |
552 | }; | |
553 | match const_val { | |
554 | Some(x) if x != 0 => {} // okay | |
555 | _ => return Err(Unpromotable), // value not known or 0 -- not okay | |
556 | } | |
557 | } | |
558 | } | |
559 | // The remaining operations can never fail. | |
560 | BinOp::Eq | |
561 | | BinOp::Ne | |
562 | | BinOp::Le | |
563 | | BinOp::Lt | |
564 | | BinOp::Ge | |
565 | | BinOp::Gt | |
566 | | BinOp::Offset | |
567 | | BinOp::Add | |
568 | | BinOp::Sub | |
569 | | BinOp::Mul | |
570 | | BinOp::BitXor | |
571 | | BinOp::BitAnd | |
572 | | BinOp::BitOr | |
573 | | BinOp::Shl | |
574 | | BinOp::Shr => {} | |
575 | } | |
e74abb32 | 576 | |
e74abb32 | 577 | self.validate_operand(lhs)?; |
5869c6ff | 578 | self.validate_operand(rhs)?; |
e74abb32 XL |
579 | } |
580 | ||
dfeec247 | 581 | Rvalue::AddressOf(_, place) => { |
1b1a35ee XL |
582 | // We accept `&raw *`, i.e., raw reborrows -- creating a raw pointer is |
583 | // no problem, only using it is. | |
5869c6ff XL |
584 | if let Some((place_base, ProjectionElem::Deref)) = place.as_ref().last_projection() |
585 | { | |
586 | let base_ty = place_base.ty(self.body, self.tcx).ty; | |
1b1a35ee | 587 | if let ty::Ref(..) = base_ty.kind() { |
5869c6ff | 588 | return self.validate_place(place_base); |
dfeec247 XL |
589 | } |
590 | } | |
5869c6ff | 591 | return Err(Unpromotable); |
dfeec247 XL |
592 | } |
593 | ||
e74abb32 | 594 | Rvalue::Ref(_, kind, place) => { |
e74abb32 | 595 | // Special-case reborrows to be more like a copy of the reference. |
5869c6ff XL |
596 | let mut place_simplified = place.as_ref(); |
597 | if let Some((place_base, ProjectionElem::Deref)) = | |
598 | place_simplified.last_projection() | |
599 | { | |
600 | let base_ty = place_base.ty(self.body, self.tcx).ty; | |
1b1a35ee | 601 | if let ty::Ref(..) = base_ty.kind() { |
5869c6ff | 602 | place_simplified = place_base; |
e74abb32 XL |
603 | } |
604 | } | |
605 | ||
5869c6ff | 606 | self.validate_place(place_simplified)?; |
e74abb32 | 607 | |
5869c6ff XL |
608 | // Check that the reference is fine (using the original place!). |
609 | // (Needs to come after `validate_place` to avoid ICEs.) | |
610 | self.validate_ref(*kind, place)?; | |
e74abb32 XL |
611 | } |
612 | ||
5869c6ff | 613 | Rvalue::Aggregate(_, operands) => { |
e74abb32 XL |
614 | for o in operands { |
615 | self.validate_operand(o)?; | |
616 | } | |
e74abb32 XL |
617 | } |
618 | } | |
5869c6ff XL |
619 | |
620 | Ok(()) | |
e74abb32 XL |
621 | } |
622 | ||
623 | fn validate_call( | |
624 | &self, | |
625 | callee: &Operand<'tcx>, | |
626 | args: &[Operand<'tcx>], | |
627 | ) -> Result<(), Unpromotable> { | |
f9f354fc | 628 | let fn_ty = callee.ty(self.body, self.tcx); |
e74abb32 | 629 | |
17df50a5 | 630 | // Inside const/static items, we promote all (eligible) function calls. |
29967ef6 | 631 | // Everywhere else, we require `#[rustc_promotable]` on the callee. |
17df50a5 XL |
632 | let promote_all_const_fn = matches!( |
633 | self.const_kind, | |
634 | Some(hir::ConstContext::Static(_) | hir::ConstContext::Const) | |
635 | ); | |
29967ef6 | 636 | if !promote_all_const_fn { |
1b1a35ee | 637 | if let ty::FnDef(def_id, _) = *fn_ty.kind() { |
e74abb32 XL |
638 | // Never promote runtime `const fn` calls of |
639 | // functions without `#[rustc_promotable]`. | |
640 | if !self.tcx.is_promotable_const_fn(def_id) { | |
641 | return Err(Unpromotable); | |
642 | } | |
643 | } | |
644 | } | |
645 | ||
1b1a35ee | 646 | let is_const_fn = match *fn_ty.kind() { |
3c0e092e | 647 | ty::FnDef(def_id, _) => self.tcx.is_const_fn_raw(def_id), |
e74abb32 XL |
648 | _ => false, |
649 | }; | |
650 | if !is_const_fn { | |
651 | return Err(Unpromotable); | |
652 | } | |
653 | ||
654 | self.validate_operand(callee)?; | |
655 | for arg in args { | |
656 | self.validate_operand(arg)?; | |
657 | } | |
658 | ||
659 | Ok(()) | |
660 | } | |
661 | } | |
662 | ||
663 | // FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`. | |
664 | pub fn validate_candidates( | |
f9f354fc | 665 | ccx: &ConstCx<'_, '_>, |
e74abb32 XL |
666 | temps: &IndexVec<Local, TempState>, |
667 | candidates: &[Candidate], | |
668 | ) -> Vec<Candidate> { | |
17df50a5 | 669 | let validator = Validator { ccx, temps }; |
e74abb32 | 670 | |
dfeec247 XL |
671 | candidates |
672 | .iter() | |
673 | .copied() | |
17df50a5 | 674 | .filter(|&candidate| validator.validate_candidate(candidate).is_ok()) |
dfeec247 | 675 | .collect() |
a7813a04 XL |
676 | } |
677 | ||
dc9dc135 XL |
678 | struct Promoter<'a, 'tcx> { |
679 | tcx: TyCtxt<'tcx>, | |
f9f354fc XL |
680 | source: &'a mut Body<'tcx>, |
681 | promoted: Body<'tcx>, | |
c30ab7b3 | 682 | temps: &'a mut IndexVec<Local, TempState>, |
dfeec247 | 683 | extra_statements: &'a mut Vec<(Location, Statement<'tcx>)>, |
a7813a04 XL |
684 | |
685 | /// If true, all nested temps are also kept in the | |
686 | /// source MIR, not moved to the promoted MIR. | |
dc9dc135 | 687 | keep_original: bool, |
a7813a04 XL |
688 | } |
689 | ||
690 | impl<'a, 'tcx> Promoter<'a, 'tcx> { | |
691 | fn new_block(&mut self) -> BasicBlock { | |
3157f602 XL |
692 | let span = self.promoted.span; |
693 | self.promoted.basic_blocks_mut().push(BasicBlockData { | |
a7813a04 XL |
694 | statements: vec![], |
695 | terminator: Some(Terminator { | |
f9f354fc | 696 | source_info: SourceInfo::outermost(span), |
dfeec247 | 697 | kind: TerminatorKind::Return, |
a7813a04 | 698 | }), |
dfeec247 | 699 | is_cleanup: false, |
3157f602 | 700 | }) |
a7813a04 XL |
701 | } |
702 | ||
c30ab7b3 | 703 | fn assign(&mut self, dest: Local, rvalue: Rvalue<'tcx>, span: Span) { |
3157f602 XL |
704 | let last = self.promoted.basic_blocks().last().unwrap(); |
705 | let data = &mut self.promoted[last]; | |
a7813a04 | 706 | data.statements.push(Statement { |
f9f354fc | 707 | source_info: SourceInfo::outermost(span), |
94222f64 | 708 | kind: StatementKind::Assign(Box::new((Place::from(dest), rvalue))), |
a7813a04 XL |
709 | }); |
710 | } | |
711 | ||
e74abb32 XL |
712 | fn is_temp_kind(&self, local: Local) -> bool { |
713 | self.source.local_kind(local) == LocalKind::Temp | |
714 | } | |
715 | ||
9fa01778 | 716 | /// Copies the initialization of this temp to the |
a7813a04 | 717 | /// promoted MIR, recursing through temps. |
c30ab7b3 | 718 | fn promote_temp(&mut self, temp: Local) -> Local { |
a7813a04 | 719 | let old_keep_original = self.keep_original; |
476ff2be SL |
720 | let loc = match self.temps[temp] { |
721 | TempState::Defined { location, uses } if uses > 0 => { | |
a7813a04 XL |
722 | if uses > 1 { |
723 | self.keep_original = true; | |
724 | } | |
476ff2be | 725 | location |
a7813a04 | 726 | } |
dfeec247 XL |
727 | state => { |
728 | span_bug!(self.promoted.span, "{:?} not promotable: {:?}", temp, state); | |
a7813a04 XL |
729 | } |
730 | }; | |
731 | if !self.keep_original { | |
3157f602 | 732 | self.temps[temp] = TempState::PromotedOut; |
a7813a04 XL |
733 | } |
734 | ||
e74abb32 | 735 | let num_stmts = self.source[loc.block].statements.len(); |
f9f354fc | 736 | let new_temp = self.promoted.local_decls.push(LocalDecl::new( |
dfeec247 XL |
737 | self.source.local_decls[temp].ty, |
738 | self.source.local_decls[temp].source_info.span, | |
739 | )); | |
476ff2be | 740 | |
dfeec247 | 741 | debug!("promote({:?} @ {:?}/{:?}, {:?})", temp, loc, num_stmts, self.keep_original); |
a7813a04 XL |
742 | |
743 | // First, take the Rvalue or Call out of the source MIR, | |
744 | // or duplicate it, depending on keep_original. | |
e74abb32 | 745 | if loc.statement_index < num_stmts { |
e1599b0c | 746 | let (mut rvalue, source_info) = { |
476ff2be SL |
747 | let statement = &mut self.source[loc.block].statements[loc.statement_index]; |
748 | let rhs = match statement.kind { | |
dfeec247 | 749 | StatementKind::Assign(box (_, ref mut rhs)) => rhs, |
476ff2be | 750 | _ => { |
dfeec247 XL |
751 | span_bug!( |
752 | statement.source_info.span, | |
753 | "{:?} is not an assignment", | |
754 | statement | |
755 | ); | |
476ff2be SL |
756 | } |
757 | }; | |
758 | ||
dfeec247 XL |
759 | ( |
760 | if self.keep_original { | |
761 | rhs.clone() | |
762 | } else { | |
94222f64 | 763 | let unit = Rvalue::Use(Operand::Constant(Box::new(Constant { |
ba9703b0 XL |
764 | span: statement.source_info.span, |
765 | user_ty: None, | |
6a06907d | 766 | literal: ty::Const::zero_sized(self.tcx, self.tcx.types.unit).into(), |
94222f64 | 767 | }))); |
dfeec247 XL |
768 | mem::replace(rhs, unit) |
769 | }, | |
770 | statement.source_info, | |
771 | ) | |
5bcae85e | 772 | }; |
476ff2be SL |
773 | |
774 | self.visit_rvalue(&mut rvalue, loc); | |
775 | self.assign(new_temp, rvalue, source_info.span); | |
a7813a04 | 776 | } else { |
476ff2be SL |
777 | let terminator = if self.keep_original { |
778 | self.source[loc.block].terminator().clone() | |
779 | } else { | |
780 | let terminator = self.source[loc.block].terminator_mut(); | |
781 | let target = match terminator.kind { | |
782 | TerminatorKind::Call { destination: Some((_, target)), .. } => target, | |
783 | ref kind => { | |
784 | span_bug!(terminator.source_info.span, "{:?} not promotable", kind); | |
785 | } | |
786 | }; | |
787 | Terminator { | |
788 | source_info: terminator.source_info, | |
dfeec247 | 789 | kind: mem::replace(&mut terminator.kind, TerminatorKind::Goto { target }), |
a7813a04 XL |
790 | } |
791 | }; | |
a7813a04 | 792 | |
476ff2be | 793 | match terminator.kind { |
f035d41b | 794 | TerminatorKind::Call { mut func, mut args, from_hir_call, fn_span, .. } => { |
476ff2be SL |
795 | self.visit_operand(&mut func, loc); |
796 | for arg in &mut args { | |
797 | self.visit_operand(arg, loc); | |
798 | } | |
a7813a04 | 799 | |
476ff2be SL |
800 | let last = self.promoted.basic_blocks().last().unwrap(); |
801 | let new_target = self.new_block(); | |
a7813a04 | 802 | |
476ff2be SL |
803 | *self.promoted[last].terminator_mut() = Terminator { |
804 | kind: TerminatorKind::Call { | |
3b2f2976 XL |
805 | func, |
806 | args, | |
476ff2be | 807 | cleanup: None, |
dfeec247 | 808 | destination: Some((Place::from(new_temp), new_target)), |
0bf4aa26 | 809 | from_hir_call, |
f035d41b | 810 | fn_span, |
476ff2be | 811 | }, |
29967ef6 | 812 | source_info: SourceInfo::outermost(terminator.source_info.span), |
476ff2be SL |
813 | ..terminator |
814 | }; | |
a7813a04 | 815 | } |
476ff2be SL |
816 | ref kind => { |
817 | span_bug!(terminator.source_info.span, "{:?} not promotable", kind); | |
818 | } | |
819 | }; | |
820 | }; | |
a7813a04 | 821 | |
a7813a04 | 822 | self.keep_original = old_keep_original; |
3157f602 | 823 | new_temp |
a7813a04 XL |
824 | } |
825 | ||
3c0e092e | 826 | fn promote_candidate(mut self, candidate: Candidate, next_promoted_id: usize) -> Body<'tcx> { |
29967ef6 | 827 | let def = self.source.source.with_opt_param(); |
dfeec247 | 828 | let mut rvalue = { |
94b46f34 | 829 | let promoted = &mut self.promoted; |
e1599b0c XL |
830 | let promoted_id = Promoted::new(next_promoted_id); |
831 | let tcx = self.tcx; | |
dfeec247 | 832 | let mut promoted_operand = |ty, span| { |
94b46f34 | 833 | promoted.span = span; |
f9f354fc | 834 | promoted.local_decls[RETURN_PLACE] = LocalDecl::new(ty, span); |
dfeec247 XL |
835 | |
836 | Operand::Constant(Box::new(Constant { | |
837 | span, | |
838 | user_ty: None, | |
6a06907d XL |
839 | literal: tcx |
840 | .mk_const(ty::Const { | |
841 | ty, | |
cdc7bbd5 | 842 | val: ty::ConstKind::Unevaluated(ty::Unevaluated { |
6a06907d | 843 | def, |
94222f64 XL |
844 | substs_: Some(InternalSubsts::for_item( |
845 | tcx, | |
846 | def.did, | |
847 | |param, _| { | |
848 | if let ty::GenericParamDefKind::Lifetime = param.kind { | |
849 | tcx.lifetimes.re_erased.into() | |
850 | } else { | |
851 | tcx.mk_param_from_def(param) | |
852 | } | |
853 | }, | |
854 | )), | |
cdc7bbd5 XL |
855 | promoted: Some(promoted_id), |
856 | }), | |
6a06907d XL |
857 | }) |
858 | .into(), | |
dfeec247 | 859 | })) |
94b46f34 XL |
860 | }; |
861 | let (blocks, local_decls) = self.source.basic_blocks_and_local_decls_mut(); | |
3c0e092e XL |
862 | let loc = candidate.location; |
863 | let statement = &mut blocks[loc.block].statements[loc.statement_index]; | |
864 | match statement.kind { | |
865 | StatementKind::Assign(box ( | |
866 | _, | |
867 | Rvalue::Ref(ref mut region, borrow_kind, ref mut place), | |
868 | )) => { | |
869 | // Use the underlying local for this (necessarily interior) borrow. | |
870 | let ty = local_decls.local_decls()[place.local].ty; | |
871 | let span = statement.source_info.span; | |
872 | ||
873 | let ref_ty = tcx.mk_ref( | |
874 | tcx.lifetimes.re_erased, | |
875 | ty::TypeAndMut { ty, mutbl: borrow_kind.to_mutbl_lossy() }, | |
876 | ); | |
877 | ||
878 | *region = tcx.lifetimes.re_erased; | |
879 | ||
880 | let mut projection = vec![PlaceElem::Deref]; | |
881 | projection.extend(place.projection); | |
882 | place.projection = tcx.intern_place_elems(&projection); | |
883 | ||
884 | // Create a temp to hold the promoted reference. | |
885 | // This is because `*r` requires `r` to be a local, | |
886 | // otherwise we would use the `promoted` directly. | |
887 | let mut promoted_ref = LocalDecl::new(ref_ty, span); | |
888 | promoted_ref.source_info = statement.source_info; | |
889 | let promoted_ref = local_decls.push(promoted_ref); | |
890 | assert_eq!(self.temps.push(TempState::Unpromotable), promoted_ref); | |
891 | ||
892 | let promoted_ref_statement = Statement { | |
893 | source_info: statement.source_info, | |
894 | kind: StatementKind::Assign(Box::new(( | |
895 | Place::from(promoted_ref), | |
896 | Rvalue::Use(promoted_operand(ref_ty, span)), | |
897 | ))), | |
898 | }; | |
899 | self.extra_statements.push((loc, promoted_ref_statement)); | |
900 | ||
901 | Rvalue::Ref( | |
902 | tcx.lifetimes.re_erased, | |
903 | borrow_kind, | |
904 | Place { | |
905 | local: mem::replace(&mut place.local, promoted_ref), | |
906 | projection: List::empty(), | |
907 | }, | |
908 | ) | |
a7813a04 | 909 | } |
3c0e092e | 910 | _ => bug!(), |
a7813a04 XL |
911 | } |
912 | }; | |
94b46f34 XL |
913 | |
914 | assert_eq!(self.new_block(), START_BLOCK); | |
dfeec247 XL |
915 | self.visit_rvalue( |
916 | &mut rvalue, | |
917 | Location { block: BasicBlock::new(0), statement_index: usize::MAX }, | |
918 | ); | |
c30ab7b3 | 919 | |
94b46f34 | 920 | let span = self.promoted.span; |
dfeec247 | 921 | self.assign(RETURN_PLACE, rvalue, span); |
3c0e092e | 922 | self.promoted |
a7813a04 XL |
923 | } |
924 | } | |
925 | ||
926 | /// Replaces all temporaries with their promoted counterparts. | |
927 | impl<'a, 'tcx> MutVisitor<'tcx> for Promoter<'a, 'tcx> { | |
e74abb32 XL |
928 | fn tcx(&self) -> TyCtxt<'tcx> { |
929 | self.tcx | |
930 | } | |
931 | ||
dfeec247 | 932 | fn visit_local(&mut self, local: &mut Local, _: PlaceContext, _: Location) { |
e74abb32 | 933 | if self.is_temp_kind(*local) { |
ea8adc8c | 934 | *local = self.promote_temp(*local); |
a7813a04 | 935 | } |
a7813a04 XL |
936 | } |
937 | } | |
938 | ||
dc9dc135 | 939 | pub fn promote_candidates<'tcx>( |
f9f354fc | 940 | body: &mut Body<'tcx>, |
dc9dc135 XL |
941 | tcx: TyCtxt<'tcx>, |
942 | mut temps: IndexVec<Local, TempState>, | |
943 | candidates: Vec<Candidate>, | |
f9f354fc | 944 | ) -> IndexVec<Promoted, Body<'tcx>> { |
a7813a04 | 945 | // Visit candidates in reverse, in case they're nested. |
476ff2be | 946 | debug!("promote_candidates({:?})", candidates); |
94b46f34 | 947 | |
e1599b0c XL |
948 | let mut promotions = IndexVec::new(); |
949 | ||
dfeec247 | 950 | let mut extra_statements = vec![]; |
a7813a04 | 951 | for candidate in candidates.into_iter().rev() { |
3c0e092e XL |
952 | let Location { block, statement_index } = candidate.location; |
953 | if let StatementKind::Assign(box (place, _)) = &body[block].statements[statement_index].kind | |
954 | { | |
955 | if let Some(local) = place.as_local() { | |
956 | if temps[local] == TempState::PromotedOut { | |
957 | // Already promoted. | |
958 | continue; | |
a7813a04 | 959 | } |
a7813a04 | 960 | } |
94b46f34 XL |
961 | } |
962 | ||
dc9dc135 | 963 | // Declare return place local so that `mir::Body::new` doesn't complain. |
f9f354fc | 964 | let initial_locals = iter::once(LocalDecl::new(tcx.types.never, body.span)).collect(); |
dfeec247 | 965 | |
3c0e092e | 966 | let mut scope = body.source_scopes[body.source_info(candidate.location).scope].clone(); |
29967ef6 XL |
967 | scope.parent_scope = None; |
968 | ||
969 | let promoted = Body::new( | |
94222f64 | 970 | tcx, |
29967ef6 | 971 | body.source, // `promoted` gets filled in below |
dfeec247 | 972 | IndexVec::new(), |
29967ef6 | 973 | IndexVec::from_elem_n(scope, 1), |
dfeec247 XL |
974 | initial_locals, |
975 | IndexVec::new(), | |
976 | 0, | |
977 | vec![], | |
978 | body.span, | |
6a06907d | 979 | body.generator_kind(), |
dfeec247 | 980 | ); |
c30ab7b3 | 981 | |
8faf50e0 | 982 | let promoter = Promoter { |
f9f354fc | 983 | promoted, |
94b46f34 | 984 | tcx, |
dc9dc135 | 985 | source: body, |
a7813a04 | 986 | temps: &mut temps, |
dfeec247 XL |
987 | extra_statements: &mut extra_statements, |
988 | keep_original: false, | |
a7813a04 | 989 | }; |
e1599b0c | 990 | |
3c0e092e XL |
991 | let mut promoted = promoter.promote_candidate(candidate, promotions.len()); |
992 | promoted.source.promoted = Some(promotions.next_index()); | |
993 | promotions.push(promoted); | |
a7813a04 XL |
994 | } |
995 | ||
dfeec247 XL |
996 | // Insert each of `extra_statements` before its indicated location, which |
997 | // has to be done in reverse location order, to not invalidate the rest. | |
998 | extra_statements.sort_by_key(|&(loc, _)| cmp::Reverse(loc)); | |
999 | for (loc, statement) in extra_statements { | |
1000 | body[loc.block].statements.insert(loc.statement_index, statement); | |
1001 | } | |
1002 | ||
a7813a04 | 1003 | // Eliminate assignments to, and drops of promoted temps. |
c30ab7b3 | 1004 | let promoted = |index: Local| temps[index] == TempState::PromotedOut; |
dc9dc135 | 1005 | for block in body.basic_blocks_mut() { |
dfeec247 XL |
1006 | block.statements.retain(|statement| match &statement.kind { |
1007 | StatementKind::Assign(box (place, _)) => { | |
1008 | if let Some(index) = place.as_local() { | |
1009 | !promoted(index) | |
1010 | } else { | |
1011 | true | |
a7813a04 | 1012 | } |
a7813a04 | 1013 | } |
dfeec247 XL |
1014 | StatementKind::StorageLive(index) | StatementKind::StorageDead(index) => { |
1015 | !promoted(*index) | |
1016 | } | |
1017 | _ => true, | |
a7813a04 XL |
1018 | }); |
1019 | let terminator = block.terminator_mut(); | |
f035d41b | 1020 | if let TerminatorKind::Drop { place, target, .. } = &terminator.kind { |
ba9703b0 XL |
1021 | if let Some(index) = place.as_local() { |
1022 | if promoted(index) { | |
1023 | terminator.kind = TerminatorKind::Goto { target: *target }; | |
a7813a04 XL |
1024 | } |
1025 | } | |
a7813a04 XL |
1026 | } |
1027 | } | |
e1599b0c XL |
1028 | |
1029 | promotions | |
a7813a04 | 1030 | } |
6a06907d XL |
1031 | |
1032 | /// This function returns `true` if the function being called in the array | |
1033 | /// repeat expression is a `const` function. | |
c295e0f8 | 1034 | pub fn is_const_fn_in_array_repeat_expression<'tcx>( |
6a06907d XL |
1035 | ccx: &ConstCx<'_, 'tcx>, |
1036 | place: &Place<'tcx>, | |
1037 | body: &Body<'tcx>, | |
1038 | ) -> bool { | |
1039 | match place.as_local() { | |
1040 | // rule out cases such as: `let my_var = some_fn(); [my_var; N]` | |
1041 | Some(local) if body.local_decls[local].is_user_variable() => return false, | |
1042 | None => return false, | |
1043 | _ => {} | |
1044 | } | |
1045 | ||
1046 | for block in body.basic_blocks() { | |
1047 | if let Some(Terminator { kind: TerminatorKind::Call { func, destination, .. }, .. }) = | |
1048 | &block.terminator | |
1049 | { | |
1050 | if let Operand::Constant(box Constant { literal, .. }) = func { | |
1051 | if let ty::FnDef(def_id, _) = *literal.ty().kind() { | |
1052 | if let Some((destination_place, _)) = destination { | |
1053 | if destination_place == place { | |
c295e0f8 | 1054 | if ccx.tcx.is_const_fn(def_id) { |
6a06907d XL |
1055 | return true; |
1056 | } | |
1057 | } | |
1058 | } | |
1059 | } | |
1060 | } | |
1061 | } | |
1062 | } | |
1063 | ||
1064 | false | |
1065 | } |