]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/check_consts/validation.rs
c864abdae66a53cf6f29d127c7e7acdd53ca8504
[rust.git] / src / librustc_mir / transform / check_consts / validation.rs
1 //! The `Visitor` responsible for actually checking a `mir::Body` for invalid operations.
2
3 use rustc::middle::lang_items;
4 use rustc::mir::visit::{MutatingUseContext, NonMutatingUseContext, PlaceContext, Visitor};
5 use rustc::mir::*;
6 use rustc::traits::{self, TraitEngine};
7 use rustc::ty::cast::CastTy;
8 use rustc::ty::{self, TyCtxt};
9 use rustc_error_codes::*;
10 use rustc_errors::struct_span_err;
11 use rustc_hir::{def_id::DefId, HirId};
12 use rustc_index::bit_set::BitSet;
13 use rustc_span::symbol::sym;
14 use rustc_span::Span;
15
16 use std::borrow::Cow;
17 use std::ops::Deref;
18
19 use self::old_dataflow::IndirectlyMutableLocals;
20 use super::ops::{self, NonConstOp};
21 use super::qualifs::{self, HasMutInterior, NeedsDrop};
22 use super::resolver::FlowSensitiveAnalysis;
23 use super::{is_lang_panic_fn, ConstKind, Item, Qualif};
24 use crate::const_eval::{is_const_fn, is_unstable_const_fn};
25 use crate::dataflow::{self as old_dataflow, generic as dataflow};
26
27 pub type IndirectlyMutableResults<'mir, 'tcx> =
28     old_dataflow::DataflowResultsCursor<'mir, 'tcx, IndirectlyMutableLocals<'mir, 'tcx>>;
29
30 struct QualifCursor<'a, 'mir, 'tcx, Q: Qualif> {
31     cursor: dataflow::ResultsCursor<'mir, 'tcx, FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q>>,
32     in_any_value_of_ty: BitSet<Local>,
33 }
34
35 impl<Q: Qualif> QualifCursor<'a, 'mir, 'tcx, Q> {
36     pub fn new(q: Q, item: &'a Item<'mir, 'tcx>, dead_unwinds: &BitSet<BasicBlock>) -> Self {
37         let analysis = FlowSensitiveAnalysis::new(q, item);
38         let results =
39             dataflow::Engine::new(item.tcx, &item.body, item.def_id, dead_unwinds, analysis)
40                 .iterate_to_fixpoint();
41         let cursor = dataflow::ResultsCursor::new(*item.body, results);
42
43         let mut in_any_value_of_ty = BitSet::new_empty(item.body.local_decls.len());
44         for (local, decl) in item.body.local_decls.iter_enumerated() {
45             if Q::in_any_value_of_ty(item, decl.ty) {
46                 in_any_value_of_ty.insert(local);
47             }
48         }
49
50         QualifCursor { cursor, in_any_value_of_ty }
51     }
52 }
53
54 pub struct Qualifs<'a, 'mir, 'tcx> {
55     has_mut_interior: QualifCursor<'a, 'mir, 'tcx, HasMutInterior>,
56     needs_drop: QualifCursor<'a, 'mir, 'tcx, NeedsDrop>,
57     indirectly_mutable: IndirectlyMutableResults<'mir, 'tcx>,
58 }
59
60 impl Qualifs<'a, 'mir, 'tcx> {
61     fn indirectly_mutable(&mut self, local: Local, location: Location) -> bool {
62         self.indirectly_mutable.seek(location);
63         self.indirectly_mutable.get().contains(local)
64     }
65
66     /// Returns `true` if `local` is `NeedsDrop` at the given `Location`.
67     ///
68     /// Only updates the cursor if absolutely necessary
69     fn needs_drop_lazy_seek(&mut self, local: Local, location: Location) -> bool {
70         if !self.needs_drop.in_any_value_of_ty.contains(local) {
71             return false;
72         }
73
74         self.needs_drop.cursor.seek_before(location);
75         self.needs_drop.cursor.get().contains(local) || self.indirectly_mutable(local, location)
76     }
77
78     /// Returns `true` if `local` is `HasMutInterior` at the given `Location`.
79     ///
80     /// Only updates the cursor if absolutely necessary.
81     fn has_mut_interior_lazy_seek(&mut self, local: Local, location: Location) -> bool {
82         if !self.has_mut_interior.in_any_value_of_ty.contains(local) {
83             return false;
84         }
85
86         self.has_mut_interior.cursor.seek_before(location);
87         self.has_mut_interior.cursor.get().contains(local)
88             || self.indirectly_mutable(local, location)
89     }
90
91     /// Returns `true` if `local` is `HasMutInterior`, but requires the `has_mut_interior` and
92     /// `indirectly_mutable` cursors to be updated beforehand.
93     fn has_mut_interior_eager_seek(&self, local: Local) -> bool {
94         if !self.has_mut_interior.in_any_value_of_ty.contains(local) {
95             return false;
96         }
97
98         self.has_mut_interior.cursor.get().contains(local)
99             || self.indirectly_mutable.get().contains(local)
100     }
101
102     fn in_return_place(&mut self, item: &Item<'_, 'tcx>) -> ConstQualifs {
103         // Find the `Return` terminator if one exists.
104         //
105         // If no `Return` terminator exists, this MIR is divergent. Just return the conservative
106         // qualifs for the return type.
107         let return_block = item
108             .body
109             .basic_blocks()
110             .iter_enumerated()
111             .find(|(_, block)| match block.terminator().kind {
112                 TerminatorKind::Return => true,
113                 _ => false,
114             })
115             .map(|(bb, _)| bb);
116
117         let return_block = match return_block {
118             None => return qualifs::in_any_value_of_ty(item, item.body.return_ty()),
119             Some(bb) => bb,
120         };
121
122         let return_loc = item.body.terminator_loc(return_block);
123
124         ConstQualifs {
125             needs_drop: self.needs_drop_lazy_seek(RETURN_PLACE, return_loc),
126             has_mut_interior: self.has_mut_interior_lazy_seek(RETURN_PLACE, return_loc),
127         }
128     }
129 }
130
131 pub struct Validator<'a, 'mir, 'tcx> {
132     item: &'a Item<'mir, 'tcx>,
133     qualifs: Qualifs<'a, 'mir, 'tcx>,
134
135     /// The span of the current statement.
136     span: Span,
137 }
138
139 impl Deref for Validator<'_, 'mir, 'tcx> {
140     type Target = Item<'mir, 'tcx>;
141
142     fn deref(&self) -> &Self::Target {
143         &self.item
144     }
145 }
146
147 impl Validator<'a, 'mir, 'tcx> {
148     pub fn new(item: &'a Item<'mir, 'tcx>) -> Self {
149         let dead_unwinds = BitSet::new_empty(item.body.basic_blocks().len());
150
151         let needs_drop = QualifCursor::new(NeedsDrop, item, &dead_unwinds);
152
153         let has_mut_interior = QualifCursor::new(HasMutInterior, item, &dead_unwinds);
154
155         let indirectly_mutable = old_dataflow::do_dataflow(
156             item.tcx,
157             &*item.body,
158             item.def_id,
159             &item.tcx.get_attrs(item.def_id),
160             &dead_unwinds,
161             old_dataflow::IndirectlyMutableLocals::new(item.tcx, *item.body, item.param_env),
162             |_, local| old_dataflow::DebugFormatted::new(&local),
163         );
164
165         let indirectly_mutable =
166             old_dataflow::DataflowResultsCursor::new(indirectly_mutable, *item.body);
167
168         let qualifs = Qualifs { needs_drop, has_mut_interior, indirectly_mutable };
169
170         Validator { span: item.body.span, item, qualifs }
171     }
172
173     pub fn check_body(&mut self) {
174         let Item { tcx, body, def_id, const_kind, .. } = *self.item;
175
176         let use_min_const_fn_checks = (const_kind == Some(ConstKind::ConstFn)
177             && crate::const_eval::is_min_const_fn(tcx, def_id))
178             && !tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you;
179
180         if use_min_const_fn_checks {
181             // Enforce `min_const_fn` for stable `const fn`s.
182             use crate::transform::qualify_min_const_fn::is_min_const_fn;
183             if let Err((span, err)) = is_min_const_fn(tcx, def_id, &body) {
184                 error_min_const_fn_violation(tcx, span, err);
185                 return;
186             }
187         }
188
189         check_short_circuiting_in_const_local(self.item);
190
191         if body.is_cfg_cyclic() {
192             // We can't provide a good span for the error here, but this should be caught by the
193             // HIR const-checker anyways.
194             self.check_op_spanned(ops::Loop, body.span);
195         }
196
197         self.visit_body(body);
198
199         // Ensure that the end result is `Sync` in a non-thread local `static`.
200         let should_check_for_sync =
201             const_kind == Some(ConstKind::Static) && !tcx.has_attr(def_id, sym::thread_local);
202
203         if should_check_for_sync {
204             let hir_id = tcx.hir().as_local_hir_id(def_id).unwrap();
205             check_return_ty_is_sync(tcx, &body, hir_id);
206         }
207     }
208
209     pub fn qualifs_in_return_place(&mut self) -> ConstQualifs {
210         self.qualifs.in_return_place(self.item)
211     }
212
213     /// Emits an error at the given `span` if an expression cannot be evaluated in the current
214     /// context.
215     pub fn check_op_spanned<O>(&mut self, op: O, span: Span)
216     where
217         O: NonConstOp,
218     {
219         trace!("check_op: op={:?}", op);
220
221         if op.is_allowed_in_item(self) {
222             return;
223         }
224
225         // If an operation is supported in miri (and is not already controlled by a feature gate) it
226         // can be turned on with `-Zunleash-the-miri-inside-of-you`.
227         let is_unleashable = O::IS_SUPPORTED_IN_MIRI && O::feature_gate(self.tcx).is_none();
228
229         if is_unleashable && self.tcx.sess.opts.debugging_opts.unleash_the_miri_inside_of_you {
230             self.tcx.sess.span_warn(span, "skipping const checks");
231             return;
232         }
233
234         op.emit_error(self, span);
235     }
236
237     /// Emits an error if an expression cannot be evaluated in the current context.
238     pub fn check_op(&mut self, op: impl NonConstOp) {
239         let span = self.span;
240         self.check_op_spanned(op, span)
241     }
242
243     fn check_static(&mut self, def_id: DefId, span: Span) {
244         let is_thread_local = self.tcx.has_attr(def_id, sym::thread_local);
245         if is_thread_local {
246             self.check_op_spanned(ops::ThreadLocalAccess, span)
247         } else {
248             self.check_op_spanned(ops::StaticAccess, span)
249         }
250     }
251
252     fn check_immutable_borrow_like(&mut self, location: Location, place: &Place<'tcx>) {
253         // FIXME: Change the `in_*` methods to take a `FnMut` so we don't have to manually
254         // seek the cursors beforehand.
255         self.qualifs.has_mut_interior.cursor.seek_before(location);
256         self.qualifs.indirectly_mutable.seek(location);
257
258         let borrowed_place_has_mut_interior = HasMutInterior::in_place(
259             &self.item,
260             &|local| self.qualifs.has_mut_interior_eager_seek(local),
261             place.as_ref(),
262         );
263
264         if borrowed_place_has_mut_interior {
265             self.check_op(ops::CellBorrow);
266         }
267     }
268 }
269
270 impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> {
271     fn visit_basic_block_data(&mut self, bb: BasicBlock, block: &BasicBlockData<'tcx>) {
272         trace!("visit_basic_block_data: bb={:?} is_cleanup={:?}", bb, block.is_cleanup);
273
274         // Just as the old checker did, we skip const-checking basic blocks on the unwind path.
275         // These blocks often drop locals that would otherwise be returned from the function.
276         //
277         // FIXME: This shouldn't be unsound since a panic at compile time will cause a compiler
278         // error anyway, but maybe we should do more here?
279         if block.is_cleanup {
280             return;
281         }
282
283         self.super_basic_block_data(bb, block);
284     }
285
286     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
287         trace!("visit_rvalue: rvalue={:?} location={:?}", rvalue, location);
288
289         // Special-case reborrows to be more like a copy of a reference.
290         match *rvalue {
291             Rvalue::Ref(_, kind, ref place) => {
292                 if let Some(reborrowed_proj) = place_as_reborrow(self.tcx, *self.body, place) {
293                     let ctx = match kind {
294                         BorrowKind::Shared => {
295                             PlaceContext::NonMutatingUse(NonMutatingUseContext::SharedBorrow)
296                         }
297                         BorrowKind::Shallow => {
298                             PlaceContext::NonMutatingUse(NonMutatingUseContext::ShallowBorrow)
299                         }
300                         BorrowKind::Unique => {
301                             PlaceContext::NonMutatingUse(NonMutatingUseContext::UniqueBorrow)
302                         }
303                         BorrowKind::Mut { .. } => {
304                             PlaceContext::MutatingUse(MutatingUseContext::Borrow)
305                         }
306                     };
307                     self.visit_place_base(&place.base, ctx, location);
308                     self.visit_projection(&place.base, reborrowed_proj, ctx, location);
309                     return;
310                 }
311             }
312             Rvalue::AddressOf(mutbl, ref place) => {
313                 if let Some(reborrowed_proj) = place_as_reborrow(self.tcx, *self.body, place) {
314                     let ctx = match mutbl {
315                         Mutability::Not => {
316                             PlaceContext::NonMutatingUse(NonMutatingUseContext::AddressOf)
317                         }
318                         Mutability::Mut => PlaceContext::MutatingUse(MutatingUseContext::AddressOf),
319                     };
320                     self.visit_place_base(&place.base, ctx, location);
321                     self.visit_projection(&place.base, reborrowed_proj, ctx, location);
322                     return;
323                 }
324             }
325             _ => {}
326         }
327
328         self.super_rvalue(rvalue, location);
329
330         match *rvalue {
331             Rvalue::Use(_)
332             | Rvalue::Repeat(..)
333             | Rvalue::UnaryOp(UnOp::Neg, _)
334             | Rvalue::UnaryOp(UnOp::Not, _)
335             | Rvalue::NullaryOp(NullOp::SizeOf, _)
336             | Rvalue::CheckedBinaryOp(..)
337             | Rvalue::Cast(CastKind::Pointer(_), ..)
338             | Rvalue::Discriminant(..)
339             | Rvalue::Len(_)
340             | Rvalue::Aggregate(..) => {}
341
342             Rvalue::Ref(_, kind @ BorrowKind::Mut { .. }, ref place)
343             | Rvalue::Ref(_, kind @ BorrowKind::Unique, ref place) => {
344                 let ty = place.ty(*self.body, self.tcx).ty;
345                 let is_allowed = match ty.kind {
346                     // Inside a `static mut`, `&mut [...]` is allowed.
347                     ty::Array(..) | ty::Slice(_) if self.const_kind() == ConstKind::StaticMut => {
348                         true
349                     }
350
351                     // FIXME(ecstaticmorse): We could allow `&mut []` inside a const context given
352                     // that this is merely a ZST and it is already eligible for promotion.
353                     // This may require an RFC?
354                     /*
355                     ty::Array(_, len) if len.try_eval_usize(cx.tcx, cx.param_env) == Some(0)
356                         => true,
357                     */
358                     _ => false,
359                 };
360
361                 if !is_allowed {
362                     if let BorrowKind::Mut { .. } = kind {
363                         self.check_op(ops::MutBorrow);
364                     } else {
365                         self.check_op(ops::CellBorrow);
366                     }
367                 }
368             }
369
370             Rvalue::AddressOf(Mutability::Mut, _) => self.check_op(ops::MutAddressOf),
371
372             Rvalue::Ref(_, BorrowKind::Shared, ref place)
373             | Rvalue::Ref(_, BorrowKind::Shallow, ref place) => {
374                 self.check_immutable_borrow_like(location, place)
375             }
376
377             Rvalue::AddressOf(Mutability::Not, ref place) => {
378                 self.check_immutable_borrow_like(location, place)
379             }
380
381             Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
382                 let operand_ty = operand.ty(*self.body, self.tcx);
383                 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
384                 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
385
386                 if let (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) =
387                     (cast_in, cast_out)
388                 {
389                     self.check_op(ops::RawPtrToIntCast);
390                 }
391             }
392
393             Rvalue::BinaryOp(op, ref lhs, _) => {
394                 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(*self.body, self.tcx).kind {
395                     assert!(
396                         op == BinOp::Eq
397                             || op == BinOp::Ne
398                             || op == BinOp::Le
399                             || op == BinOp::Lt
400                             || op == BinOp::Ge
401                             || op == BinOp::Gt
402                             || op == BinOp::Offset
403                     );
404
405                     self.check_op(ops::RawPtrComparison);
406                 }
407             }
408
409             Rvalue::NullaryOp(NullOp::Box, _) => {
410                 self.check_op(ops::HeapAllocation);
411             }
412         }
413     }
414
415     fn visit_place_base(
416         &mut self,
417         place_base: &PlaceBase,
418         context: PlaceContext,
419         location: Location,
420     ) {
421         trace!(
422             "visit_place_base: place_base={:?} context={:?} location={:?}",
423             place_base,
424             context,
425             location,
426         );
427         self.super_place_base(place_base, context, location);
428
429         match place_base {
430             PlaceBase::Local(_) => {}
431         }
432     }
433
434     fn visit_operand(&mut self, op: &Operand<'tcx>, location: Location) {
435         self.super_operand(op, location);
436         if let Operand::Constant(c) = op {
437             if let Some(def_id) = c.check_static_ptr(self.tcx) {
438                 self.check_static(def_id, self.span);
439             }
440         }
441     }
442     fn visit_projection_elem(
443         &mut self,
444         place_base: &PlaceBase,
445         proj_base: &[PlaceElem<'tcx>],
446         elem: &PlaceElem<'tcx>,
447         context: PlaceContext,
448         location: Location,
449     ) {
450         trace!(
451             "visit_projection_elem: place_base={:?} proj_base={:?} elem={:?} \
452             context={:?} location={:?}",
453             place_base,
454             proj_base,
455             elem,
456             context,
457             location,
458         );
459
460         self.super_projection_elem(place_base, proj_base, elem, context, location);
461
462         match elem {
463             ProjectionElem::Deref => {
464                 let base_ty = Place::ty_from(place_base, proj_base, *self.body, self.tcx).ty;
465                 if let ty::RawPtr(_) = base_ty.kind {
466                     if proj_base.is_empty() {
467                         if let (PlaceBase::Local(local), []) = (place_base, proj_base) {
468                             let decl = &self.body.local_decls[*local];
469                             if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
470                                 let span = decl.source_info.span;
471                                 self.check_static(def_id, span);
472                                 return;
473                             }
474                         }
475                     }
476                     self.check_op(ops::RawPtrDeref);
477                 }
478
479                 if context.is_mutating_use() {
480                     self.check_op(ops::MutDeref);
481                 }
482             }
483
484             ProjectionElem::ConstantIndex { .. }
485             | ProjectionElem::Subslice { .. }
486             | ProjectionElem::Field(..)
487             | ProjectionElem::Index(_) => {
488                 let base_ty = Place::ty_from(place_base, proj_base, *self.body, self.tcx).ty;
489                 match base_ty.ty_adt_def() {
490                     Some(def) if def.is_union() => {
491                         self.check_op(ops::UnionAccess);
492                     }
493
494                     _ => {}
495                 }
496             }
497
498             ProjectionElem::Downcast(..) => {
499                 self.check_op(ops::Downcast);
500             }
501         }
502     }
503
504     fn visit_source_info(&mut self, source_info: &SourceInfo) {
505         trace!("visit_source_info: source_info={:?}", source_info);
506         self.span = source_info.span;
507     }
508
509     fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
510         trace!("visit_statement: statement={:?} location={:?}", statement, location);
511
512         match statement.kind {
513             StatementKind::Assign(..) | StatementKind::SetDiscriminant { .. } => {
514                 self.super_statement(statement, location);
515             }
516             StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => {
517                 self.check_op(ops::IfOrMatch);
518             }
519             // FIXME(eddyb) should these really do nothing?
520             StatementKind::FakeRead(..)
521             | StatementKind::StorageLive(_)
522             | StatementKind::StorageDead(_)
523             | StatementKind::InlineAsm { .. }
524             | StatementKind::Retag { .. }
525             | StatementKind::AscribeUserType(..)
526             | StatementKind::Nop => {}
527         }
528     }
529
530     fn visit_terminator_kind(&mut self, kind: &TerminatorKind<'tcx>, location: Location) {
531         trace!("visit_terminator_kind: kind={:?} location={:?}", kind, location);
532         self.super_terminator_kind(kind, location);
533
534         match kind {
535             TerminatorKind::Call { func, .. } => {
536                 let fn_ty = func.ty(*self.body, self.tcx);
537
538                 let def_id = match fn_ty.kind {
539                     ty::FnDef(def_id, _) => def_id,
540
541                     ty::FnPtr(_) => {
542                         self.check_op(ops::FnCallIndirect);
543                         return;
544                     }
545                     _ => {
546                         self.check_op(ops::FnCallOther);
547                         return;
548                     }
549                 };
550
551                 // At this point, we are calling a function whose `DefId` is known...
552                 if is_const_fn(self.tcx, def_id) {
553                     return;
554                 }
555
556                 if is_lang_panic_fn(self.tcx, def_id) {
557                     self.check_op(ops::Panic);
558                 } else if let Some(feature) = is_unstable_const_fn(self.tcx, def_id) {
559                     // Exempt unstable const fns inside of macros with
560                     // `#[allow_internal_unstable]`.
561                     if !self.span.allows_unstable(feature) {
562                         self.check_op(ops::FnCallUnstable(def_id, feature));
563                     }
564                 } else {
565                     self.check_op(ops::FnCallNonConst(def_id));
566                 }
567             }
568
569             // Forbid all `Drop` terminators unless the place being dropped is a local with no
570             // projections that cannot be `NeedsDrop`.
571             TerminatorKind::Drop { location: dropped_place, .. }
572             | TerminatorKind::DropAndReplace { location: dropped_place, .. } => {
573                 let mut err_span = self.span;
574
575                 // Check to see if the type of this place can ever have a drop impl. If not, this
576                 // `Drop` terminator is frivolous.
577                 let ty_needs_drop =
578                     dropped_place.ty(*self.body, self.tcx).ty.needs_drop(self.tcx, self.param_env);
579
580                 if !ty_needs_drop {
581                     return;
582                 }
583
584                 let needs_drop = if let Some(local) = dropped_place.as_local() {
585                     // Use the span where the local was declared as the span of the drop error.
586                     err_span = self.body.local_decls[local].source_info.span;
587                     self.qualifs.needs_drop_lazy_seek(local, location)
588                 } else {
589                     true
590                 };
591
592                 if needs_drop {
593                     self.check_op_spanned(ops::LiveDrop, err_span);
594                 }
595             }
596
597             _ => {}
598         }
599     }
600 }
601
602 fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: Span, msg: Cow<'_, str>) {
603     struct_span_err!(tcx.sess, span, E0723, "{}", msg)
604         .note("for more information, see issue https://github.com/rust-lang/rust/issues/57563")
605         .help("add `#![feature(const_fn)]` to the crate attributes to enable")
606         .emit();
607 }
608
609 fn check_short_circuiting_in_const_local(item: &Item<'_, 'tcx>) {
610     let body = item.body;
611
612     if body.control_flow_destroyed.is_empty() {
613         return;
614     }
615
616     let mut locals = body.vars_iter();
617     if let Some(local) = locals.next() {
618         let span = body.local_decls[local].source_info.span;
619         let mut error = item.tcx.sess.struct_span_err(
620             span,
621             &format!(
622                 "new features like let bindings are not permitted in {}s \
623                 which also use short circuiting operators",
624                 item.const_kind(),
625             ),
626         );
627         for (span, kind) in body.control_flow_destroyed.iter() {
628             error.span_note(
629                 *span,
630                 &format!(
631                     "use of {} here does not actually short circuit due to \
632                 the const evaluator presently not being able to do control flow. \
633                 See https://github.com/rust-lang/rust/issues/49146 for more \
634                 information.",
635                     kind
636                 ),
637             );
638         }
639         for local in locals {
640             let span = body.local_decls[local].source_info.span;
641             error.span_note(span, "more locals defined here");
642         }
643         error.emit();
644     }
645 }
646
647 fn check_return_ty_is_sync(tcx: TyCtxt<'tcx>, body: &Body<'tcx>, hir_id: HirId) {
648     let ty = body.return_ty();
649     tcx.infer_ctxt().enter(|infcx| {
650         let cause = traits::ObligationCause::new(body.span, hir_id, traits::SharedStatic);
651         let mut fulfillment_cx = traits::FulfillmentContext::new();
652         let sync_def_id = tcx.require_lang_item(lang_items::SyncTraitLangItem, Some(body.span));
653         fulfillment_cx.register_bound(&infcx, ty::ParamEnv::empty(), ty, sync_def_id, cause);
654         if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) {
655             infcx.report_fulfillment_errors(&err, None, false);
656         }
657     });
658 }
659
660 fn place_as_reborrow(
661     tcx: TyCtxt<'tcx>,
662     body: &Body<'tcx>,
663     place: &'a Place<'tcx>,
664 ) -> Option<&'a [PlaceElem<'tcx>]> {
665     place.projection.split_last().and_then(|(outermost, inner)| {
666         if outermost != &ProjectionElem::Deref {
667             return None;
668         }
669
670         // A borrow of a `static` also looks like `&(*_1)` in the MIR, but `_1` is a `const`
671         // that points to the allocation for the static. Don't treat these as reborrows.
672         match place.base {
673             PlaceBase::Local(local) => {
674                 if body.local_decls[local].is_ref_to_static() {
675                     return None;
676                 }
677             }
678         }
679
680         // Ensure the type being derefed is a reference and not a raw pointer.
681         //
682         // This is sufficient to prevent an access to a `static mut` from being marked as a
683         // reborrow, even if the check above were to disappear.
684         let inner_ty = Place::ty_from(&place.base, inner, body, tcx).ty;
685         match inner_ty.kind {
686             ty::Ref(..) => Some(inner),
687             _ => None,
688         }
689     })
690 }