]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_const_eval/src/transform/check_consts/check.rs
Auto merge of #90348 - Amanieu:asm_feature_gates, r=joshtriplett
[rust.git] / compiler / rustc_const_eval / src / transform / check_consts / check.rs
1 //! The `Visitor` responsible for actually checking a `mir::Body` for invalid operations.
2
3 use rustc_errors::{Applicability, Diagnostic, ErrorReported};
4 use rustc_hir::def_id::DefId;
5 use rustc_hir::{self as hir, HirId, LangItem};
6 use rustc_index::bit_set::BitSet;
7 use rustc_infer::infer::TyCtxtInferExt;
8 use rustc_infer::traits::{ImplSource, Obligation, ObligationCause};
9 use rustc_middle::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor};
10 use rustc_middle::mir::*;
11 use rustc_middle::ty::cast::CastTy;
12 use rustc_middle::ty::subst::{GenericArgKind, InternalSubsts};
13 use rustc_middle::ty::{self, adjustment::PointerCast, Instance, InstanceDef, Ty, TyCtxt};
14 use rustc_middle::ty::{Binder, TraitPredicate, TraitRef};
15 use rustc_mir_dataflow::{self, Analysis};
16 use rustc_span::{sym, Span, Symbol};
17 use rustc_trait_selection::traits::error_reporting::InferCtxtExt;
18 use rustc_trait_selection::traits::{self, SelectionContext, TraitEngine};
19
20 use std::mem;
21 use std::ops::Deref;
22
23 use super::ops::{self, NonConstOp, Status};
24 use super::qualifs::{self, CustomEq, HasMutInterior, NeedsDrop, NeedsNonConstDrop};
25 use super::resolver::FlowSensitiveAnalysis;
26 use super::{ConstCx, Qualif};
27 use crate::const_eval::is_unstable_const_fn;
28
29 type QualifResults<'mir, 'tcx, Q> =
30     rustc_mir_dataflow::ResultsCursor<'mir, 'tcx, FlowSensitiveAnalysis<'mir, 'mir, 'tcx, Q>>;
31
32 #[derive(Default)]
33 pub struct Qualifs<'mir, 'tcx> {
34     has_mut_interior: Option<QualifResults<'mir, 'tcx, HasMutInterior>>,
35     needs_drop: Option<QualifResults<'mir, 'tcx, NeedsDrop>>,
36     needs_non_const_drop: Option<QualifResults<'mir, 'tcx, NeedsNonConstDrop>>,
37 }
38
39 impl Qualifs<'mir, 'tcx> {
40     /// Returns `true` if `local` is `NeedsDrop` at the given `Location`.
41     ///
42     /// Only updates the cursor if absolutely necessary
43     pub fn needs_drop(
44         &mut self,
45         ccx: &'mir ConstCx<'mir, 'tcx>,
46         local: Local,
47         location: Location,
48     ) -> bool {
49         let ty = ccx.body.local_decls[local].ty;
50         if !NeedsDrop::in_any_value_of_ty(ccx, ty) {
51             return false;
52         }
53
54         let needs_drop = self.needs_drop.get_or_insert_with(|| {
55             let ConstCx { tcx, body, .. } = *ccx;
56
57             FlowSensitiveAnalysis::new(NeedsDrop, ccx)
58                 .into_engine(tcx, &body)
59                 .iterate_to_fixpoint()
60                 .into_results_cursor(&body)
61         });
62
63         needs_drop.seek_before_primary_effect(location);
64         needs_drop.get().contains(local)
65     }
66
67     /// Returns `true` if `local` is `NeedsNonConstDrop` at the given `Location`.
68     ///
69     /// Only updates the cursor if absolutely necessary
70     pub fn needs_non_const_drop(
71         &mut self,
72         ccx: &'mir ConstCx<'mir, 'tcx>,
73         local: Local,
74         location: Location,
75     ) -> bool {
76         let ty = ccx.body.local_decls[local].ty;
77         if !NeedsNonConstDrop::in_any_value_of_ty(ccx, ty) {
78             return false;
79         }
80
81         let needs_non_const_drop = self.needs_non_const_drop.get_or_insert_with(|| {
82             let ConstCx { tcx, body, .. } = *ccx;
83
84             FlowSensitiveAnalysis::new(NeedsNonConstDrop, ccx)
85                 .into_engine(tcx, &body)
86                 .iterate_to_fixpoint()
87                 .into_results_cursor(&body)
88         });
89
90         needs_non_const_drop.seek_before_primary_effect(location);
91         needs_non_const_drop.get().contains(local)
92     }
93
94     /// Returns `true` if `local` is `HasMutInterior` at the given `Location`.
95     ///
96     /// Only updates the cursor if absolutely necessary.
97     pub fn has_mut_interior(
98         &mut self,
99         ccx: &'mir ConstCx<'mir, 'tcx>,
100         local: Local,
101         location: Location,
102     ) -> bool {
103         let ty = ccx.body.local_decls[local].ty;
104         if !HasMutInterior::in_any_value_of_ty(ccx, ty) {
105             return false;
106         }
107
108         let has_mut_interior = self.has_mut_interior.get_or_insert_with(|| {
109             let ConstCx { tcx, body, .. } = *ccx;
110
111             FlowSensitiveAnalysis::new(HasMutInterior, ccx)
112                 .into_engine(tcx, &body)
113                 .iterate_to_fixpoint()
114                 .into_results_cursor(&body)
115         });
116
117         has_mut_interior.seek_before_primary_effect(location);
118         has_mut_interior.get().contains(local)
119     }
120
121     fn in_return_place(
122         &mut self,
123         ccx: &'mir ConstCx<'mir, 'tcx>,
124         error_occured: Option<ErrorReported>,
125     ) -> ConstQualifs {
126         // Find the `Return` terminator if one exists.
127         //
128         // If no `Return` terminator exists, this MIR is divergent. Just return the conservative
129         // qualifs for the return type.
130         let return_block = ccx
131             .body
132             .basic_blocks()
133             .iter_enumerated()
134             .find(|(_, block)| matches!(block.terminator().kind, TerminatorKind::Return))
135             .map(|(bb, _)| bb);
136
137         let return_block = match return_block {
138             None => return qualifs::in_any_value_of_ty(ccx, ccx.body.return_ty(), error_occured),
139             Some(bb) => bb,
140         };
141
142         let return_loc = ccx.body.terminator_loc(return_block);
143
144         let custom_eq = match ccx.const_kind() {
145             // We don't care whether a `const fn` returns a value that is not structurally
146             // matchable. Functions calls are opaque and always use type-based qualification, so
147             // this value should never be used.
148             hir::ConstContext::ConstFn => true,
149
150             // If we know that all values of the return type are structurally matchable, there's no
151             // need to run dataflow.
152             _ if !CustomEq::in_any_value_of_ty(ccx, ccx.body.return_ty()) => false,
153
154             hir::ConstContext::Const | hir::ConstContext::Static(_) => {
155                 let mut cursor = FlowSensitiveAnalysis::new(CustomEq, ccx)
156                     .into_engine(ccx.tcx, &ccx.body)
157                     .iterate_to_fixpoint()
158                     .into_results_cursor(&ccx.body);
159
160                 cursor.seek_after_primary_effect(return_loc);
161                 cursor.get().contains(RETURN_PLACE)
162             }
163         };
164
165         ConstQualifs {
166             needs_drop: self.needs_drop(ccx, RETURN_PLACE, return_loc),
167             needs_non_const_drop: self.needs_non_const_drop(ccx, RETURN_PLACE, return_loc),
168             has_mut_interior: self.has_mut_interior(ccx, RETURN_PLACE, return_loc),
169             custom_eq,
170             error_occured,
171         }
172     }
173 }
174
175 pub struct Checker<'mir, 'tcx> {
176     ccx: &'mir ConstCx<'mir, 'tcx>,
177     qualifs: Qualifs<'mir, 'tcx>,
178
179     /// The span of the current statement.
180     span: Span,
181
182     /// A set that stores for each local whether it has a `StorageDead` for it somewhere.
183     local_has_storage_dead: Option<BitSet<Local>>,
184
185     error_emitted: Option<ErrorReported>,
186     secondary_errors: Vec<Diagnostic>,
187 }
188
189 impl Deref for Checker<'mir, 'tcx> {
190     type Target = ConstCx<'mir, 'tcx>;
191
192     fn deref(&self) -> &Self::Target {
193         &self.ccx
194     }
195 }
196
197 impl Checker<'mir, 'tcx> {
198     pub fn new(ccx: &'mir ConstCx<'mir, 'tcx>) -> Self {
199         Checker {
200             span: ccx.body.span,
201             ccx,
202             qualifs: Default::default(),
203             local_has_storage_dead: None,
204             error_emitted: None,
205             secondary_errors: Vec::new(),
206         }
207     }
208
209     pub fn check_body(&mut self) {
210         let ConstCx { tcx, body, .. } = *self.ccx;
211         let def_id = self.ccx.def_id();
212
213         // `async` functions cannot be `const fn`. This is checked during AST lowering, so there's
214         // no need to emit duplicate errors here.
215         if is_async_fn(self.ccx) || body.generator.is_some() {
216             tcx.sess.delay_span_bug(body.span, "`async` functions cannot be `const fn`");
217             return;
218         }
219
220         // The local type and predicate checks are not free and only relevant for `const fn`s.
221         if self.const_kind() == hir::ConstContext::ConstFn {
222             // Prevent const trait methods from being annotated as `stable`.
223             // FIXME: Do this as part of stability checking.
224             if self.is_const_stable_const_fn() {
225                 let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
226                 if crate::const_eval::is_parent_const_impl_raw(tcx, hir_id) {
227                     self.ccx
228                         .tcx
229                         .sess
230                         .struct_span_err(self.span, "trait methods cannot be stable const fn")
231                         .emit();
232                 }
233             }
234
235             self.check_item_predicates();
236
237             for (idx, local) in body.local_decls.iter_enumerated() {
238                 // Handle the return place below.
239                 if idx == RETURN_PLACE || local.internal {
240                     continue;
241                 }
242
243                 self.span = local.source_info.span;
244                 self.check_local_or_return_ty(local.ty, idx);
245             }
246
247             // impl trait is gone in MIR, so check the return type of a const fn by its signature
248             // instead of the type of the return place.
249             self.span = body.local_decls[RETURN_PLACE].source_info.span;
250             let return_ty = tcx.fn_sig(def_id).output();
251             self.check_local_or_return_ty(return_ty.skip_binder(), RETURN_PLACE);
252         }
253
254         if !tcx.has_attr(def_id.to_def_id(), sym::rustc_do_not_const_check) {
255             self.visit_body(&body);
256         }
257
258         // Ensure that the end result is `Sync` in a non-thread local `static`.
259         let should_check_for_sync = self.const_kind()
260             == hir::ConstContext::Static(hir::Mutability::Not)
261             && !tcx.is_thread_local_static(def_id.to_def_id());
262
263         if should_check_for_sync {
264             let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
265             check_return_ty_is_sync(tcx, &body, hir_id);
266         }
267
268         // If we got through const-checking without emitting any "primary" errors, emit any
269         // "secondary" errors if they occurred.
270         let secondary_errors = mem::take(&mut self.secondary_errors);
271         if self.error_emitted.is_none() {
272             for error in secondary_errors {
273                 self.tcx.sess.diagnostic().emit_diagnostic(&error);
274             }
275         } else {
276             assert!(self.tcx.sess.has_errors());
277         }
278     }
279
280     fn local_has_storage_dead(&mut self, local: Local) -> bool {
281         let ccx = self.ccx;
282         self.local_has_storage_dead
283             .get_or_insert_with(|| {
284                 struct StorageDeads {
285                     locals: BitSet<Local>,
286                 }
287                 impl Visitor<'tcx> for StorageDeads {
288                     fn visit_statement(&mut self, stmt: &Statement<'tcx>, _: Location) {
289                         if let StatementKind::StorageDead(l) = stmt.kind {
290                             self.locals.insert(l);
291                         }
292                     }
293                 }
294                 let mut v = StorageDeads { locals: BitSet::new_empty(ccx.body.local_decls.len()) };
295                 v.visit_body(ccx.body);
296                 v.locals
297             })
298             .contains(local)
299     }
300
301     pub fn qualifs_in_return_place(&mut self) -> ConstQualifs {
302         self.qualifs.in_return_place(self.ccx, self.error_emitted)
303     }
304
305     /// Emits an error if an expression cannot be evaluated in the current context.
306     pub fn check_op(&mut self, op: impl NonConstOp) {
307         self.check_op_spanned(op, self.span);
308     }
309
310     /// Emits an error at the given `span` if an expression cannot be evaluated in the current
311     /// context.
312     pub fn check_op_spanned<O: NonConstOp>(&mut self, op: O, span: Span) {
313         let gate = match op.status_in_item(self.ccx) {
314             Status::Allowed => return,
315
316             Status::Unstable(gate) if self.tcx.features().enabled(gate) => {
317                 let unstable_in_stable = self.ccx.is_const_stable_const_fn()
318                     && !super::rustc_allow_const_fn_unstable(
319                         self.tcx,
320                         self.def_id().to_def_id(),
321                         gate,
322                     );
323                 if unstable_in_stable {
324                     emit_unstable_in_stable_error(self.ccx, span, gate);
325                 }
326
327                 return;
328             }
329
330             Status::Unstable(gate) => Some(gate),
331             Status::Forbidden => None,
332         };
333
334         if self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
335             self.tcx.sess.miri_unleashed_feature(span, gate);
336             return;
337         }
338
339         let mut err = op.build_error(self.ccx, span);
340         assert!(err.is_error());
341
342         match op.importance() {
343             ops::DiagnosticImportance::Primary => {
344                 self.error_emitted = Some(ErrorReported);
345                 err.emit();
346             }
347
348             ops::DiagnosticImportance::Secondary => err.buffer(&mut self.secondary_errors),
349         }
350     }
351
352     fn check_static(&mut self, def_id: DefId, span: Span) {
353         if self.tcx.is_thread_local_static(def_id) {
354             self.tcx.sess.delay_span_bug(span, "tls access is checked in `Rvalue::ThreadLocalRef");
355         }
356         self.check_op_spanned(ops::StaticAccess, span)
357     }
358
359     fn check_local_or_return_ty(&mut self, ty: Ty<'tcx>, local: Local) {
360         let kind = self.body.local_kind(local);
361
362         for ty in ty.walk(self.tcx) {
363             let ty = match ty.unpack() {
364                 GenericArgKind::Type(ty) => ty,
365
366                 // No constraints on lifetimes or constants, except potentially
367                 // constants' types, but `walk` will get to them as well.
368                 GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => continue,
369             };
370
371             match *ty.kind() {
372                 ty::Ref(_, _, hir::Mutability::Mut) => self.check_op(ops::ty::MutRef(kind)),
373                 ty::Opaque(..) => self.check_op(ops::ty::ImplTrait),
374                 ty::FnPtr(..) => self.check_op(ops::ty::FnPtr(kind)),
375
376                 ty::Dynamic(preds, _) => {
377                     for pred in preds.iter() {
378                         match pred.skip_binder() {
379                             ty::ExistentialPredicate::AutoTrait(_)
380                             | ty::ExistentialPredicate::Projection(_) => {
381                                 self.check_op(ops::ty::DynTrait(kind))
382                             }
383                             ty::ExistentialPredicate::Trait(trait_ref) => {
384                                 if Some(trait_ref.def_id) != self.tcx.lang_items().sized_trait() {
385                                     self.check_op(ops::ty::DynTrait(kind))
386                                 }
387                             }
388                         }
389                     }
390                 }
391                 _ => {}
392             }
393         }
394     }
395
396     fn check_item_predicates(&mut self) {
397         let ConstCx { tcx, .. } = *self.ccx;
398
399         let mut current = self.def_id().to_def_id();
400         loop {
401             let predicates = tcx.predicates_of(current);
402             for (predicate, _) in predicates.predicates {
403                 match predicate.kind().skip_binder() {
404                     ty::PredicateKind::RegionOutlives(_)
405                     | ty::PredicateKind::TypeOutlives(_)
406                     | ty::PredicateKind::WellFormed(_)
407                     | ty::PredicateKind::Projection(_)
408                     | ty::PredicateKind::ConstEvaluatable(..)
409                     | ty::PredicateKind::ConstEquate(..)
410                     | ty::PredicateKind::TypeWellFormedFromEnv(..) => continue,
411                     ty::PredicateKind::ObjectSafe(_) => {
412                         bug!("object safe predicate on function: {:#?}", predicate)
413                     }
414                     ty::PredicateKind::ClosureKind(..) => {
415                         bug!("closure kind predicate on function: {:#?}", predicate)
416                     }
417                     ty::PredicateKind::Subtype(_) | ty::PredicateKind::Coerce(_) => {
418                         bug!("subtype/coerce predicate on function: {:#?}", predicate)
419                     }
420                     ty::PredicateKind::Trait(pred) => {
421                         if Some(pred.def_id()) == tcx.lang_items().sized_trait() {
422                             continue;
423                         }
424                         match pred.self_ty().kind() {
425                             ty::Param(p) => {
426                                 let generics = tcx.generics_of(current);
427                                 let def = generics.type_param(p, tcx);
428                                 let span = tcx.def_span(def.def_id);
429
430                                 // These are part of the function signature, so treat them like
431                                 // arguments when determining importance.
432                                 let kind = LocalKind::Arg;
433
434                                 self.check_op_spanned(ops::ty::TraitBound(kind), span);
435                             }
436                             // other kinds of bounds are either tautologies
437                             // or cause errors in other passes
438                             _ => continue,
439                         }
440                     }
441                 }
442             }
443             match predicates.parent {
444                 Some(parent) => current = parent,
445                 None => break,
446             }
447         }
448     }
449
450     fn check_mut_borrow(&mut self, local: Local, kind: hir::BorrowKind) {
451         match self.const_kind() {
452             // In a const fn all borrows are transient or point to the places given via
453             // references in the arguments (so we already checked them with
454             // TransientMutBorrow/MutBorrow as appropriate).
455             // The borrow checker guarantees that no new non-transient borrows are created.
456             // NOTE: Once we have heap allocations during CTFE we need to figure out
457             // how to prevent `const fn` to create long-lived allocations that point
458             // to mutable memory.
459             hir::ConstContext::ConstFn => self.check_op(ops::TransientMutBorrow(kind)),
460             _ => {
461                 // Locals with StorageDead do not live beyond the evaluation and can
462                 // thus safely be borrowed without being able to be leaked to the final
463                 // value of the constant.
464                 if self.local_has_storage_dead(local) {
465                     self.check_op(ops::TransientMutBorrow(kind));
466                 } else {
467                     self.check_op(ops::MutBorrow(kind));
468                 }
469             }
470         }
471     }
472 }
473
474 impl Visitor<'tcx> for Checker<'mir, 'tcx> {
475     fn visit_basic_block_data(&mut self, bb: BasicBlock, block: &BasicBlockData<'tcx>) {
476         trace!("visit_basic_block_data: bb={:?} is_cleanup={:?}", bb, block.is_cleanup);
477
478         // We don't const-check basic blocks on the cleanup path since we never unwind during
479         // const-eval: a panic causes an immediate compile error. In other words, cleanup blocks
480         // are unreachable during const-eval.
481         //
482         // We can't be more conservative (e.g., by const-checking cleanup blocks anyways) because
483         // locals that would never be dropped during normal execution are sometimes dropped during
484         // unwinding, which means backwards-incompatible live-drop errors.
485         if block.is_cleanup {
486             return;
487         }
488
489         self.super_basic_block_data(bb, block);
490     }
491
492     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
493         trace!("visit_rvalue: rvalue={:?} location={:?}", rvalue, location);
494
495         // Special-case reborrows to be more like a copy of a reference.
496         match *rvalue {
497             Rvalue::Ref(_, kind, place) => {
498                 if let Some(reborrowed_place_ref) = place_as_reborrow(self.tcx, self.body, place) {
499                     let ctx = match kind {
500                         BorrowKind::Shared => {
501                             PlaceContext::NonMutatingUse(NonMutatingUseContext::SharedBorrow)
502                         }
503                         BorrowKind::Shallow => {
504                             PlaceContext::NonMutatingUse(NonMutatingUseContext::ShallowBorrow)
505                         }
506                         BorrowKind::Unique => {
507                             PlaceContext::NonMutatingUse(NonMutatingUseContext::UniqueBorrow)
508                         }
509                         BorrowKind::Mut { .. } => {
510                             PlaceContext::MutatingUse(MutatingUseContext::Borrow)
511                         }
512                     };
513                     self.visit_local(&reborrowed_place_ref.local, ctx, location);
514                     self.visit_projection(reborrowed_place_ref, ctx, location);
515                     return;
516                 }
517             }
518             Rvalue::AddressOf(mutbl, place) => {
519                 if let Some(reborrowed_place_ref) = place_as_reborrow(self.tcx, self.body, place) {
520                     let ctx = match mutbl {
521                         Mutability::Not => {
522                             PlaceContext::NonMutatingUse(NonMutatingUseContext::AddressOf)
523                         }
524                         Mutability::Mut => PlaceContext::MutatingUse(MutatingUseContext::AddressOf),
525                     };
526                     self.visit_local(&reborrowed_place_ref.local, ctx, location);
527                     self.visit_projection(reborrowed_place_ref, ctx, location);
528                     return;
529                 }
530             }
531             _ => {}
532         }
533
534         self.super_rvalue(rvalue, location);
535
536         match *rvalue {
537             Rvalue::ThreadLocalRef(_) => self.check_op(ops::ThreadLocalAccess),
538
539             Rvalue::Use(_)
540             | Rvalue::Repeat(..)
541             | Rvalue::Discriminant(..)
542             | Rvalue::Len(_)
543             | Rvalue::Aggregate(..) => {}
544
545             Rvalue::Ref(_, kind @ BorrowKind::Mut { .. }, ref place)
546             | Rvalue::Ref(_, kind @ BorrowKind::Unique, ref place) => {
547                 let ty = place.ty(self.body, self.tcx).ty;
548                 let is_allowed = match ty.kind() {
549                     // Inside a `static mut`, `&mut [...]` is allowed.
550                     ty::Array(..) | ty::Slice(_)
551                         if self.const_kind() == hir::ConstContext::Static(hir::Mutability::Mut) =>
552                     {
553                         true
554                     }
555
556                     // FIXME(ecstaticmorse): We could allow `&mut []` inside a const context given
557                     // that this is merely a ZST and it is already eligible for promotion.
558                     // This may require an RFC?
559                     /*
560                     ty::Array(_, len) if len.try_eval_usize(cx.tcx, cx.param_env) == Some(0)
561                         => true,
562                     */
563                     _ => false,
564                 };
565
566                 if !is_allowed {
567                     if let BorrowKind::Mut { .. } = kind {
568                         self.check_mut_borrow(place.local, hir::BorrowKind::Ref)
569                     } else {
570                         self.check_op(ops::CellBorrow);
571                     }
572                 }
573             }
574
575             Rvalue::AddressOf(Mutability::Mut, ref place) => {
576                 self.check_mut_borrow(place.local, hir::BorrowKind::Raw)
577             }
578
579             Rvalue::Ref(_, BorrowKind::Shared | BorrowKind::Shallow, ref place)
580             | Rvalue::AddressOf(Mutability::Not, ref place) => {
581                 let borrowed_place_has_mut_interior = qualifs::in_place::<HasMutInterior, _>(
582                     &self.ccx,
583                     &mut |local| self.qualifs.has_mut_interior(self.ccx, local, location),
584                     place.as_ref(),
585                 );
586
587                 if borrowed_place_has_mut_interior {
588                     match self.const_kind() {
589                         // In a const fn all borrows are transient or point to the places given via
590                         // references in the arguments (so we already checked them with
591                         // TransientCellBorrow/CellBorrow as appropriate).
592                         // The borrow checker guarantees that no new non-transient borrows are created.
593                         // NOTE: Once we have heap allocations during CTFE we need to figure out
594                         // how to prevent `const fn` to create long-lived allocations that point
595                         // to (interior) mutable memory.
596                         hir::ConstContext::ConstFn => self.check_op(ops::TransientCellBorrow),
597                         _ => {
598                             // Locals with StorageDead are definitely not part of the final constant value, and
599                             // it is thus inherently safe to permit such locals to have their
600                             // address taken as we can't end up with a reference to them in the
601                             // final value.
602                             // Note: This is only sound if every local that has a `StorageDead` has a
603                             // `StorageDead` in every control flow path leading to a `return` terminator.
604                             if self.local_has_storage_dead(place.local) {
605                                 self.check_op(ops::TransientCellBorrow);
606                             } else {
607                                 self.check_op(ops::CellBorrow);
608                             }
609                         }
610                     }
611                 }
612             }
613
614             Rvalue::Cast(
615                 CastKind::Pointer(PointerCast::MutToConstPointer | PointerCast::ArrayToPointer),
616                 _,
617                 _,
618             ) => {}
619
620             Rvalue::Cast(
621                 CastKind::Pointer(
622                     PointerCast::UnsafeFnPointer
623                     | PointerCast::ClosureFnPointer(_)
624                     | PointerCast::ReifyFnPointer,
625                 ),
626                 _,
627                 _,
628             ) => self.check_op(ops::FnPtrCast),
629
630             Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), _, _) => {
631                 // Nothing to check here (`check_local_or_return_ty` ensures no trait objects occur
632                 // in the type of any local, which also excludes casts).
633             }
634
635             Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
636                 let operand_ty = operand.ty(self.body, self.tcx);
637                 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
638                 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
639
640                 if let (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) = (cast_in, cast_out) {
641                     self.check_op(ops::RawPtrToIntCast);
642                 }
643             }
644
645             Rvalue::NullaryOp(NullOp::SizeOf | NullOp::AlignOf, _) => {}
646             Rvalue::NullaryOp(NullOp::Box, _) => self.check_op(ops::HeapAllocation),
647             Rvalue::ShallowInitBox(_, _) => {}
648
649             Rvalue::UnaryOp(_, ref operand) => {
650                 let ty = operand.ty(self.body, self.tcx);
651                 if is_int_bool_or_char(ty) {
652                     // Int, bool, and char operations are fine.
653                 } else if ty.is_floating_point() {
654                     self.check_op(ops::FloatingPointOp);
655                 } else {
656                     span_bug!(self.span, "non-primitive type in `Rvalue::UnaryOp`: {:?}", ty);
657                 }
658             }
659
660             Rvalue::BinaryOp(op, box (ref lhs, ref rhs))
661             | Rvalue::CheckedBinaryOp(op, box (ref lhs, ref rhs)) => {
662                 let lhs_ty = lhs.ty(self.body, self.tcx);
663                 let rhs_ty = rhs.ty(self.body, self.tcx);
664
665                 if is_int_bool_or_char(lhs_ty) && is_int_bool_or_char(rhs_ty) {
666                     // Int, bool, and char operations are fine.
667                 } else if lhs_ty.is_fn_ptr() || lhs_ty.is_unsafe_ptr() {
668                     assert_eq!(lhs_ty, rhs_ty);
669                     assert!(
670                         op == BinOp::Eq
671                             || op == BinOp::Ne
672                             || op == BinOp::Le
673                             || op == BinOp::Lt
674                             || op == BinOp::Ge
675                             || op == BinOp::Gt
676                             || op == BinOp::Offset
677                     );
678
679                     self.check_op(ops::RawPtrComparison);
680                 } else if lhs_ty.is_floating_point() || rhs_ty.is_floating_point() {
681                     self.check_op(ops::FloatingPointOp);
682                 } else {
683                     span_bug!(
684                         self.span,
685                         "non-primitive type in `Rvalue::BinaryOp`: {:?} âš¬ {:?}",
686                         lhs_ty,
687                         rhs_ty
688                     );
689                 }
690             }
691         }
692     }
693
694     fn visit_operand(&mut self, op: &Operand<'tcx>, location: Location) {
695         self.super_operand(op, location);
696         if let Operand::Constant(c) = op {
697             if let Some(def_id) = c.check_static_ptr(self.tcx) {
698                 self.check_static(def_id, self.span);
699             }
700         }
701     }
702     fn visit_projection_elem(
703         &mut self,
704         place_local: Local,
705         proj_base: &[PlaceElem<'tcx>],
706         elem: PlaceElem<'tcx>,
707         context: PlaceContext,
708         location: Location,
709     ) {
710         trace!(
711             "visit_projection_elem: place_local={:?} proj_base={:?} elem={:?} \
712             context={:?} location={:?}",
713             place_local,
714             proj_base,
715             elem,
716             context,
717             location,
718         );
719
720         self.super_projection_elem(place_local, proj_base, elem, context, location);
721
722         match elem {
723             ProjectionElem::Deref => {
724                 let base_ty = Place::ty_from(place_local, proj_base, self.body, self.tcx).ty;
725                 if let ty::RawPtr(_) = base_ty.kind() {
726                     if proj_base.is_empty() {
727                         let decl = &self.body.local_decls[place_local];
728                         if let Some(box LocalInfo::StaticRef { def_id, .. }) = decl.local_info {
729                             let span = decl.source_info.span;
730                             self.check_static(def_id, span);
731                             return;
732                         }
733                     }
734                     self.check_op(ops::RawPtrDeref);
735                 }
736
737                 if context.is_mutating_use() {
738                     self.check_op(ops::MutDeref);
739                 }
740             }
741
742             ProjectionElem::ConstantIndex { .. }
743             | ProjectionElem::Downcast(..)
744             | ProjectionElem::Subslice { .. }
745             | ProjectionElem::Field(..)
746             | ProjectionElem::Index(_) => {}
747         }
748     }
749
750     fn visit_source_info(&mut self, source_info: &SourceInfo) {
751         trace!("visit_source_info: source_info={:?}", source_info);
752         self.span = source_info.span;
753     }
754
755     fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
756         trace!("visit_statement: statement={:?} location={:?}", statement, location);
757
758         self.super_statement(statement, location);
759
760         match statement.kind {
761             StatementKind::LlvmInlineAsm { .. } => {
762                 self.check_op(ops::InlineAsm);
763             }
764
765             StatementKind::Assign(..)
766             | StatementKind::SetDiscriminant { .. }
767             | StatementKind::FakeRead(..)
768             | StatementKind::StorageLive(_)
769             | StatementKind::StorageDead(_)
770             | StatementKind::Retag { .. }
771             | StatementKind::AscribeUserType(..)
772             | StatementKind::Coverage(..)
773             | StatementKind::CopyNonOverlapping(..)
774             | StatementKind::Nop => {}
775         }
776     }
777
778     #[instrument(level = "debug", skip(self))]
779     fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
780         use rustc_target::spec::abi::Abi::RustIntrinsic;
781
782         self.super_terminator(terminator, location);
783
784         match &terminator.kind {
785             TerminatorKind::Call { func, args, .. } => {
786                 let ConstCx { tcx, body, param_env, .. } = *self.ccx;
787                 let caller = self.def_id().to_def_id();
788
789                 let fn_ty = func.ty(body, tcx);
790
791                 let (mut callee, mut substs) = match *fn_ty.kind() {
792                     ty::FnDef(def_id, substs) => (def_id, substs),
793
794                     ty::FnPtr(_) => {
795                         self.check_op(ops::FnCallIndirect);
796                         return;
797                     }
798                     _ => {
799                         span_bug!(terminator.source_info.span, "invalid callee of type {:?}", fn_ty)
800                     }
801                 };
802
803                 let mut nonconst_call_permission = false;
804
805                 // Attempting to call a trait method?
806                 if let Some(trait_id) = tcx.trait_of_item(callee) {
807                     trace!("attempting to call a trait method");
808                     if !self.tcx.features().const_trait_impl {
809                         self.check_op(ops::FnCallNonConst);
810                         return;
811                     }
812
813                     let trait_ref = TraitRef::from_method(tcx, trait_id, substs);
814                     let obligation = Obligation::new(
815                         ObligationCause::dummy(),
816                         param_env,
817                         Binder::dummy(TraitPredicate {
818                             trait_ref,
819                             constness: ty::BoundConstness::ConstIfConst,
820                             polarity: ty::ImplPolarity::Positive,
821                         }),
822                     );
823
824                     let implsrc = tcx.infer_ctxt().enter(|infcx| {
825                         let mut selcx =
826                             SelectionContext::with_constness(&infcx, hir::Constness::Const);
827                         selcx.select(&obligation)
828                     });
829
830                     match implsrc {
831                         Ok(Some(ImplSource::Param(_, ty::BoundConstness::ConstIfConst))) => {
832                             debug!(
833                                 "const_trait_impl: provided {:?} via where-clause in {:?}",
834                                 trait_ref, param_env
835                             );
836                             return;
837                         }
838                         Ok(Some(ImplSource::UserDefined(data))) => {
839                             let callee_name = tcx.item_name(callee);
840                             if let Some(&did) = tcx
841                                 .associated_item_def_ids(data.impl_def_id)
842                                 .iter()
843                                 .find(|did| tcx.item_name(**did) == callee_name)
844                             {
845                                 // using internal substs is ok here, since this is only
846                                 // used for the `resolve` call below
847                                 substs = InternalSubsts::identity_for_item(tcx, did);
848                                 callee = did;
849                             }
850                         }
851                         _ if !tcx.is_const_fn_raw(callee) => {
852                             // At this point, it is only legal when the caller is marked with
853                             // #[default_method_body_is_const], and the callee is in the same
854                             // trait.
855                             let callee_trait = tcx.trait_of_item(callee);
856                             if callee_trait.is_some() {
857                                 if tcx.has_attr(caller, sym::default_method_body_is_const) {
858                                     if tcx.trait_of_item(caller) == callee_trait {
859                                         nonconst_call_permission = true;
860                                     }
861                                 }
862                             }
863
864                             if !nonconst_call_permission {
865                                 self.check_op(ops::FnCallNonConst);
866                                 return;
867                             }
868                         }
869                         _ => {}
870                     }
871
872                     // Resolve a trait method call to its concrete implementation, which may be in a
873                     // `const` trait impl.
874                     let instance = Instance::resolve(tcx, param_env, callee, substs);
875                     debug!("Resolving ({:?}) -> {:?}", callee, instance);
876                     if let Ok(Some(func)) = instance {
877                         if let InstanceDef::Item(def) = func.def {
878                             callee = def.did;
879                         }
880                     }
881                 }
882
883                 // At this point, we are calling a function, `callee`, whose `DefId` is known...
884
885                 // `begin_panic` and `panic_display` are generic functions that accept
886                 // types other than str. Check to enforce that only str can be used in
887                 // const-eval.
888
889                 // const-eval of the `begin_panic` fn assumes the argument is `&str`
890                 if Some(callee) == tcx.lang_items().begin_panic_fn() {
891                     match args[0].ty(&self.ccx.body.local_decls, tcx).kind() {
892                         ty::Ref(_, ty, _) if ty.is_str() => return,
893                         _ => self.check_op(ops::PanicNonStr),
894                     }
895                 }
896
897                 // const-eval of the `panic_display` fn assumes the argument is `&&str`
898                 if Some(callee) == tcx.lang_items().panic_display() {
899                     match args[0].ty(&self.ccx.body.local_decls, tcx).kind() {
900                         ty::Ref(_, ty, _) if matches!(ty.kind(), ty::Ref(_, ty, _) if ty.is_str()) =>
901                         {
902                             return;
903                         }
904                         _ => self.check_op(ops::PanicNonStr),
905                     }
906                 }
907
908                 if Some(callee) == tcx.lang_items().exchange_malloc_fn() {
909                     self.check_op(ops::HeapAllocation);
910                     return;
911                 }
912
913                 // `async` blocks get lowered to `std::future::from_generator(/* a closure */)`.
914                 let is_async_block = Some(callee) == tcx.lang_items().from_generator_fn();
915                 if is_async_block {
916                     let kind = hir::GeneratorKind::Async(hir::AsyncGeneratorKind::Block);
917                     self.check_op(ops::Generator(kind));
918                     return;
919                 }
920
921                 let is_intrinsic = tcx.fn_sig(callee).abi() == RustIntrinsic;
922
923                 if !tcx.is_const_fn_raw(callee) {
924                     if tcx.trait_of_item(callee).is_some() {
925                         if tcx.has_attr(callee, sym::default_method_body_is_const) {
926                             // To get to here we must have already found a const impl for the
927                             // trait, but for it to still be non-const can be that the impl is
928                             // using default method bodies.
929                             nonconst_call_permission = true;
930                         }
931                     }
932
933                     if !nonconst_call_permission {
934                         self.check_op(ops::FnCallNonConst);
935                         return;
936                     }
937                 }
938
939                 // If the `const fn` we are trying to call is not const-stable, ensure that we have
940                 // the proper feature gate enabled.
941                 if let Some(gate) = is_unstable_const_fn(tcx, callee) {
942                     trace!(?gate, "calling unstable const fn");
943                     if self.span.allows_unstable(gate) {
944                         return;
945                     }
946
947                     // Calling an unstable function *always* requires that the corresponding gate
948                     // be enabled, even if the function has `#[rustc_allow_const_fn_unstable(the_gate)]`.
949                     if !tcx.features().declared_lib_features.iter().any(|&(sym, _)| sym == gate) {
950                         self.check_op(ops::FnCallUnstable(callee, Some(gate)));
951                         return;
952                     }
953
954                     // If this crate is not using stability attributes, or the caller is not claiming to be a
955                     // stable `const fn`, that is all that is required.
956                     if !self.ccx.is_const_stable_const_fn() {
957                         trace!("crate not using stability attributes or caller not stably const");
958                         return;
959                     }
960
961                     // Otherwise, we are something const-stable calling a const-unstable fn.
962
963                     if super::rustc_allow_const_fn_unstable(tcx, caller, gate) {
964                         trace!("rustc_allow_const_fn_unstable gate active");
965                         return;
966                     }
967
968                     self.check_op(ops::FnCallUnstable(callee, Some(gate)));
969                     return;
970                 }
971
972                 // FIXME(ecstaticmorse); For compatibility, we consider `unstable` callees that
973                 // have no `rustc_const_stable` attributes to be const-unstable as well. This
974                 // should be fixed later.
975                 let callee_is_unstable_unmarked = tcx.lookup_const_stability(callee).is_none()
976                     && tcx.lookup_stability(callee).map_or(false, |s| s.level.is_unstable());
977                 if callee_is_unstable_unmarked {
978                     trace!("callee_is_unstable_unmarked");
979                     // We do not use `const` modifiers for intrinsic "functions", as intrinsics are
980                     // `extern` funtions, and these have no way to get marked `const`. So instead we
981                     // use `rustc_const_(un)stable` attributes to mean that the intrinsic is `const`
982                     if self.ccx.is_const_stable_const_fn() || is_intrinsic {
983                         self.check_op(ops::FnCallUnstable(callee, None));
984                         return;
985                     }
986                 }
987                 trace!("permitting call");
988             }
989
990             // Forbid all `Drop` terminators unless the place being dropped is a local with no
991             // projections that cannot be `NeedsNonConstDrop`.
992             TerminatorKind::Drop { place: dropped_place, .. }
993             | TerminatorKind::DropAndReplace { place: dropped_place, .. } => {
994                 // If we are checking live drops after drop-elaboration, don't emit duplicate
995                 // errors here.
996                 if super::post_drop_elaboration::checking_enabled(self.ccx) {
997                     return;
998                 }
999
1000                 let mut err_span = self.span;
1001
1002                 let ty_needs_non_const_drop = qualifs::NeedsNonConstDrop::in_any_value_of_ty(
1003                     self.ccx,
1004                     dropped_place.ty(self.body, self.tcx).ty,
1005                 );
1006
1007                 if !ty_needs_non_const_drop {
1008                     return;
1009                 }
1010
1011                 let needs_non_const_drop = if let Some(local) = dropped_place.as_local() {
1012                     // Use the span where the local was declared as the span of the drop error.
1013                     err_span = self.body.local_decls[local].source_info.span;
1014                     self.qualifs.needs_non_const_drop(self.ccx, local, location)
1015                 } else {
1016                     true
1017                 };
1018
1019                 if needs_non_const_drop {
1020                     self.check_op_spanned(
1021                         ops::LiveDrop { dropped_at: Some(terminator.source_info.span) },
1022                         err_span,
1023                     );
1024                 }
1025             }
1026
1027             TerminatorKind::InlineAsm { .. } => self.check_op(ops::InlineAsm),
1028
1029             TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
1030                 self.check_op(ops::Generator(hir::GeneratorKind::Gen))
1031             }
1032
1033             TerminatorKind::Abort => {
1034                 // Cleanup blocks are skipped for const checking (see `visit_basic_block_data`).
1035                 span_bug!(self.span, "`Abort` terminator outside of cleanup block")
1036             }
1037
1038             TerminatorKind::Assert { .. }
1039             | TerminatorKind::FalseEdge { .. }
1040             | TerminatorKind::FalseUnwind { .. }
1041             | TerminatorKind::Goto { .. }
1042             | TerminatorKind::Resume
1043             | TerminatorKind::Return
1044             | TerminatorKind::SwitchInt { .. }
1045             | TerminatorKind::Unreachable => {}
1046         }
1047     }
1048 }
1049
1050 fn check_return_ty_is_sync(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, hir_id: HirId) {
1051     let ty = body.return_ty();
1052     tcx.infer_ctxt().enter(|infcx| {
1053         let cause = traits::ObligationCause::new(body.span, hir_id, traits::SharedStatic);
1054         let mut fulfillment_cx = traits::FulfillmentContext::new();
1055         let sync_def_id = tcx.require_lang_item(LangItem::Sync, Some(body.span));
1056         fulfillment_cx.register_bound(&infcx, ty::ParamEnv::empty(), ty, sync_def_id, cause);
1057         if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) {
1058             infcx.report_fulfillment_errors(&err, None, false);
1059         }
1060     });
1061 }
1062
1063 fn place_as_reborrow(
1064     tcx: TyCtxt<'tcx>,
1065     body: &Body<'tcx>,
1066     place: Place<'tcx>,
1067 ) -> Option<PlaceRef<'tcx>> {
1068     match place.as_ref().last_projection() {
1069         Some((place_base, ProjectionElem::Deref)) => {
1070             // A borrow of a `static` also looks like `&(*_1)` in the MIR, but `_1` is a `const`
1071             // that points to the allocation for the static. Don't treat these as reborrows.
1072             if body.local_decls[place_base.local].is_ref_to_static() {
1073                 None
1074             } else {
1075                 // Ensure the type being derefed is a reference and not a raw pointer.
1076                 // This is sufficient to prevent an access to a `static mut` from being marked as a
1077                 // reborrow, even if the check above were to disappear.
1078                 let inner_ty = place_base.ty(body, tcx).ty;
1079
1080                 if let ty::Ref(..) = inner_ty.kind() {
1081                     return Some(place_base);
1082                 } else {
1083                     return None;
1084                 }
1085             }
1086         }
1087         _ => None,
1088     }
1089 }
1090
1091 fn is_int_bool_or_char(ty: Ty<'_>) -> bool {
1092     ty.is_bool() || ty.is_integral() || ty.is_char()
1093 }
1094
1095 fn is_async_fn(ccx: &ConstCx<'_, '_>) -> bool {
1096     ccx.fn_sig().map_or(false, |sig| sig.header.asyncness == hir::IsAsync::Async)
1097 }
1098
1099 fn emit_unstable_in_stable_error(ccx: &ConstCx<'_, '_>, span: Span, gate: Symbol) {
1100     let attr_span = ccx.fn_sig().map_or(ccx.body.span, |sig| sig.span.shrink_to_lo());
1101
1102     ccx.tcx
1103         .sess
1104         .struct_span_err(
1105             span,
1106             &format!("const-stable function cannot use `#[feature({})]`", gate.as_str()),
1107         )
1108         .span_suggestion(
1109             attr_span,
1110             "if it is not part of the public API, make this function unstably const",
1111             concat!(r#"#[rustc_const_unstable(feature = "...", issue = "...")]"#, '\n').to_owned(),
1112             Applicability::HasPlaceholders,
1113         )
1114         .span_suggestion(
1115             attr_span,
1116             "otherwise `#[rustc_allow_const_fn_unstable]` can be used to bypass stability checks",
1117             format!("#[rustc_allow_const_fn_unstable({})]\n", gate),
1118             Applicability::MaybeIncorrect,
1119         )
1120         .emit();
1121 }