]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/check_unsafety.rs
Rollup merge of #67884 - anp:allow-unused-const-attr, r=oli-obk
[rust.git] / src / librustc_mir / transform / check_unsafety.rs
1 use rustc::hir::intravisit;
2 use rustc::lint::builtin::{SAFE_PACKED_BORROWS, UNUSED_UNSAFE};
3 use rustc::mir::visit::{MutatingUseContext, PlaceContext, Visitor};
4 use rustc::mir::*;
5 use rustc::ty::cast::CastTy;
6 use rustc::ty::query::Providers;
7 use rustc::ty::{self, TyCtxt};
8 use rustc_data_structures::fx::FxHashSet;
9 use rustc_errors::struct_span_err;
10 use rustc_hir as hir;
11 use rustc_hir::def_id::DefId;
12 use rustc_hir::Node;
13 use rustc_span::symbol::{sym, Symbol};
14
15 use std::ops::Bound;
16
17 use crate::const_eval::{is_const_fn, is_min_const_fn};
18 use crate::util;
19
20 use rustc_error_codes::*;
21
22 pub struct UnsafetyChecker<'a, 'tcx> {
23     body: &'a Body<'tcx>,
24     const_context: bool,
25     min_const_fn: bool,
26     violations: Vec<UnsafetyViolation>,
27     source_info: SourceInfo,
28     tcx: TyCtxt<'tcx>,
29     param_env: ty::ParamEnv<'tcx>,
30     /// Mark an `unsafe` block as used, so we don't lint it.
31     used_unsafe: FxHashSet<hir::HirId>,
32     inherited_blocks: Vec<(hir::HirId, bool)>,
33 }
34
35 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
36     fn new(
37         const_context: bool,
38         min_const_fn: bool,
39         body: &'a Body<'tcx>,
40         tcx: TyCtxt<'tcx>,
41         param_env: ty::ParamEnv<'tcx>,
42     ) -> Self {
43         // sanity check
44         if min_const_fn {
45             assert!(const_context);
46         }
47         Self {
48             body,
49             const_context,
50             min_const_fn,
51             violations: vec![],
52             source_info: SourceInfo { span: body.span, scope: OUTERMOST_SOURCE_SCOPE },
53             tcx,
54             param_env,
55             used_unsafe: Default::default(),
56             inherited_blocks: vec![],
57         }
58     }
59 }
60
61 impl<'a, 'tcx> Visitor<'tcx> for UnsafetyChecker<'a, 'tcx> {
62     fn visit_terminator(&mut self, terminator: &Terminator<'tcx>, location: Location) {
63         self.source_info = terminator.source_info;
64         match terminator.kind {
65             TerminatorKind::Goto { .. }
66             | TerminatorKind::SwitchInt { .. }
67             | TerminatorKind::Drop { .. }
68             | TerminatorKind::Yield { .. }
69             | TerminatorKind::Assert { .. }
70             | TerminatorKind::DropAndReplace { .. }
71             | TerminatorKind::GeneratorDrop
72             | TerminatorKind::Resume
73             | TerminatorKind::Abort
74             | TerminatorKind::Return
75             | TerminatorKind::Unreachable
76             | TerminatorKind::FalseEdges { .. }
77             | TerminatorKind::FalseUnwind { .. } => {
78                 // safe (at least as emitted during MIR construction)
79             }
80
81             TerminatorKind::Call { ref func, .. } => {
82                 let func_ty = func.ty(self.body, self.tcx);
83                 let sig = func_ty.fn_sig(self.tcx);
84                 if let hir::Unsafety::Unsafe = sig.unsafety() {
85                     self.require_unsafe(
86                         "call to unsafe function",
87                         "consult the function's documentation for information on how to avoid \
88                          undefined behavior",
89                         UnsafetyViolationKind::GeneralAndConstFn,
90                     )
91                 }
92             }
93         }
94         self.super_terminator(terminator, location);
95     }
96
97     fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
98         self.source_info = statement.source_info;
99         match statement.kind {
100             StatementKind::Assign(..)
101             | StatementKind::FakeRead(..)
102             | StatementKind::SetDiscriminant { .. }
103             | StatementKind::StorageLive(..)
104             | StatementKind::StorageDead(..)
105             | StatementKind::Retag { .. }
106             | StatementKind::AscribeUserType(..)
107             | StatementKind::Nop => {
108                 // safe (at least as emitted during MIR construction)
109             }
110
111             StatementKind::InlineAsm { .. } => self.require_unsafe(
112                 "use of inline assembly",
113                 "inline assembly is entirely unchecked and can cause undefined behavior",
114                 UnsafetyViolationKind::General,
115             ),
116         }
117         self.super_statement(statement, location);
118     }
119
120     fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
121         match rvalue {
122             Rvalue::Aggregate(box ref aggregate, _) => match aggregate {
123                 &AggregateKind::Array(..) | &AggregateKind::Tuple => {}
124                 &AggregateKind::Adt(ref def, ..) => {
125                     match self.tcx.layout_scalar_valid_range(def.did) {
126                         (Bound::Unbounded, Bound::Unbounded) => {}
127                         _ => self.require_unsafe(
128                             "initializing type with `rustc_layout_scalar_valid_range` attr",
129                             "initializing a layout restricted type's field with a value \
130                                 outside the valid range is undefined behavior",
131                             UnsafetyViolationKind::GeneralAndConstFn,
132                         ),
133                     }
134                 }
135                 &AggregateKind::Closure(def_id, _) | &AggregateKind::Generator(def_id, _, _) => {
136                     let UnsafetyCheckResult { violations, unsafe_blocks } =
137                         self.tcx.unsafety_check_result(def_id);
138                     self.register_violations(&violations, &unsafe_blocks);
139                 }
140             },
141             // casting pointers to ints is unsafe in const fn because the const evaluator cannot
142             // possibly know what the result of various operations like `address / 2` would be
143             // pointers during const evaluation have no integral address, only an abstract one
144             Rvalue::Cast(CastKind::Misc, ref operand, cast_ty)
145                 if self.const_context && self.tcx.features().const_raw_ptr_to_usize_cast =>
146             {
147                 let operand_ty = operand.ty(self.body, self.tcx);
148                 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
149                 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
150                 match (cast_in, cast_out) {
151                     (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => {
152                         self.register_violations(
153                             &[UnsafetyViolation {
154                                 source_info: self.source_info,
155                                 description: Symbol::intern("cast of pointer to int"),
156                                 details: Symbol::intern(
157                                     "casting pointers to integers in constants",
158                                 ),
159                                 kind: UnsafetyViolationKind::General,
160                             }],
161                             &[],
162                         );
163                     }
164                     _ => {}
165                 }
166             }
167             // raw pointer and fn pointer operations are unsafe as it is not clear whether one
168             // pointer would be "less" or "equal" to another, because we cannot know where llvm
169             // or the linker will place various statics in memory. Without this information the
170             // result of a comparison of addresses would differ between runtime and compile-time.
171             Rvalue::BinaryOp(_, ref lhs, _)
172                 if self.const_context && self.tcx.features().const_compare_raw_pointers =>
173             {
174                 if let ty::RawPtr(_) | ty::FnPtr(..) = lhs.ty(self.body, self.tcx).kind {
175                     self.register_violations(
176                         &[UnsafetyViolation {
177                             source_info: self.source_info,
178                             description: Symbol::intern("pointer operation"),
179                             details: Symbol::intern("operations on pointers in constants"),
180                             kind: UnsafetyViolationKind::General,
181                         }],
182                         &[],
183                     );
184                 }
185             }
186             _ => {}
187         }
188         self.super_rvalue(rvalue, location);
189     }
190
191     fn visit_place(&mut self, place: &Place<'tcx>, context: PlaceContext, _location: Location) {
192         match place.base {
193             PlaceBase::Local(..) => {
194                 // Locals are safe.
195             }
196             PlaceBase::Static(box Static { kind: StaticKind::Promoted(_, _), .. }) => {
197                 bug!("unsafety checking should happen before promotion");
198             }
199             PlaceBase::Static(box Static { kind: StaticKind::Static, .. }) => {
200                 bug!("StaticKind::Static should not exist");
201             }
202         }
203
204         for (i, elem) in place.projection.iter().enumerate() {
205             let proj_base = &place.projection[..i];
206
207             if context.is_borrow() {
208                 if util::is_disaligned(self.tcx, self.body, self.param_env, place) {
209                     let source_info = self.source_info;
210                     let lint_root = self.body.source_scopes[source_info.scope]
211                         .local_data
212                         .as_ref()
213                         .assert_crate_local()
214                         .lint_root;
215                     self.register_violations(
216                         &[UnsafetyViolation {
217                             source_info,
218                             description: Symbol::intern("borrow of packed field"),
219                             details: Symbol::intern(
220                                 "fields of packed structs might be misaligned: dereferencing a \
221                             misaligned pointer or even just creating a misaligned reference \
222                             is undefined behavior",
223                             ),
224                             kind: UnsafetyViolationKind::BorrowPacked(lint_root),
225                         }],
226                         &[],
227                     );
228                 }
229             }
230             let is_borrow_of_interior_mut = context.is_borrow()
231                 && !Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty.is_freeze(
232                     self.tcx,
233                     self.param_env,
234                     self.source_info.span,
235                 );
236             // prevent
237             // * `&mut x.field`
238             // * `x.field = y;`
239             // * `&x.field` if `field`'s type has interior mutability
240             // because either of these would allow modifying the layout constrained field and
241             // insert values that violate the layout constraints.
242             if context.is_mutating_use() || is_borrow_of_interior_mut {
243                 self.check_mut_borrowing_layout_constrained_field(place, context.is_mutating_use());
244             }
245             let old_source_info = self.source_info;
246             if let (PlaceBase::Local(local), []) = (&place.base, proj_base) {
247                 let decl = &self.body.local_decls[*local];
248                 if decl.internal {
249                     // Internal locals are used in the `move_val_init` desugaring.
250                     // We want to check unsafety against the source info of the
251                     // desugaring, rather than the source info of the RHS.
252                     self.source_info = self.body.local_decls[*local].source_info;
253                 } else if let LocalInfo::StaticRef { def_id, .. } = decl.local_info {
254                     if self.tcx.is_mutable_static(def_id) {
255                         self.require_unsafe(
256                             "use of mutable static",
257                             "mutable statics can be mutated by multiple threads: aliasing \
258                         violations or data races will cause undefined behavior",
259                             UnsafetyViolationKind::General,
260                         );
261                         return;
262                     } else if self.tcx.is_foreign_item(def_id) {
263                         self.require_unsafe(
264                             "use of extern static",
265                             "extern statics are not controlled by the Rust type system: \
266                         invalid data, aliasing violations or data races will cause \
267                         undefined behavior",
268                             UnsafetyViolationKind::General,
269                         );
270                         return;
271                     }
272                 }
273             }
274             let base_ty = Place::ty_from(&place.base, proj_base, self.body, self.tcx).ty;
275             match base_ty.kind {
276                 ty::RawPtr(..) => self.require_unsafe(
277                     "dereference of raw pointer",
278                     "raw pointers may be NULL, dangling or unaligned; they can violate \
279                          aliasing rules and cause data races: all of these are undefined \
280                          behavior",
281                     UnsafetyViolationKind::General,
282                 ),
283                 ty::Adt(adt, _) => {
284                     if adt.is_union() {
285                         if context == PlaceContext::MutatingUse(MutatingUseContext::Store)
286                             || context == PlaceContext::MutatingUse(MutatingUseContext::Drop)
287                             || context == PlaceContext::MutatingUse(MutatingUseContext::AsmOutput)
288                         {
289                             let elem_ty = match elem {
290                                 ProjectionElem::Field(_, ty) => ty,
291                                 _ => span_bug!(
292                                     self.source_info.span,
293                                     "non-field projection {:?} from union?",
294                                     place
295                                 ),
296                             };
297                             if !elem_ty.is_copy_modulo_regions(
298                                 self.tcx,
299                                 self.param_env,
300                                 self.source_info.span,
301                             ) {
302                                 self.require_unsafe(
303                                     "assignment to non-`Copy` union field",
304                                     "the previous content of the field will be dropped, which \
305                                      causes undefined behavior if the field was not properly \
306                                      initialized",
307                                     UnsafetyViolationKind::GeneralAndConstFn,
308                                 )
309                             } else {
310                                 // write to non-move union, safe
311                             }
312                         } else {
313                             self.require_unsafe(
314                                 "access to union field",
315                                 "the field may not be properly initialized: using \
316                                  uninitialized data will cause undefined behavior",
317                                 UnsafetyViolationKind::GeneralAndConstFn,
318                             )
319                         }
320                     }
321                 }
322                 _ => {}
323             }
324             self.source_info = old_source_info;
325         }
326     }
327 }
328
329 impl<'a, 'tcx> UnsafetyChecker<'a, 'tcx> {
330     fn require_unsafe(
331         &mut self,
332         description: &'static str,
333         details: &'static str,
334         kind: UnsafetyViolationKind,
335     ) {
336         let source_info = self.source_info;
337         self.register_violations(
338             &[UnsafetyViolation {
339                 source_info,
340                 description: Symbol::intern(description),
341                 details: Symbol::intern(details),
342                 kind,
343             }],
344             &[],
345         );
346     }
347
348     fn register_violations(
349         &mut self,
350         violations: &[UnsafetyViolation],
351         unsafe_blocks: &[(hir::HirId, bool)],
352     ) {
353         let safety = self.body.source_scopes[self.source_info.scope]
354             .local_data
355             .as_ref()
356             .assert_crate_local()
357             .safety;
358         let within_unsafe = match safety {
359             // `unsafe` blocks are required in safe code
360             Safety::Safe => {
361                 for violation in violations {
362                     let mut violation = violation.clone();
363                     match violation.kind {
364                         UnsafetyViolationKind::GeneralAndConstFn
365                         | UnsafetyViolationKind::General => {}
366                         UnsafetyViolationKind::BorrowPacked(_) => {
367                             if self.min_const_fn {
368                                 // const fns don't need to be backwards compatible and can
369                                 // emit these violations as a hard error instead of a backwards
370                                 // compat lint
371                                 violation.kind = UnsafetyViolationKind::General;
372                             }
373                         }
374                     }
375                     if !self.violations.contains(&violation) {
376                         self.violations.push(violation)
377                     }
378                 }
379                 false
380             }
381             // `unsafe` function bodies allow unsafe without additional unsafe blocks
382             Safety::BuiltinUnsafe | Safety::FnUnsafe => true,
383             Safety::ExplicitUnsafe(hir_id) => {
384                 // mark unsafe block as used if there are any unsafe operations inside
385                 if !violations.is_empty() {
386                     self.used_unsafe.insert(hir_id);
387                 }
388                 // only some unsafety is allowed in const fn
389                 if self.min_const_fn {
390                     for violation in violations {
391                         match violation.kind {
392                             // these unsafe things are stable in const fn
393                             UnsafetyViolationKind::GeneralAndConstFn => {}
394                             // these things are forbidden in const fns
395                             UnsafetyViolationKind::General
396                             | UnsafetyViolationKind::BorrowPacked(_) => {
397                                 let mut violation = violation.clone();
398                                 // const fns don't need to be backwards compatible and can
399                                 // emit these violations as a hard error instead of a backwards
400                                 // compat lint
401                                 violation.kind = UnsafetyViolationKind::General;
402                                 if !self.violations.contains(&violation) {
403                                     self.violations.push(violation)
404                                 }
405                             }
406                         }
407                     }
408                 }
409                 true
410             }
411         };
412         self.inherited_blocks.extend(
413             unsafe_blocks.iter().map(|&(hir_id, is_used)| (hir_id, is_used && !within_unsafe)),
414         );
415     }
416     fn check_mut_borrowing_layout_constrained_field(
417         &mut self,
418         place: &Place<'tcx>,
419         is_mut_use: bool,
420     ) {
421         let mut cursor = place.projection.as_ref();
422         while let &[ref proj_base @ .., elem] = cursor {
423             cursor = proj_base;
424
425             match elem {
426                 ProjectionElem::Field(..) => {
427                     let ty =
428                         Place::ty_from(&place.base, proj_base, &self.body.local_decls, self.tcx).ty;
429                     match ty.kind {
430                         ty::Adt(def, _) => match self.tcx.layout_scalar_valid_range(def.did) {
431                             (Bound::Unbounded, Bound::Unbounded) => {}
432                             _ => {
433                                 let (description, details) = if is_mut_use {
434                                     (
435                                         "mutation of layout constrained field",
436                                         "mutating layout constrained fields cannot statically be \
437                                         checked for valid values",
438                                     )
439                                 } else {
440                                     (
441                                         "borrow of layout constrained field with interior \
442                                         mutability",
443                                         "references to fields of layout constrained fields \
444                                         lose the constraints. Coupled with interior mutability, \
445                                         the field can be changed to invalid values",
446                                     )
447                                 };
448                                 let source_info = self.source_info;
449                                 self.register_violations(
450                                     &[UnsafetyViolation {
451                                         source_info,
452                                         description: Symbol::intern(description),
453                                         details: Symbol::intern(details),
454                                         kind: UnsafetyViolationKind::GeneralAndConstFn,
455                                     }],
456                                     &[],
457                                 );
458                             }
459                         },
460                         _ => {}
461                     }
462                 }
463                 _ => {}
464             }
465         }
466     }
467 }
468
469 pub(crate) fn provide(providers: &mut Providers<'_>) {
470     *providers = Providers { unsafety_check_result, unsafe_derive_on_repr_packed, ..*providers };
471 }
472
473 struct UnusedUnsafeVisitor<'a> {
474     used_unsafe: &'a FxHashSet<hir::HirId>,
475     unsafe_blocks: &'a mut Vec<(hir::HirId, bool)>,
476 }
477
478 impl<'a, 'tcx> intravisit::Visitor<'tcx> for UnusedUnsafeVisitor<'a> {
479     fn nested_visit_map<'this>(&'this mut self) -> intravisit::NestedVisitorMap<'this, 'tcx> {
480         intravisit::NestedVisitorMap::None
481     }
482
483     fn visit_block(&mut self, block: &'tcx hir::Block<'tcx>) {
484         intravisit::walk_block(self, block);
485
486         if let hir::BlockCheckMode::UnsafeBlock(hir::UnsafeSource::UserProvided) = block.rules {
487             self.unsafe_blocks.push((block.hir_id, self.used_unsafe.contains(&block.hir_id)));
488         }
489     }
490 }
491
492 fn check_unused_unsafe(
493     tcx: TyCtxt<'_>,
494     def_id: DefId,
495     used_unsafe: &FxHashSet<hir::HirId>,
496     unsafe_blocks: &mut Vec<(hir::HirId, bool)>,
497 ) {
498     let body_id =
499         tcx.hir().as_local_hir_id(def_id).and_then(|hir_id| tcx.hir().maybe_body_owned_by(hir_id));
500
501     let body_id = match body_id {
502         Some(body) => body,
503         None => {
504             debug!("check_unused_unsafe({:?}) - no body found", def_id);
505             return;
506         }
507     };
508     let body = tcx.hir().body(body_id);
509     debug!("check_unused_unsafe({:?}, body={:?}, used_unsafe={:?})", def_id, body, used_unsafe);
510
511     let mut visitor = UnusedUnsafeVisitor { used_unsafe, unsafe_blocks };
512     intravisit::Visitor::visit_body(&mut visitor, body);
513 }
514
515 fn unsafety_check_result(tcx: TyCtxt<'_>, def_id: DefId) -> UnsafetyCheckResult {
516     debug!("unsafety_violations({:?})", def_id);
517
518     // N.B., this borrow is valid because all the consumers of
519     // `mir_built` force this.
520     let body = &tcx.mir_built(def_id).borrow();
521
522     let param_env = tcx.param_env(def_id);
523
524     let id = tcx.hir().as_local_hir_id(def_id).unwrap();
525     let (const_context, min_const_fn) = match tcx.hir().body_owner_kind(id) {
526         hir::BodyOwnerKind::Closure => (false, false),
527         hir::BodyOwnerKind::Fn => (is_const_fn(tcx, def_id), is_min_const_fn(tcx, def_id)),
528         hir::BodyOwnerKind::Const | hir::BodyOwnerKind::Static(_) => (true, false),
529     };
530     let mut checker = UnsafetyChecker::new(const_context, min_const_fn, body, tcx, param_env);
531     // mir_built ensures that body has a computed cache, so we don't (and can't) attempt to
532     // recompute it here.
533     let body = body.unwrap_read_only();
534     checker.visit_body(body);
535
536     check_unused_unsafe(tcx, def_id, &checker.used_unsafe, &mut checker.inherited_blocks);
537     UnsafetyCheckResult {
538         violations: checker.violations.into(),
539         unsafe_blocks: checker.inherited_blocks.into(),
540     }
541 }
542
543 fn unsafe_derive_on_repr_packed(tcx: TyCtxt<'_>, def_id: DefId) {
544     let lint_hir_id = tcx
545         .hir()
546         .as_local_hir_id(def_id)
547         .unwrap_or_else(|| bug!("checking unsafety for non-local def id {:?}", def_id));
548
549     // FIXME: when we make this a hard error, this should have its
550     // own error code.
551     let message = if tcx.generics_of(def_id).own_requires_monomorphization() {
552         "`#[derive]` can't be used on a `#[repr(packed)]` struct with \
553          type or const parameters (error E0133)"
554             .to_string()
555     } else {
556         "`#[derive]` can't be used on a `#[repr(packed)]` struct that \
557          does not derive Copy (error E0133)"
558             .to_string()
559     };
560     tcx.lint_hir(SAFE_PACKED_BORROWS, lint_hir_id, tcx.def_span(def_id), &message);
561 }
562
563 /// Returns the `HirId` for an enclosing scope that is also `unsafe`.
564 fn is_enclosed(
565     tcx: TyCtxt<'_>,
566     used_unsafe: &FxHashSet<hir::HirId>,
567     id: hir::HirId,
568 ) -> Option<(String, hir::HirId)> {
569     let parent_id = tcx.hir().get_parent_node(id);
570     if parent_id != id {
571         if used_unsafe.contains(&parent_id) {
572             Some(("block".to_string(), parent_id))
573         } else if let Some(Node::Item(&hir::Item {
574             kind: hir::ItemKind::Fn(ref sig, _, _), ..
575         })) = tcx.hir().find(parent_id)
576         {
577             match sig.header.unsafety {
578                 hir::Unsafety::Unsafe => Some(("fn".to_string(), parent_id)),
579                 hir::Unsafety::Normal => None,
580             }
581         } else {
582             is_enclosed(tcx, used_unsafe, parent_id)
583         }
584     } else {
585         None
586     }
587 }
588
589 fn report_unused_unsafe(tcx: TyCtxt<'_>, used_unsafe: &FxHashSet<hir::HirId>, id: hir::HirId) {
590     let span = tcx.sess.source_map().def_span(tcx.hir().span(id));
591     let msg = "unnecessary `unsafe` block";
592     let mut db = tcx.struct_span_lint_hir(UNUSED_UNSAFE, id, span, msg);
593     db.span_label(span, msg);
594     if let Some((kind, id)) = is_enclosed(tcx, used_unsafe, id) {
595         db.span_label(
596             tcx.sess.source_map().def_span(tcx.hir().span(id)),
597             format!("because it's nested under this `unsafe` {}", kind),
598         );
599     }
600     db.emit();
601 }
602
603 fn builtin_derive_def_id(tcx: TyCtxt<'_>, def_id: DefId) -> Option<DefId> {
604     debug!("builtin_derive_def_id({:?})", def_id);
605     if let Some(impl_def_id) = tcx.impl_of_method(def_id) {
606         if tcx.has_attr(impl_def_id, sym::automatically_derived) {
607             debug!("builtin_derive_def_id({:?}) - is {:?}", def_id, impl_def_id);
608             Some(impl_def_id)
609         } else {
610             debug!("builtin_derive_def_id({:?}) - not automatically derived", def_id);
611             None
612         }
613     } else {
614         debug!("builtin_derive_def_id({:?}) - not a method", def_id);
615         None
616     }
617 }
618
619 pub fn check_unsafety(tcx: TyCtxt<'_>, def_id: DefId) {
620     debug!("check_unsafety({:?})", def_id);
621
622     // closures are handled by their parent fn.
623     if tcx.is_closure(def_id) {
624         return;
625     }
626
627     let UnsafetyCheckResult { violations, unsafe_blocks } = tcx.unsafety_check_result(def_id);
628
629     for &UnsafetyViolation { source_info, description, details, kind } in violations.iter() {
630         // Report an error.
631         match kind {
632             UnsafetyViolationKind::GeneralAndConstFn | UnsafetyViolationKind::General => {
633                 struct_span_err!(
634                     tcx.sess,
635                     source_info.span,
636                     E0133,
637                     "{} is unsafe and requires unsafe function or block",
638                     description
639                 )
640                 .span_label(source_info.span, &*description.as_str())
641                 .note(&details.as_str())
642                 .emit();
643             }
644             UnsafetyViolationKind::BorrowPacked(lint_hir_id) => {
645                 if let Some(impl_def_id) = builtin_derive_def_id(tcx, def_id) {
646                     tcx.unsafe_derive_on_repr_packed(impl_def_id);
647                 } else {
648                     tcx.lint_node_note(
649                         SAFE_PACKED_BORROWS,
650                         lint_hir_id,
651                         source_info.span,
652                         &format!(
653                             "{} is unsafe and requires unsafe function or block \
654                                             (error E0133)",
655                             description
656                         ),
657                         &details.as_str(),
658                     );
659                 }
660             }
661         }
662     }
663
664     let mut unsafe_blocks: Vec<_> = unsafe_blocks.into_iter().collect();
665     unsafe_blocks.sort_by_cached_key(|(hir_id, _)| tcx.hir().hir_to_node_id(*hir_id));
666     let used_unsafe: FxHashSet<_> =
667         unsafe_blocks.iter().flat_map(|&&(id, used)| used.then_some(id)).collect();
668     for &(block_id, is_used) in unsafe_blocks {
669         if !is_used {
670             report_unused_unsafe(tcx, &used_unsafe, block_id);
671         }
672     }
673 }