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