]> git.lizzy.rs Git - rust.git/blob - compiler/rustc_mir_transform/src/check_unsafety.rs
Add new `Deinit` statement kind
[rust.git] / compiler / rustc_mir_transform / src / check_unsafety.rs
1 use rustc_data_structures::fx::FxHashMap;
2 use rustc_errors::struct_span_err;
3 use rustc_hir as hir;
4 use rustc_hir::def_id::{DefId, LocalDefId};
5 use rustc_hir::hir_id::HirId;
6 use rustc_hir::intravisit;
7 use rustc_middle::mir::visit::{MutatingUseContext, PlaceContext, Visitor};
8 use rustc_middle::ty::query::Providers;
9 use rustc_middle::ty::{self, TyCtxt};
10 use rustc_middle::{lint, mir::*};
11 use rustc_session::lint::builtin::{UNSAFE_OP_IN_UNSAFE_FN, UNUSED_UNSAFE};
12 use rustc_session::lint::Level;
13
14 use std::collections::hash_map;
15 use std::ops::Bound;
16
17 pub struct UnsafetyChecker<'a, 'tcx> {
18     body: &'a Body<'tcx>,
19     body_did: LocalDefId,
20     violations: Vec<UnsafetyViolation>,
21     source_info: SourceInfo,
22     tcx: TyCtxt<'tcx>,
23     param_env: ty::ParamEnv<'tcx>,
24
25     /// Used `unsafe` blocks in this function. This is used for the "unused_unsafe" lint.
26     ///
27     /// The keys are the used `unsafe` blocks, the UnusedUnsafeKind indicates whether
28     /// or not any of the usages happen at a place that doesn't allow `unsafe_op_in_unsafe_fn`.
29     used_unsafe_blocks: FxHashMap<HirId, UsedUnsafeBlockData>,
30 }
31
32 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
33     fn new(
34         body: &'a Body<'tcx>,
35         body_did: LocalDefId,
36         tcx: TyCtxt<'tcx>,
37         param_env: ty::ParamEnv<'tcx>,
38     ) -> Self {
39         Self {
40             body,
41             body_did,
42             violations: vec![],
43             source_info: SourceInfo::outermost(body.span),
44             tcx,
45             param_env,
46             used_unsafe_blocks: Default::default(),
47         }
48     }
49 }
50
51 impl<'tcx> Visitor<'tcx> for UnsafetyChecker<'_, 'tcx> {
52     fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
53         self.source_info = terminator.source_info;
54         match terminator.kind {
55             TerminatorKind::Goto { .. }
56             | TerminatorKind::SwitchInt { .. }
57             | TerminatorKind::Drop { .. }
58             | TerminatorKind::Yield { .. }
59             | TerminatorKind::Assert { .. }
60             | TerminatorKind::DropAndReplace { .. }
61             | TerminatorKind::GeneratorDrop
62             | TerminatorKind::Resume
63             | TerminatorKind::Abort
64             | TerminatorKind::Return
65             | TerminatorKind::Unreachable
66             | TerminatorKind::FalseEdge { .. }
67             | TerminatorKind::FalseUnwind { .. } => {
68                 // safe (at least as emitted during MIR construction)
69             }
70
71             TerminatorKind::Call { ref func, .. } => {
72                 let func_ty = func.ty(self.body, self.tcx);
73                 let sig = func_ty.fn_sig(self.tcx);
74                 if let hir::Unsafety::Unsafe = sig.unsafety() {
75                     self.require_unsafe(
76                         UnsafetyViolationKind::General,
77                         UnsafetyViolationDetails::CallToUnsafeFunction,
78                     )
79                 }
80
81                 if let ty::FnDef(func_id, _) = func_ty.kind() {
82                     self.check_target_features(*func_id);
83                 }
84             }
85
86             TerminatorKind::InlineAsm { .. } => self.require_unsafe(
87                 UnsafetyViolationKind::General,
88                 UnsafetyViolationDetails::UseOfInlineAssembly,
89             ),
90         }
91         self.super_terminator(terminator, location);
92     }
93
94     fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
95         self.source_info = statement.source_info;
96         match statement.kind {
97             StatementKind::Assign(..)
98             | StatementKind::FakeRead(..)
99             | StatementKind::SetDiscriminant { .. }
100             | StatementKind::Deinit(..)
101             | StatementKind::StorageLive(..)
102             | StatementKind::StorageDead(..)
103             | StatementKind::Retag { .. }
104             | StatementKind::AscribeUserType(..)
105             | StatementKind::Coverage(..)
106             | StatementKind::Nop => {
107                 // safe (at least as emitted during MIR construction)
108             }
109
110             StatementKind::CopyNonOverlapping(..) => unreachable!(),
111         }
112         self.super_statement(statement, location);
113     }
114
115     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
116         match rvalue {
117             Rvalue::Aggregate(box ref aggregate, _) => match aggregate {
118                 &AggregateKind::Array(..) | &AggregateKind::Tuple => {}
119                 &AggregateKind::Adt(adt_did, ..) => {
120                     match self.tcx.layout_scalar_valid_range(adt_did) {
121                         (Bound::Unbounded, Bound::Unbounded) => {}
122                         _ => self.require_unsafe(
123                             UnsafetyViolationKind::General,
124                             UnsafetyViolationDetails::InitializingTypeWith,
125                         ),
126                     }
127                 }
128                 &AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
129                     let UnsafetyCheckResult { violations, used_unsafe_blocks, .. } =
130                         self.tcx.unsafety_check_result(def_id.expect_local());
131                     self.register_violations(
132                         violations,
133                         used_unsafe_blocks.iter().map(|(&h, &d)| (h, d)),
134                     );
135                 }
136             },
137             _ => {}
138         }
139         self.super_rvalue(rvalue, location);
140     }
141
142     fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
143         // On types with `scalar_valid_range`, prevent
144         // * `&mut x.field`
145         // * `x.field = y;`
146         // * `&x.field` if `field`'s type has interior mutability
147         // because either of these would allow modifying the layout constrained field and
148         // insert values that violate the layout constraints.
149         if context.is_mutating_use() || context.is_borrow() {
150             self.check_mut_borrowing_layout_constrained_field(*place, context.is_mutating_use());
151         }
152
153         // Some checks below need the extra meta info of the local declaration.
154         let decl = &self.body.local_decls[place.local];
155
156         // Check the base local: it might be an unsafe-to-access static. We only check derefs of the
157         // temporary holding the static pointer to avoid duplicate errors
158         // <https://github.com/rust-lang/rust/pull/78068#issuecomment-731753506>.
159         if decl.internal && place.projection.first() == Some(&ProjectionElem::Deref) {
160             // If the projection root is an artificial local that we introduced when
161             // desugaring `static`, give a more specific error message
162             // (avoid the general "raw pointer" clause below, that would only be confusing).
163             if let Some(box LocalInfo::StaticRef { def_id, .. }) = decl.local_info {
164                 if self.tcx.is_mutable_static(def_id) {
165                     self.require_unsafe(
166                         UnsafetyViolationKind::General,
167                         UnsafetyViolationDetails::UseOfMutableStatic,
168                     );
169                     return;
170                 } else if self.tcx.is_foreign_item(def_id) {
171                     self.require_unsafe(
172                         UnsafetyViolationKind::General,
173                         UnsafetyViolationDetails::UseOfExternStatic,
174                     );
175                     return;
176                 }
177             }
178         }
179
180         // Check for raw pointer `Deref`.
181         for (base, proj) in place.iter_projections() {
182             if proj == ProjectionElem::Deref {
183                 let base_ty = base.ty(self.body, self.tcx).ty;
184                 if base_ty.is_unsafe_ptr() {
185                     self.require_unsafe(
186                         UnsafetyViolationKind::General,
187                         UnsafetyViolationDetails::DerefOfRawPointer,
188                     )
189                 }
190             }
191         }
192
193         // Check for union fields. For this we traverse right-to-left, as the last `Deref` changes
194         // whether we *read* the union field or potentially *write* to it (if this place is being assigned to).
195         let mut saw_deref = false;
196         for (base, proj) in place.iter_projections().rev() {
197             if proj == ProjectionElem::Deref {
198                 saw_deref = true;
199                 continue;
200             }
201
202             let base_ty = base.ty(self.body, self.tcx).ty;
203             if base_ty.is_union() {
204                 // If we did not hit a `Deref` yet and the overall place use is an assignment, the
205                 // rules are different.
206                 let assign_to_field = !saw_deref
207                     && matches!(
208                         context,
209                         PlaceContext::MutatingUse(
210                             MutatingUseContext::Store
211                                 | MutatingUseContext::Drop
212                                 | MutatingUseContext::AsmOutput
213                         )
214                     );
215                 // If this is just an assignment, determine if the assigned type needs dropping.
216                 if assign_to_field {
217                     // We have to check the actual type of the assignment, as that determines if the
218                     // old value is being dropped.
219                     let assigned_ty = place.ty(&self.body.local_decls, self.tcx).ty;
220                     // To avoid semver hazard, we only consider `Copy` and `ManuallyDrop` non-dropping.
221                     let manually_drop = assigned_ty
222                         .ty_adt_def()
223                         .map_or(false, |adt_def| adt_def.is_manually_drop());
224                     let nodrop = manually_drop
225                         || assigned_ty.is_copy_modulo_regions(
226                             self.tcx.at(self.source_info.span),
227                             self.param_env,
228                         );
229                     if !nodrop {
230                         self.require_unsafe(
231                             UnsafetyViolationKind::General,
232                             UnsafetyViolationDetails::AssignToDroppingUnionField,
233                         );
234                     } else {
235                         // write to non-drop union field, safe
236                     }
237                 } else {
238                     self.require_unsafe(
239                         UnsafetyViolationKind::General,
240                         UnsafetyViolationDetails::AccessToUnionField,
241                     )
242                 }
243             }
244         }
245     }
246 }
247
248 impl<'tcx> UnsafetyChecker<'_, 'tcx> {
249     fn require_unsafe(&mut self, kind: UnsafetyViolationKind, details: UnsafetyViolationDetails) {
250         // Violations can turn out to be `UnsafeFn` during analysis, but they should not start out as such.
251         assert_ne!(kind, UnsafetyViolationKind::UnsafeFn);
252
253         let source_info = self.source_info;
254         let lint_root = self.body.source_scopes[self.source_info.scope]
255             .local_data
256             .as_ref()
257             .assert_crate_local()
258             .lint_root;
259         self.register_violations(
260             [&UnsafetyViolation { source_info, lint_root, kind, details }],
261             [],
262         );
263     }
264
265     fn register_violations<'a>(
266         &mut self,
267         violations: impl IntoIterator<Item = &'a UnsafetyViolation>,
268         new_used_unsafe_blocks: impl IntoIterator<Item = (HirId, UsedUnsafeBlockData)>,
269     ) {
270         use UsedUnsafeBlockData::{AllAllowedInUnsafeFn, SomeDisallowedInUnsafeFn};
271
272         let update_entry = |this: &mut Self, hir_id, new_usage| {
273             match this.used_unsafe_blocks.entry(hir_id) {
274                 hash_map::Entry::Occupied(mut entry) => {
275                     if new_usage == SomeDisallowedInUnsafeFn {
276                         *entry.get_mut() = SomeDisallowedInUnsafeFn;
277                     }
278                 }
279                 hash_map::Entry::Vacant(entry) => {
280                     entry.insert(new_usage);
281                 }
282             };
283         };
284         let safety = self.body.source_scopes[self.source_info.scope]
285             .local_data
286             .as_ref()
287             .assert_crate_local()
288             .safety;
289         match safety {
290             // `unsafe` blocks are required in safe code
291             Safety::Safe => violations.into_iter().for_each(|&violation| {
292                 match violation.kind {
293                     UnsafetyViolationKind::General => {}
294                     UnsafetyViolationKind::UnsafeFn => {
295                         bug!("`UnsafetyViolationKind::UnsafeFn` in an `Safe` context")
296                     }
297                 }
298                 if !self.violations.contains(&violation) {
299                     self.violations.push(violation)
300                 }
301             }),
302             // With the RFC 2585, no longer allow `unsafe` operations in `unsafe fn`s
303             Safety::FnUnsafe => violations.into_iter().for_each(|&(mut violation)| {
304                 violation.kind = UnsafetyViolationKind::UnsafeFn;
305                 if !self.violations.contains(&violation) {
306                     self.violations.push(violation)
307                 }
308             }),
309             Safety::BuiltinUnsafe => {}
310             Safety::ExplicitUnsafe(hir_id) => violations.into_iter().for_each(|violation| {
311                 update_entry(
312                     self,
313                     hir_id,
314                     match self.tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, violation.lint_root).0
315                     {
316                         Level::Allow => AllAllowedInUnsafeFn(violation.lint_root),
317                         _ => SomeDisallowedInUnsafeFn,
318                     },
319                 )
320             }),
321         };
322
323         new_used_unsafe_blocks
324             .into_iter()
325             .for_each(|(hir_id, usage_data)| update_entry(self, hir_id, usage_data));
326     }
327     fn check_mut_borrowing_layout_constrained_field(
328         &mut self,
329         place: Place<'tcx>,
330         is_mut_use: bool,
331     ) {
332         for (place_base, elem) in place.iter_projections().rev() {
333             match elem {
334                 // Modifications behind a dereference don't affect the value of
335                 // the pointer.
336                 ProjectionElem::Deref => return,
337                 ProjectionElem::Field(..) => {
338                     let ty = place_base.ty(&self.body.local_decls, self.tcx).ty;
339                     if let ty::Adt(def, _) = ty.kind() {
340                         if self.tcx.layout_scalar_valid_range(def.did())
341                             != (Bound::Unbounded, Bound::Unbounded)
342                         {
343                             let details = if is_mut_use {
344                                 UnsafetyViolationDetails::MutationOfLayoutConstrainedField
345
346                             // Check `is_freeze` as late as possible to avoid cycle errors
347                             // with opaque types.
348                             } else if !place
349                                 .ty(self.body, self.tcx)
350                                 .ty
351                                 .is_freeze(self.tcx.at(self.source_info.span), self.param_env)
352                             {
353                                 UnsafetyViolationDetails::BorrowOfLayoutConstrainedField
354                             } else {
355                                 continue;
356                             };
357                             self.require_unsafe(UnsafetyViolationKind::General, details);
358                         }
359                     }
360                 }
361                 _ => {}
362             }
363         }
364     }
365
366     /// Checks whether calling `func_did` needs an `unsafe` context or not, i.e. whether
367     /// the called function has target features the calling function hasn't.
368     fn check_target_features(&mut self, func_did: DefId) {
369         // Unsafety isn't required on wasm targets. For more information see
370         // the corresponding check in typeck/src/collect.rs
371         if self.tcx.sess.target.options.is_like_wasm {
372             return;
373         }
374
375         let callee_features = &self.tcx.codegen_fn_attrs(func_did).target_features;
376         let self_features = &self.tcx.codegen_fn_attrs(self.body_did).target_features;
377
378         // Is `callee_features` a subset of `calling_features`?
379         if !callee_features.iter().all(|feature| self_features.contains(feature)) {
380             self.require_unsafe(
381                 UnsafetyViolationKind::General,
382                 UnsafetyViolationDetails::CallToFunctionWith,
383             )
384         }
385     }
386 }
387
388 pub(crate) fn provide(providers: &mut Providers) {
389     *providers = Providers {
390         unsafety_check_result: |tcx, def_id| {
391             if let Some(def) = ty::WithOptConstParam::try_lookup(def_id, tcx) {
392                 tcx.unsafety_check_result_for_const_arg(def)
393             } else {
394                 unsafety_check_result(tcx, ty::WithOptConstParam::unknown(def_id))
395             }
396         },
397         unsafety_check_result_for_const_arg: |tcx, (did, param_did)| {
398             unsafety_check_result(
399                 tcx,
400                 ty::WithOptConstParam { did, const_param_did: Some(param_did) },
401             )
402         },
403         ..*providers
404     };
405 }
406
407 /// Context information for [`UnusedUnsafeVisitor`] traversal,
408 /// saves (innermost) relevant context
409 #[derive(Copy, Clone, Debug)]
410 enum Context {
411     Safe,
412     /// in an `unsafe fn`
413     UnsafeFn(HirId),
414     /// in a *used* `unsafe` block
415     /// (i.e. a block without unused-unsafe warning)
416     UnsafeBlock(HirId),
417 }
418
419 struct UnusedUnsafeVisitor<'a, 'tcx> {
420     tcx: TyCtxt<'tcx>,
421     used_unsafe_blocks: &'a FxHashMap<HirId, UsedUnsafeBlockData>,
422     context: Context,
423     unused_unsafes: &'a mut Vec<(HirId, UnusedUnsafe)>,
424 }
425
426 impl<'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'_, 'tcx> {
427     fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
428         use UsedUnsafeBlockData::{AllAllowedInUnsafeFn, SomeDisallowedInUnsafeFn};
429
430         if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
431             let used = match self.tcx.lint_level_at_node(UNUSED_UNSAFE, block.hir_id) {
432                 (Level::Allow, _) => Some(SomeDisallowedInUnsafeFn),
433                 _ => self.used_unsafe_blocks.get(&block.hir_id).copied(),
434             };
435             let unused_unsafe = match (self.context, used) {
436                 (_, None) => UnusedUnsafe::Unused,
437                 (Context::Safe, Some(_))
438                 | (Context::UnsafeFn(_), Some(SomeDisallowedInUnsafeFn)) => {
439                     let previous_context = self.context;
440                     self.context = Context::UnsafeBlock(block.hir_id);
441                     intravisit::walk_block(self, block);
442                     self.context = previous_context;
443                     return;
444                 }
445                 (Context::UnsafeFn(hir_id), Some(AllAllowedInUnsafeFn(lint_root))) => {
446                     UnusedUnsafe::InUnsafeFn(hir_id, lint_root)
447                 }
448                 (Context::UnsafeBlock(hir_id), Some(_)) => UnusedUnsafe::InUnsafeBlock(hir_id),
449             };
450             self.unused_unsafes.push((block.hir_id, unused_unsafe));
451         }
452         intravisit::walk_block(self, block);
453     }
454
455     fn visit_fn(
456         &mut self,
457         fk: intravisit::FnKind<'tcx>,
458         _fd: &'tcx hir::FnDecl<'tcx>,
459         b: hir::BodyId,
460         _s: rustc_span::Span,
461         _id: HirId,
462     ) {
463         if matches!(fk, intravisit::FnKind::Closure) {
464             self.visit_body(self.tcx.hir().body(b))
465         }
466     }
467 }
468
469 fn check_unused_unsafe(
470     tcx: TyCtxt<'_>,
471     def_id: LocalDefId,
472     used_unsafe_blocks: &FxHashMap<HirId, UsedUnsafeBlockData>,
473 ) -> Vec<(HirId, UnusedUnsafe)> {
474     let hir_id = tcx.hir().local_def_id_to_hir_id(def_id);
475     let body_id = tcx.hir().maybe_body_owned_by(hir_id);
476
477     let Some(body_id) = body_id else {
478         debug!("check_unused_unsafe({:?}) - no body found", def_id);
479         return vec![];
480     };
481     let body = tcx.hir().body(body_id);
482
483     let context = match tcx.hir().fn_sig_by_hir_id(hir_id) {
484         Some(sig) if sig.header.unsafety == hir::Unsafety::Unsafe => Context::UnsafeFn(hir_id),
485         _ => Context::Safe,
486     };
487
488     debug!(
489         "check_unused_unsafe({:?}, context={:?}, body={:?}, used_unsafe_blocks={:?})",
490         def_id, body, context, used_unsafe_blocks
491     );
492
493     let mut unused_unsafes = vec![];
494
495     let mut visitor = UnusedUnsafeVisitor {
496         tcx,
497         used_unsafe_blocks,
498         context,
499         unused_unsafes: &mut unused_unsafes,
500     };
501     intravisit::Visitor::visit_body(&mut visitor, body);
502
503     unused_unsafes
504 }
505
506 fn unsafety_check_result<'tcx>(
507     tcx: TyCtxt<'tcx>,
508     def: ty::WithOptConstParam<LocalDefId>,
509 ) -> &'tcx UnsafetyCheckResult {
510     debug!("unsafety_violations({:?})", def);
511
512     // N.B., this borrow is valid because all the consumers of
513     // `mir_built` force this.
514     let body = &tcx.mir_built(def).borrow();
515
516     let param_env = tcx.param_env(def.did);
517
518     let mut checker = UnsafetyChecker::new(body, def.did, tcx, param_env);
519     checker.visit_body(&body);
520
521     let unused_unsafes = (!tcx.is_closure(def.did.to_def_id()))
522         .then(|| check_unused_unsafe(tcx, def.did, &checker.used_unsafe_blocks));
523
524     tcx.arena.alloc(UnsafetyCheckResult {
525         violations: checker.violations,
526         used_unsafe_blocks: checker.used_unsafe_blocks,
527         unused_unsafes,
528     })
529 }
530
531 fn report_unused_unsafe(tcx: TyCtxt<'_>, kind: UnusedUnsafe, id: HirId) {
532     let span = tcx.sess.source_map().guess_head_span(tcx.hir().span(id));
533     tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, |lint| {
534         let msg = "unnecessary `unsafe` block";
535         let mut db = lint.build(msg);
536         db.span_label(span, msg);
537         match kind {
538             UnusedUnsafe::Unused => {}
539             UnusedUnsafe::InUnsafeBlock(id) => {
540                 db.span_label(
541                     tcx.sess.source_map().guess_head_span(tcx.hir().span(id)),
542                     format!("because it's nested under this `unsafe` block"),
543                 );
544             }
545             UnusedUnsafe::InUnsafeFn(id, usage_lint_root) => {
546                 db.span_label(
547                     tcx.sess.source_map().guess_head_span(tcx.hir().span(id)),
548                     format!("because it's nested under this `unsafe` fn"),
549                 )
550                 .note(
551                     "this `unsafe` block does contain unsafe operations, \
552                     but those are already allowed in an `unsafe fn`",
553                 );
554                 let (level, source) =
555                     tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, usage_lint_root);
556                 assert_eq!(level, Level::Allow);
557                 lint::explain_lint_level_source(
558                     UNSAFE_OP_IN_UNSAFE_FN,
559                     Level::Allow,
560                     source,
561                     &mut db,
562                 );
563             }
564         }
565
566         db.emit();
567     });
568 }
569
570 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: LocalDefId) {
571     debug!("check_unsafety({:?})", def_id);
572
573     // closures are handled by their parent fn.
574     if tcx.is_closure(def_id.to_def_id()) {
575         return;
576     }
577
578     let UnsafetyCheckResult { violations, unused_unsafes, .. } = tcx.unsafety_check_result(def_id);
579
580     for &UnsafetyViolation { source_info, lint_root, kind, details } in violations.iter() {
581         let (description, note) = details.description_and_note();
582
583         // Report an error.
584         let unsafe_fn_msg =
585             if unsafe_op_in_unsafe_fn_allowed(tcx, lint_root) { " function or" } else { "" };
586
587         match kind {
588             UnsafetyViolationKind::General => {
589                 // once
590                 struct_span_err!(
591                     tcx.sess,
592                     source_info.span,
593                     E0133,
594                     "{} is unsafe and requires unsafe{} block",
595                     description,
596                     unsafe_fn_msg,
597                 )
598                 .span_label(source_info.span, description)
599                 .note(note)
600                 .emit();
601             }
602             UnsafetyViolationKind::UnsafeFn => tcx.struct_span_lint_hir(
603                 UNSAFE_OP_IN_UNSAFE_FN,
604                 lint_root,
605                 source_info.span,
606                 |lint| {
607                     lint.build(&format!(
608                         "{} is unsafe and requires unsafe block (error E0133)",
609                         description,
610                     ))
611                     .span_label(source_info.span, description)
612                     .note(note)
613                     .emit();
614                 },
615             ),
616         }
617     }
618
619     for &(block_id, kind) in unused_unsafes.as_ref().unwrap() {
620         report_unused_unsafe(tcx, kind, block_id);
621     }
622 }
623
624 fn unsafe_op_in_unsafe_fn_allowed(tcx: TyCtxt<'_>, id: HirId) -> bool {
625     tcx.lint_level_at_node(UNSAFE_OP_IN_UNSAFE_FN, id).0 == Level::Allow
626 }