1 //! Values computed by queries that use MIR.
3 use crate::mir::{abstract_const, Body, Promoted};
4 use crate::ty::{self, Ty, TyCtxt};
5 use rustc_data_structures::fx::FxHashMap;
6 use rustc_data_structures::sync::Lrc;
7 use rustc_errors::ErrorReported;
9 use rustc_hir::def_id::{DefId, LocalDefId};
10 use rustc_index::bit_set::BitMatrix;
11 use rustc_index::vec::IndexVec;
13 use rustc_target::abi::VariantIdx;
14 use smallvec::SmallVec;
16 use std::fmt::{self, Debug};
18 use super::{Field, SourceInfo};
20 #[derive(Copy, Clone, PartialEq, TyEncodable, TyDecodable, HashStable)]
21 pub enum UnsafetyViolationKind {
22 /// Only permitted in regular `fn`s, prohibited in `const fn`s.
24 /// Permitted both in `const fn`s and regular `fn`s.
26 /// Borrow of packed field.
27 /// Has to be handled as a lint for backwards compatibility.
29 /// Unsafe operation in an `unsafe fn` but outside an `unsafe` block.
30 /// Has to be handled as a lint for backwards compatibility.
31 /// Should stay gated under `#![feature(unsafe_block_in_unsafe_fn)]`.
33 /// Borrow of packed field in an `unsafe fn` but outside an `unsafe` block.
34 /// Has to be handled as a lint for backwards compatibility.
35 /// Should stay gated under `#![feature(unsafe_block_in_unsafe_fn)]`.
39 #[derive(Copy, Clone, PartialEq, TyEncodable, TyDecodable, HashStable)]
40 pub enum UnsafetyViolationDetails {
49 AssignToNonCopyUnionField,
51 MutationOfLayoutConstrainedField,
52 BorrowOfLayoutConstrainedField,
56 impl UnsafetyViolationDetails {
57 pub fn description_and_note(&self) -> (&'static str, &'static str) {
58 use UnsafetyViolationDetails::*;
60 CallToUnsafeFunction => (
61 "call to unsafe function",
62 "consult the function's documentation for information on how to avoid undefined \
65 UseOfInlineAssembly => (
66 "use of inline assembly",
67 "inline assembly is entirely unchecked and can cause undefined behavior",
69 InitializingTypeWith => (
70 "initializing type with `rustc_layout_scalar_valid_range` attr",
71 "initializing a layout restricted type's field with a value outside the valid \
72 range is undefined behavior",
74 CastOfPointerToInt => {
75 ("cast of pointer to int", "casting pointers to integers in constants")
77 BorrowOfPackedField => (
78 "borrow of packed field",
79 "fields of packed structs might be misaligned: dereferencing a misaligned pointer \
80 or even just creating a misaligned reference is undefined behavior",
82 UseOfMutableStatic => (
83 "use of mutable static",
84 "mutable statics can be mutated by multiple threads: aliasing violations or data \
85 races will cause undefined behavior",
87 UseOfExternStatic => (
88 "use of extern static",
89 "extern statics are not controlled by the Rust type system: invalid data, \
90 aliasing violations or data races will cause undefined behavior",
92 DerefOfRawPointer => (
93 "dereference of raw pointer",
94 "raw pointers may be NULL, dangling or unaligned; they can violate aliasing rules \
95 and cause data races: all of these are undefined behavior",
97 AssignToNonCopyUnionField => (
98 "assignment to non-`Copy` union field",
99 "the previous content of the field will be dropped, which causes undefined \
100 behavior if the field was not properly initialized",
102 AccessToUnionField => (
103 "access to union field",
104 "the field may not be properly initialized: using uninitialized data will cause \
107 MutationOfLayoutConstrainedField => (
108 "mutation of layout constrained field",
109 "mutating layout constrained fields cannot statically be checked for valid values",
111 BorrowOfLayoutConstrainedField => (
112 "borrow of layout constrained field with interior mutability",
113 "references to fields of layout constrained fields lose the constraints. Coupled \
114 with interior mutability, the field can be changed to invalid values",
116 CallToFunctionWith => (
117 "call to function with `#[target_feature]`",
118 "can only be called if the required target features are available",
124 #[derive(Copy, Clone, PartialEq, TyEncodable, TyDecodable, HashStable)]
125 pub struct UnsafetyViolation {
126 pub source_info: SourceInfo,
127 pub lint_root: hir::HirId,
128 pub kind: UnsafetyViolationKind,
129 pub details: UnsafetyViolationDetails,
132 #[derive(Clone, TyEncodable, TyDecodable, HashStable)]
133 pub struct UnsafetyCheckResult {
134 /// Violations that are propagated *upwards* from this function.
135 pub violations: Lrc<[UnsafetyViolation]>,
136 /// `unsafe` blocks in this function, along with whether they are used. This is
137 /// used for the "unused_unsafe" lint.
138 pub unsafe_blocks: Lrc<[(hir::HirId, bool)]>,
141 rustc_index::newtype_index! {
142 pub struct GeneratorSavedLocal {
144 DEBUG_FORMAT = "_{}",
148 /// The layout of generator state.
149 #[derive(Clone, TyEncodable, TyDecodable, HashStable, TypeFoldable)]
150 pub struct GeneratorLayout<'tcx> {
151 /// The type of every local stored inside the generator.
152 pub field_tys: IndexVec<GeneratorSavedLocal, Ty<'tcx>>,
154 /// Which of the above fields are in each variant. Note that one field may
155 /// be stored in multiple variants.
156 pub variant_fields: IndexVec<VariantIdx, IndexVec<Field, GeneratorSavedLocal>>,
158 /// The source that led to each variant being created (usually, a yield or
160 pub variant_source_info: IndexVec<VariantIdx, SourceInfo>,
162 /// Which saved locals are storage-live at the same time. Locals that do not
163 /// have conflicts with each other are allowed to overlap in the computed
165 pub storage_conflicts: BitMatrix<GeneratorSavedLocal, GeneratorSavedLocal>,
168 impl Debug for GeneratorLayout<'_> {
169 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
170 /// Prints an iterator of (key, value) tuples as a map.
171 struct MapPrinter<'a, K, V>(Cell<Option<Box<dyn Iterator<Item = (K, V)> + 'a>>>);
172 impl<'a, K, V> MapPrinter<'a, K, V> {
173 fn new(iter: impl Iterator<Item = (K, V)> + 'a) -> Self {
174 Self(Cell::new(Some(Box::new(iter))))
177 impl<'a, K: Debug, V: Debug> Debug for MapPrinter<'a, K, V> {
178 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
179 fmt.debug_map().entries(self.0.take().unwrap()).finish()
183 /// Prints the generator variant name.
184 struct GenVariantPrinter(VariantIdx);
185 impl From<VariantIdx> for GenVariantPrinter {
186 fn from(idx: VariantIdx) -> Self {
187 GenVariantPrinter(idx)
190 impl Debug for GenVariantPrinter {
191 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
192 let variant_name = ty::GeneratorSubsts::variant_name(self.0);
194 write!(fmt, "{:9}({:?})", variant_name, self.0)
196 write!(fmt, "{}", variant_name)
201 /// Forces its contents to print in regular mode instead of alternate mode.
202 struct OneLinePrinter<T>(T);
203 impl<T: Debug> Debug for OneLinePrinter<T> {
204 fn fmt(&self, fmt: &mut fmt::Formatter<'_>) -> fmt::Result {
205 write!(fmt, "{:?}", self.0)
209 fmt.debug_struct("GeneratorLayout")
210 .field("field_tys", &MapPrinter::new(self.field_tys.iter_enumerated()))
216 .map(|(k, v)| (GenVariantPrinter(k), OneLinePrinter(v))),
219 .field("storage_conflicts", &self.storage_conflicts)
224 #[derive(Debug, TyEncodable, TyDecodable, HashStable)]
225 pub struct BorrowCheckResult<'tcx> {
226 /// All the opaque types that are restricted to concrete types
227 /// by this function. Unlike the value in `TypeckResults`, this has
228 /// unerased regions.
229 pub concrete_opaque_types: FxHashMap<DefId, ty::ResolvedOpaqueTy<'tcx>>,
230 pub closure_requirements: Option<ClosureRegionRequirements<'tcx>>,
231 pub used_mut_upvars: SmallVec<[Field; 8]>,
234 /// The result of the `mir_const_qualif` query.
236 /// Each field (except `error_occured`) corresponds to an implementer of the `Qualif` trait in
237 /// `rustc_mir/src/transform/check_consts/qualifs.rs`. See that file for more information on each
239 #[derive(Clone, Copy, Debug, Default, TyEncodable, TyDecodable, HashStable)]
240 pub struct ConstQualifs {
241 pub has_mut_interior: bool,
242 pub needs_drop: bool,
244 pub error_occured: Option<ErrorReported>,
247 /// After we borrow check a closure, we are left with various
248 /// requirements that we have inferred between the free regions that
249 /// appear in the closure's signature or on its field types. These
250 /// requirements are then verified and proved by the closure's
251 /// creating function. This struct encodes those requirements.
253 /// The requirements are listed as being between various `RegionVid`. The 0th
254 /// region refers to `'static`; subsequent region vids refer to the free
255 /// regions that appear in the closure (or generator's) type, in order of
256 /// appearance. (This numbering is actually defined by the `UniversalRegions`
257 /// struct in the NLL region checker. See for example
258 /// `UniversalRegions::closure_mapping`.) Note the free regions in the
259 /// closure's signature and captures are erased.
261 /// Example: If type check produces a closure with the closure substs:
264 /// ClosureSubsts = [
265 /// 'a, // From the parent.
267 /// i8, // the "closure kind"
268 /// for<'x> fn(&'<erased> &'x u32) -> &'x u32, // the "closure signature"
269 /// &'<erased> String, // some upvar
273 /// We would "renumber" each free region to a unique vid, as follows:
276 /// ClosureSubsts = [
277 /// '1, // From the parent.
279 /// i8, // the "closure kind"
280 /// for<'x> fn(&'3 &'x u32) -> &'x u32, // the "closure signature"
281 /// &'4 String, // some upvar
285 /// Now the code might impose a requirement like `'1: '2`. When an
286 /// instance of the closure is created, the corresponding free regions
287 /// can be extracted from its type and constrained to have the given
288 /// outlives relationship.
290 /// In some cases, we have to record outlives requirements between types and
291 /// regions as well. In that case, if those types include any regions, those
292 /// regions are recorded using their external names (`ReStatic`,
293 /// `ReEarlyBound`, `ReFree`). We use these because in a query response we
294 /// cannot use `ReVar` (which is what we use internally within the rest of the
296 #[derive(Clone, Debug, TyEncodable, TyDecodable, HashStable)]
297 pub struct ClosureRegionRequirements<'tcx> {
298 /// The number of external regions defined on the closure. In our
299 /// example above, it would be 3 -- one for `'static`, then `'1`
300 /// and `'2`. This is just used for a sanity check later on, to
301 /// make sure that the number of regions we see at the callsite
303 pub num_external_vids: usize,
305 /// Requirements between the various free regions defined in
307 pub outlives_requirements: Vec<ClosureOutlivesRequirement<'tcx>>,
310 /// Indicates an outlives-constraint between a type or between two
311 /// free regions declared on the closure.
312 #[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
313 pub struct ClosureOutlivesRequirement<'tcx> {
314 // This region or type ...
315 pub subject: ClosureOutlivesSubject<'tcx>,
317 // ... must outlive this one.
318 pub outlived_free_region: ty::RegionVid,
320 // If not, report an error here ...
321 pub blame_span: Span,
323 // ... due to this reason.
324 pub category: ConstraintCategory,
327 /// Outlives-constraints can be categorized to determine whether and why they
328 /// are interesting (for error reporting). Order of variants indicates sort
329 /// order of the category, thereby influencing diagnostic output.
331 /// See also `rustc_mir::borrow_check::constraints`.
332 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash)]
333 #[derive(TyEncodable, TyDecodable, HashStable)]
334 pub enum ConstraintCategory {
335 Return(ReturnConstraint),
342 /// A constraint that came from checking the body of a closure.
344 /// We try to get the category that the closure used when reporting this.
351 ClosureUpvar(hir::HirId),
353 /// A "boring" constraint (caused by the given location) is one that
354 /// the user probably doesn't want to see described in diagnostics,
355 /// because it is kind of an artifact of the type system setup.
356 /// Example: `x = Foo { field: y }` technically creates
357 /// intermediate regions representing the "type of `Foo { field: y
358 /// }`", and data flows from `y` into those variables, but they
359 /// are not very interesting. The assignment into `x` on the other
362 // Boring and applicable everywhere.
365 /// A constraint that doesn't correspond to anything the user sees.
369 #[derive(Copy, Clone, Debug, Eq, PartialEq, PartialOrd, Ord, Hash)]
370 #[derive(TyEncodable, TyDecodable, HashStable)]
371 pub enum ReturnConstraint {
373 ClosureUpvar(hir::HirId),
376 /// The subject of a `ClosureOutlivesRequirement` -- that is, the thing
377 /// that must outlive some region.
378 #[derive(Copy, Clone, Debug, TyEncodable, TyDecodable, HashStable)]
379 pub enum ClosureOutlivesSubject<'tcx> {
380 /// Subject is a type, typically a type parameter, but could also
381 /// be a projection. Indicates a requirement like `T: 'a` being
382 /// passed to the caller, where the type here is `T`.
384 /// The type here is guaranteed not to contain any free regions at
388 /// Subject is a free region from the closure. Indicates a requirement
389 /// like `'a: 'b` being passed to the caller; the region here is `'a`.
390 Region(ty::RegionVid),
393 /// The constituent parts of an ADT or array.
394 #[derive(Copy, Clone, Debug, HashStable)]
395 pub struct DestructuredConst<'tcx> {
396 pub variant: Option<VariantIdx>,
397 pub fields: &'tcx [&'tcx ty::Const<'tcx>],
400 /// Coverage information summarized from a MIR if instrumented for source code coverage (see
401 /// compiler option `-Zinstrument-coverage`). This information is generated by the
402 /// `InstrumentCoverage` MIR pass and can be retrieved via the `coverageinfo` query.
403 #[derive(Clone, TyEncodable, TyDecodable, Debug, HashStable)]
404 pub struct CoverageInfo {
405 /// The total number of coverage region counters added to the MIR `Body`.
406 pub num_counters: u32,
408 /// The total number of coverage region counter expressions added to the MIR `Body`.
409 pub num_expressions: u32,
412 /// Shims which make dealing with `WithOptConstParam` easier.
414 /// For more information on why this is needed, consider looking
415 /// at the docs for `WithOptConstParam` itself.
416 impl<'tcx> TyCtxt<'tcx> {
418 pub fn mir_const_qualif_opt_const_arg(
420 def: ty::WithOptConstParam<LocalDefId>,
422 if let Some(param_did) = def.const_param_did {
423 self.mir_const_qualif_const_arg((def.did, param_did))
425 self.mir_const_qualif(def.did)
430 pub fn promoted_mir_opt_const_arg(
432 def: ty::WithOptConstParam<DefId>,
433 ) -> &'tcx IndexVec<Promoted, Body<'tcx>> {
434 if let Some((did, param_did)) = def.as_const_arg() {
435 self.promoted_mir_of_const_arg((did, param_did))
437 self.promoted_mir(def.did)
442 pub fn optimized_mir_opt_const_arg(
444 def: ty::WithOptConstParam<DefId>,
445 ) -> &'tcx Body<'tcx> {
446 if let Some((did, param_did)) = def.as_const_arg() {
447 self.optimized_mir_of_const_arg((did, param_did))
449 self.optimized_mir(def.did)
454 pub fn mir_abstract_const_opt_const_arg(
456 def: ty::WithOptConstParam<DefId>,
457 ) -> Result<Option<&'tcx [abstract_const::Node<'tcx>]>, ErrorReported> {
458 if let Some((did, param_did)) = def.as_const_arg() {
459 self.mir_abstract_const_of_const_arg((did, param_did))
461 self.mir_abstract_const(def.did)