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