1 //! Values computed by queries that use MIR.
3 use crate::mir::{Body, Promoted};
4 use crate::ty::{self, Ty, TyCtxt};
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_data_structures::sync::Lrc;
8 use rustc_hir::def_id::{DefId, LocalDefId};
9 use rustc_index::bit_set::BitMatrix;
10 use rustc_index::vec::IndexVec;
12 use rustc_target::abi::VariantIdx;
13 use smallvec::SmallVec;
15 use std::fmt::{self, Debug};
17 use super::{Field, SourceInfo};
19 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
20 pub enum UnsafetyViolationKind {
21 /// Only permitted in regular `fn`s, prohibited in `const fn`s.
23 /// Permitted both in `const fn`s and regular `fn`s.
25 /// Borrow of packed field.
26 /// Has to be handled as a lint for backwards compatibility.
28 /// Unsafe operation in an `unsafe fn` but outside an `unsafe` block.
29 /// Has to be handled as a lint for backwards compatibility.
30 /// Should stay gated under `#![feature(unsafe_block_in_unsafe_fn)]`.
32 /// Borrow of packed field in an `unsafe fn` but outside an `unsafe` block.
33 /// Has to be handled as a lint for backwards compatibility.
34 /// Should stay gated under `#![feature(unsafe_block_in_unsafe_fn)]`.
38 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
39 pub enum UnsafetyViolationDetails {
48 AssignToNonCopyUnionField,
50 MutationOfLayoutConstrainedField,
51 BorrowOfLayoutConstrainedField,
55 impl UnsafetyViolationDetails {
56 pub fn description_and_note(&self) -> (&'static str, &'static str) {
57 use UnsafetyViolationDetails::*;
59 CallToUnsafeFunction => (
60 "call to unsafe function",
61 "consult the function's documentation for information on how to avoid undefined \
64 UseOfInlineAssembly => (
65 "use of inline assembly",
66 "inline assembly is entirely unchecked and can cause undefined behavior",
68 InitializingTypeWith => (
69 "initializing type with `rustc_layout_scalar_valid_range` attr",
70 "initializing a layout restricted type's field with a value outside the valid \
71 range is undefined behavior",
73 CastOfPointerToInt => {
74 ("cast of pointer to int", "casting pointers to integers in constants")
76 BorrowOfPackedField => (
77 "borrow of packed field",
78 "fields of packed structs might be misaligned: dereferencing a misaligned pointer \
79 or even just creating a misaligned reference is undefined behavior",
81 UseOfMutableStatic => (
82 "use of mutable static",
83 "mutable statics can be mutated by multiple threads: aliasing violations or data \
84 races will cause undefined behavior",
86 UseOfExternStatic => (
87 "use of extern static",
88 "extern statics are not controlled by the Rust type system: invalid data, \
89 aliasing violations or data races will cause undefined behavior",
91 DerefOfRawPointer => (
92 "dereference of raw pointer",
93 "raw pointers may be NULL, dangling or unaligned; they can violate aliasing rules \
94 and cause data races: all of these are undefined behavior",
96 AssignToNonCopyUnionField => (
97 "assignment to non-`Copy` union field",
98 "the previous content of the field will be dropped, which causes undefined \
99 behavior if the field was not properly initialized",
101 AccessToUnionField => (
102 "access to union field",
103 "the field may not be properly initialized: using uninitialized data will cause \
106 MutationOfLayoutConstrainedField => (
107 "mutation of layout constrained field",
108 "mutating layout constrained fields cannot statically be checked for valid values",
110 BorrowOfLayoutConstrainedField => (
111 "borrow of layout constrained field with interior mutability",
112 "references to fields of layout constrained fields lose the constraints. Coupled \
113 with interior mutability, the field can be changed to invalid values",
115 CallToFunctionWith => (
116 "call to function with `#[target_feature]`",
117 "can only be called if the required target features are available",
123 #[derive(Copy, Clone, PartialEq, RustcEncodable, RustcDecodable, HashStable)]
124 pub struct UnsafetyViolation {
125 pub source_info: SourceInfo,
126 pub lint_root: hir::HirId,
127 pub kind: UnsafetyViolationKind,
128 pub details: UnsafetyViolationDetails,
131 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable)]
132 pub struct UnsafetyCheckResult {
133 /// Violations that are propagated *upwards* from this function.
134 pub violations: Lrc<[UnsafetyViolation]>,
135 /// `unsafe` blocks in this function, along with whether they are used. This is
136 /// used for the "unused_unsafe" lint.
137 pub unsafe_blocks: Lrc<[(hir::HirId, bool)]>,
140 rustc_index::newtype_index! {
141 pub struct GeneratorSavedLocal {
143 DEBUG_FORMAT = "_{}",
147 /// The layout of generator state.
148 #[derive(Clone, RustcEncodable, RustcDecodable, HashStable, TypeFoldable)]
149 pub struct GeneratorLayout<'tcx> {
150 /// The type of every local stored inside the generator.
151 pub field_tys: IndexVec<GeneratorSavedLocal, Ty<'tcx>>,
153 /// Which of the above fields are in each variant. Note that one field may
154 /// be stored in multiple variants.
155 pub variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>>,
157 /// The source that led to each variant being created (usually, a yield or
159 pub variant_source_info: IndexVec<VariantIdx, SourceInfo>,
161 /// Which saved locals are storage-live at the same time. Locals that do not
162 /// have conflicts with each other are allowed to overlap in the computed
164 pub storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
167 impl Debug for GeneratorLayout<'_> {
168 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
169 /// Prints an iterator of (key, value) tuples as a map.
170 struct MapPrinter<'a, K, V>(Cell<Option<Box<dyn Iterator<Item = (K, V)> + 'a>>>);
171 impl<'a, K, V> MapPrinter<'a, K, V> {
172 fn new(iter: impl Iterator<Item = (K, V)> + 'a) -> Self {
173 Self(Cell::new(Some(Box::new(iter))))
176 impl<'a, K: Debug, V: Debug> Debug for MapPrinter<'a, K, V> {
177 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
178 fmt.debug_map().entries(self.0.take().unwrap()).finish()
182 /// Prints the generator variant name.
183 struct GenVariantPrinter(VariantIdx);
184 impl From<VariantIdx> for GenVariantPrinter {
185 fn from(idx: VariantIdx) -> Self {
186 GenVariantPrinter(idx)
189 impl Debug for GenVariantPrinter {
190 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
191 let variant_name = ty::GeneratorSubsts::variant_name(self.0);
193 write!(fmt, "{:9}({:?})", variant_name, self.0)
195 write!(fmt, "{}", variant_name)
200 /// Forces its contents to print in regular mode instead of alternate mode.
201 struct OneLinePrinter<T>(T);
202 impl<T: Debug> Debug for OneLinePrinter<T> {
203 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
204 write!(fmt, "{:?}", self.0)
208 fmt.debug_struct("GeneratorLayout")
209 .field("field_tys", &MapPrinter::new(self.field_tys.iter_enumerated()))
215 .map(|(k, v)| (GenVariantPrinter(k), OneLinePrinter(v))),
218 .field("storage_conflicts", &self.storage_conflicts)
223 #[derive(Debug, RustcEncodable, RustcDecodable, HashStable)]
224 pub struct BorrowCheckResult<'tcx> {
225 /// All the opaque types that are restricted to concrete types
226 /// by this function. Unlike the value in `TypeckResults`, this has
227 /// unerased regions.
228 pub concrete_opaque_types: FxHashMap<DefId, ty::ResolvedOpaqueTy<'tcx>>,
229 pub closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
230 pub used_mut_upvars: SmallVec<[Field; 8]>,
233 /// The result of the `mir_const_qualif` query.
235 /// Each field corresponds to an implementer of the `Qualif` trait in
236 /// `librustc_mir/transform/check_consts/qualifs.rs`. See that file for more information on each
238 #[derive(Clone, Copy, Debug, Default, RustcEncodable, RustcDecodable, HashStable)]
239 pub struct ConstQualifs {
240 pub has_mut_interior: bool,
241 pub needs_drop: bool,
245 /// After we borrow check a closure, we are left with various
246 /// requirements that we have inferred between the free regions that
247 /// appear in the closure's signature or on its field types. These
248 /// requirements are then verified and proved by the closure's
249 /// creating function. This struct encodes those requirements.
251 /// The requirements are listed as being between various `RegionVid`. The 0th
252 /// region refers to `'static`; subsequent region vids refer to the free
253 /// regions that appear in the closure (or generator's) type, in order of
254 /// appearance. (This numbering is actually defined by the `UniversalRegions`
255 /// struct in the NLL region checker. See for example
256 /// `UniversalRegions::closure_mapping`.) Note the free regions in the
257 /// closure's signature and captures are erased.
259 /// Example: If type check produces a closure with the closure substs:
262 /// ClosureSubsts = [
263 /// 'a, // From the parent.
265 /// i8, // the "closure kind"
266 /// for<'x> fn(&'<erased> &'x u32) -> &'x u32, // the "closure signature"
267 /// &'<erased> String, // some upvar
271 /// We would "renumber" each free region to a unique vid, as follows:
274 /// ClosureSubsts = [
275 /// '1, // From the parent.
277 /// i8, // the "closure kind"
278 /// for<'x> fn(&'3 &'x u32) -> &'x u32, // the "closure signature"
279 /// &'4 String, // some upvar
283 /// Now the code might impose a requirement like `'1: '2`. When an
284 /// instance of the closure is created, the corresponding free regions
285 /// can be extracted from its type and constrained to have the given
286 /// outlives relationship.
288 /// In some cases, we have to record outlives requirements between types and
289 /// regions as well. In that case, if those types include any regions, those
290 /// regions are recorded using their external names (`ReStatic`,
291 /// `ReEarlyBound`, `ReFree`). We use these because in a query response we
292 /// cannot use `ReVar` (which is what we use internally within the rest of the
294 #[derive(Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
295 pub struct ClosureRegionRequirements<'tcx> {
296 /// The number of external regions defined on the closure. In our
297 /// example above, it would be 3 -- one for `'static`, then `'1`
298 /// and `'2`. This is just used for a sanity check later on, to
299 /// make sure that the number of regions we see at the callsite
301 pub num_external_vids: usize,
303 /// Requirements between the various free regions defined in
305 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>,
308 /// Indicates an outlives-constraint between a type or between two
309 /// free regions declared on the closure.
310 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
311 pub struct ClosureOutlivesRequirement<'tcx> {
312 // This region or type ...
313 pub subject: ClosureOutlivesSubject<'tcx>,
315 // ... must outlive this one.
316 pub outlived_free_region: ty::RegionVid,
318 // If not, report an error here ...
319 pub blame_span: Span,
321 // ... due to this reason.
322 pub category: ConstraintCategory,
325 /// Outlives-constraints can be categorized to determine whether and why they
326 /// are interesting (for error reporting). Order of variants indicates sort
327 /// order of the category, thereby influencing diagnostic output.
329 /// See also `rustc_mir::borrow_check::constraints`.
330 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash)]
331 #[derive(RustcEncodable, RustcDecodable, HashStable)]
332 pub enum ConstraintCategory {
333 Return(ReturnConstraint),
340 /// A constraint that came from checking the body of a closure.
342 /// We try to get the category that the closure used when reporting this.
349 ClosureUpvar(hir::HirId),
351 /// A "boring" constraint (caused by the given location) is one that
352 /// the user probably doesn't want to see described in diagnostics,
353 /// because it is kind of an artifact of the type system setup.
354 /// Example: `x = Foo { field: y }` technically creates
355 /// intermediate regions representing the "type of `Foo { field: y
356 /// }`", and data flows from `y` into those variables, but they
357 /// are not very interesting. The assignment into `x` on the other
360 // Boring and applicable everywhere.
363 /// A constraint that doesn't correspond to anything the user sees.
367 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash)]
368 #[derive(RustcEncodable, RustcDecodable, HashStable)]
369 pub enum ReturnConstraint {
371 ClosureUpvar(hir::HirId),
374 /// The subject of a `ClosureOutlivesRequirement` -- that is, the thing
375 /// that must outlive some region.
376 #[derive(Copy, Clone, Debug, RustcEncodable, RustcDecodable, HashStable)]
377 pub enum ClosureOutlivesSubject<'tcx> {
378 /// Subject is a type, typically a type parameter, but could also
379 /// be a projection. Indicates a requirement like `T: 'a` being
380 /// passed to the caller, where the type here is `T`.
382 /// The type here is guaranteed not to contain any free regions at
386 /// Subject is a free region from the closure. Indicates a requirement
387 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
388 Region(ty::RegionVid),
391 /// The constituent parts of an ADT or array.
392 #[derive(Copy, Clone, Debug, HashStable)]
393 pub struct DestructuredConst<'tcx> {
394 pub variant: Option<VariantIdx>,
395 pub fields: &'tcx [&'tcx ty::Const<'tcx>],
398 /// Coverage information summarized from a MIR if instrumented for source code coverage (see
399 /// compiler option `-Zinstrument-coverage`). This information is generated by the
400 /// `InstrumentCoverage` MIR pass and can be retrieved via the `coverageinfo` query.
401 #[derive(Clone, RustcEncodable, RustcDecodable, Debug, HashStable)]
402 pub struct CoverageInfo {
403 /// The total number of coverage region counters added to the MIR `Body`.
404 pub num_counters: u32,
406 /// The total number of coverage region counter expressions added to the MIR `Body`.
407 pub num_expressions: u32,
410 impl<'tcx> TyCtxt<'tcx> {
411 pub fn mir_borrowck_opt_const_arg(
413 def: ty::WithOptConstParam<LocalDefId>,
414 ) -> &'tcx BorrowCheckResult<'tcx> {
415 if let Some(param_did) = def.const_param_did {
416 self.mir_borrowck_const_arg((def.did, param_did))
418 self.mir_borrowck(def.did)
422 pub fn mir_const_qualif_opt_const_arg(
424 def: ty::WithOptConstParam<LocalDefId>,
426 if let Some(param_did) = def.const_param_did {
427 self.mir_const_qualif_const_arg((def.did, param_did))
429 self.mir_const_qualif(def.did)
433 pub fn promoted_mir_of_opt_const_arg(
435 def: ty::WithOptConstParam<DefId>,
436 ) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
437 if let Some((did, param_did)) = def.as_const_arg() {
438 self.promoted_mir_of_const_arg((did, param_did))
440 self.promoted_mir(def.did)