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