]> git.proxmox.com Git - rustc.git/blame - compiler/rustc_const_eval/src/transform/check_consts/resolver.rs
Update upstream source from tag 'upstream/1.70.0+dfsg1'
[rustc.git] / compiler / rustc_const_eval / src / transform / check_consts / resolver.rs
CommitLineData
e74abb32
XL
1//! Propagate `Qualif`s between locals and query the results.
2//!
3//! This contains the dataflow analysis used to track `Qualif`s on complex control-flow graphs.
4
e74abb32 5use rustc_index::bit_set::BitSet;
ba9703b0 6use rustc_middle::mir::visit::Visitor;
3c0e092e
XL
7use rustc_middle::mir::{self, BasicBlock, Local, Location, Statement, StatementKind};
8use rustc_mir_dataflow::fmt::DebugWithContext;
9use rustc_mir_dataflow::JoinSemiLattice;
a2a8927a 10use rustc_mir_dataflow::{Analysis, AnalysisDomain, CallReturnPlaces};
e74abb32 11
3c0e092e 12use std::fmt;
e74abb32
XL
13use std::marker::PhantomData;
14
f9f354fc 15use super::{qualifs, ConstCx, Qualif};
e74abb32
XL
16
17/// A `Visitor` that propagates qualifs between locals. This defines the transfer function of
18/// `FlowSensitiveAnalysis`.
19///
3c0e092e
XL
20/// To account for indirect assignments, data flow conservatively assumes that local becomes
21/// qualified immediately after it is borrowed or its address escapes. The borrow must allow for
22/// mutation, which includes shared borrows of places with interior mutability. The type of
23/// borrowed place must contain the qualif.
e74abb32 24struct TransferFunction<'a, 'mir, 'tcx, Q> {
f9f354fc 25 ccx: &'a ConstCx<'mir, 'tcx>,
3c0e092e 26 state: &'a mut State,
e74abb32
XL
27 _qualif: PhantomData<Q>,
28}
29
a2a8927a 30impl<'a, 'mir, 'tcx, Q> TransferFunction<'a, 'mir, 'tcx, Q>
e74abb32
XL
31where
32 Q: Qualif,
33{
3c0e092e
XL
34 fn new(ccx: &'a ConstCx<'mir, 'tcx>, state: &'a mut State) -> Self {
35 TransferFunction { ccx, state, _qualif: PhantomData }
e74abb32
XL
36 }
37
38 fn initialize_state(&mut self) {
3c0e092e
XL
39 self.state.qualif.clear();
40 self.state.borrow.clear();
e74abb32 41
f9f354fc
XL
42 for arg in self.ccx.body.args_iter() {
43 let arg_ty = self.ccx.body.local_decls[arg].ty;
44 if Q::in_any_value_of_ty(self.ccx, arg_ty) {
3c0e092e 45 self.state.qualif.insert(arg);
e74abb32
XL
46 }
47 }
48 }
49
3c0e092e 50 fn assign_qualif_direct(&mut self, place: &mir::Place<'tcx>, mut value: bool) {
e74abb32
XL
51 debug_assert!(!place.is_indirect());
52
3c0e092e
XL
53 if !value {
54 for (base, _elem) in place.iter_projections() {
55 let base_ty = base.ty(self.ccx.body, self.ccx.tcx);
56 if base_ty.ty.is_union() && Q::in_any_value_of_ty(self.ccx, base_ty.ty) {
57 value = true;
58 break;
59 }
60 }
61 }
62
e74abb32 63 match (value, place.as_ref()) {
dfeec247 64 (true, mir::PlaceRef { local, .. }) => {
3c0e092e 65 self.state.qualif.insert(local);
e74abb32
XL
66 }
67
68 // For now, we do not clear the qualif if a local is overwritten in full by
69 // an unqualified rvalue (e.g. `y = 5`). This is to be consistent
70 // with aggregates where we overwrite all fields with assignments, which would not
71 // get this feature.
dfeec247 72 (false, mir::PlaceRef { local: _, projection: &[] }) => {
3c0e092e 73 // self.state.qualif.remove(*local);
e74abb32
XL
74 }
75
76 _ => {}
77 }
78 }
79
80 fn apply_call_return_effect(
81 &mut self,
82 _block: BasicBlock,
a2a8927a 83 return_places: CallReturnPlaces<'_, 'tcx>,
e74abb32 84 ) {
a2a8927a
XL
85 return_places.for_each(|place| {
86 // We cannot reason about another function's internals, so use conservative type-based
87 // qualification for the result of a function call.
88 let return_ty = place.ty(self.ccx.body, self.ccx.tcx).ty;
89 let qualif = Q::in_any_value_of_ty(self.ccx, return_ty);
ba9703b0 90
a2a8927a
XL
91 if !place.is_indirect() {
92 self.assign_qualif_direct(&place, qualif);
93 }
94 });
e74abb32 95 }
3c0e092e
XL
96
97 fn address_of_allows_mutation(&self, _mt: mir::Mutability, _place: mir::Place<'tcx>) -> bool {
98 // Exact set of permissions granted by AddressOf is undecided. Conservatively assume that
99 // it might allow mutation until resolution of #56604.
100 true
101 }
102
103 fn ref_allows_mutation(&self, kind: mir::BorrowKind, place: mir::Place<'tcx>) -> bool {
104 match kind {
105 mir::BorrowKind::Mut { .. } => true,
106 mir::BorrowKind::Shared | mir::BorrowKind::Shallow | mir::BorrowKind::Unique => {
107 self.shared_borrow_allows_mutation(place)
108 }
109 }
110 }
111
112 /// `&` only allow mutation if the borrowed place is `!Freeze`.
113 ///
114 /// This assumes that it is UB to take the address of a struct field whose type is
115 /// `Freeze`, then use pointer arithmetic to derive a pointer to a *different* field of
116 /// that same struct whose type is `!Freeze`. If we decide that this is not UB, we will
117 /// have to check the type of the borrowed **local** instead of the borrowed **place**
118 /// below. See [rust-lang/unsafe-code-guidelines#134].
119 ///
120 /// [rust-lang/unsafe-code-guidelines#134]: https://github.com/rust-lang/unsafe-code-guidelines/issues/134
121 fn shared_borrow_allows_mutation(&self, place: mir::Place<'tcx>) -> bool {
2b03887a 122 !place.ty(self.ccx.body, self.ccx.tcx).ty.is_freeze(self.ccx.tcx, self.ccx.param_env)
3c0e092e 123 }
e74abb32
XL
124}
125
a2a8927a 126impl<'tcx, Q> Visitor<'tcx> for TransferFunction<'_, '_, 'tcx, Q>
e74abb32
XL
127where
128 Q: Qualif,
129{
130 fn visit_operand(&mut self, operand: &mir::Operand<'tcx>, location: Location) {
131 self.super_operand(operand, location);
132
133 if !Q::IS_CLEARED_ON_MOVE {
134 return;
135 }
136
137 // If a local with no projections is moved from (e.g. `x` in `y = x`), record that
138 // it no longer needs to be dropped.
139 if let mir::Operand::Move(place) = operand {
140 if let Some(local) = place.as_local() {
3c0e092e
XL
141 // For backward compatibility with the MaybeMutBorrowedLocals used in an earlier
142 // implementation we retain qualif if a local had been borrowed before. This might
143 // not be strictly necessary since the local is no longer initialized.
144 if !self.state.borrow.contains(local) {
145 self.state.qualif.remove(local);
146 }
e74abb32
XL
147 }
148 }
149 }
150
151 fn visit_assign(
152 &mut self,
153 place: &mir::Place<'tcx>,
154 rvalue: &mir::Rvalue<'tcx>,
155 location: Location,
156 ) {
3c0e092e
XL
157 let qualif =
158 qualifs::in_rvalue::<Q, _>(self.ccx, &mut |l| self.state.qualif.contains(l), rvalue);
e74abb32
XL
159 if !place.is_indirect() {
160 self.assign_qualif_direct(place, qualif);
161 }
162
163 // We need to assign qualifs to the left-hand side before visiting `rvalue` since
164 // qualifs can be cleared on move.
165 self.super_assign(place, rvalue, location);
166 }
167
3c0e092e
XL
168 fn visit_rvalue(&mut self, rvalue: &mir::Rvalue<'tcx>, location: Location) {
169 self.super_rvalue(rvalue, location);
170
171 match rvalue {
172 mir::Rvalue::AddressOf(mt, borrowed_place) => {
173 if !borrowed_place.is_indirect()
174 && self.address_of_allows_mutation(*mt, *borrowed_place)
175 {
176 let place_ty = borrowed_place.ty(self.ccx.body, self.ccx.tcx).ty;
177 if Q::in_any_value_of_ty(self.ccx, place_ty) {
178 self.state.qualif.insert(borrowed_place.local);
179 self.state.borrow.insert(borrowed_place.local);
180 }
181 }
182 }
183
184 mir::Rvalue::Ref(_, kind, borrowed_place) => {
185 if !borrowed_place.is_indirect() && self.ref_allows_mutation(*kind, *borrowed_place)
186 {
187 let place_ty = borrowed_place.ty(self.ccx.body, self.ccx.tcx).ty;
188 if Q::in_any_value_of_ty(self.ccx, place_ty) {
189 self.state.qualif.insert(borrowed_place.local);
190 self.state.borrow.insert(borrowed_place.local);
191 }
192 }
193 }
194
195 mir::Rvalue::Cast(..)
196 | mir::Rvalue::ShallowInitBox(..)
197 | mir::Rvalue::Use(..)
064997fb 198 | mir::Rvalue::CopyForDeref(..)
3c0e092e
XL
199 | mir::Rvalue::ThreadLocalRef(..)
200 | mir::Rvalue::Repeat(..)
201 | mir::Rvalue::Len(..)
202 | mir::Rvalue::BinaryOp(..)
203 | mir::Rvalue::CheckedBinaryOp(..)
204 | mir::Rvalue::NullaryOp(..)
205 | mir::Rvalue::UnaryOp(..)
206 | mir::Rvalue::Discriminant(..)
207 | mir::Rvalue::Aggregate(..) => {}
208 }
209 }
210
211 fn visit_statement(&mut self, statement: &Statement<'tcx>, location: Location) {
212 match statement.kind {
213 StatementKind::StorageDead(local) => {
214 self.state.qualif.remove(local);
215 self.state.borrow.remove(local);
216 }
217 _ => self.super_statement(statement, location),
218 }
219 }
220
f035d41b 221 fn visit_terminator(&mut self, terminator: &mir::Terminator<'tcx>, location: Location) {
e74abb32
XL
222 // The effect of assignment to the return place in `TerminatorKind::Call` is not applied
223 // here; that occurs in `apply_call_return_effect`.
224
3c0e092e
XL
225 // We ignore borrow on drop because custom drop impls are not allowed in consts.
226 // FIXME: Reconsider if accounting for borrows in drops is necessary for const drop.
f035d41b 227 self.super_terminator(terminator, location);
e74abb32
XL
228 }
229}
230
231/// The dataflow analysis used to propagate qualifs on arbitrary CFGs.
232pub(super) struct FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q> {
f9f354fc 233 ccx: &'a ConstCx<'mir, 'tcx>,
e74abb32
XL
234 _qualif: PhantomData<Q>,
235}
236
237impl<'a, 'mir, 'tcx, Q> FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q>
238where
239 Q: Qualif,
240{
f9f354fc
XL
241 pub(super) fn new(_: Q, ccx: &'a ConstCx<'mir, 'tcx>) -> Self {
242 FlowSensitiveAnalysis { ccx, _qualif: PhantomData }
e74abb32
XL
243 }
244
3c0e092e 245 fn transfer_function(&self, state: &'a mut State) -> TransferFunction<'a, 'mir, 'tcx, Q> {
f9f354fc 246 TransferFunction::<Q>::new(self.ccx, state)
e74abb32
XL
247 }
248}
249
3c0e092e
XL
250#[derive(Debug, PartialEq, Eq)]
251pub(super) struct State {
252 /// Describes whether a local contains qualif.
253 pub qualif: BitSet<Local>,
254 /// Describes whether a local's address escaped and it might become qualified as a result an
255 /// indirect mutation.
256 pub borrow: BitSet<Local>,
257}
258
259impl Clone for State {
260 fn clone(&self) -> Self {
261 State { qualif: self.qualif.clone(), borrow: self.borrow.clone() }
262 }
263
264 // Data flow engine when possible uses `clone_from` for domain values.
265 // Providing an implementation will avoid some intermediate memory allocations.
266 fn clone_from(&mut self, other: &Self) {
267 self.qualif.clone_from(&other.qualif);
268 self.borrow.clone_from(&other.borrow);
269 }
270}
271
272impl State {
273 #[inline]
274 pub(super) fn contains(&self, local: Local) -> bool {
275 self.qualif.contains(local)
276 }
277}
278
279impl<C> DebugWithContext<C> for State {
280 fn fmt_with(&self, ctxt: &C, f: &mut fmt::Formatter<'_>) -> fmt::Result {
281 f.write_str("qualif: ")?;
282 self.qualif.fmt_with(ctxt, f)?;
283 f.write_str(" borrow: ")?;
284 self.borrow.fmt_with(ctxt, f)?;
285 Ok(())
286 }
287
288 fn fmt_diff_with(&self, old: &Self, ctxt: &C, f: &mut fmt::Formatter<'_>) -> fmt::Result {
289 if self == old {
290 return Ok(());
291 }
292
293 if self.qualif != old.qualif {
294 f.write_str("qualif: ")?;
295 self.qualif.fmt_diff_with(&old.qualif, ctxt, f)?;
296 f.write_str("\n")?;
297 }
298
299 if self.borrow != old.borrow {
300 f.write_str("borrow: ")?;
301 self.qualif.fmt_diff_with(&old.borrow, ctxt, f)?;
302 f.write_str("\n")?;
303 }
304
305 Ok(())
306 }
307}
308
309impl JoinSemiLattice for State {
310 fn join(&mut self, other: &Self) -> bool {
311 self.qualif.join(&other.qualif) || self.borrow.join(&other.borrow)
312 }
313}
314
a2a8927a 315impl<'tcx, Q> AnalysisDomain<'tcx> for FlowSensitiveAnalysis<'_, '_, 'tcx, Q>
e74abb32
XL
316where
317 Q: Qualif,
318{
3c0e092e 319 type Domain = State;
e74abb32
XL
320
321 const NAME: &'static str = Q::ANALYSIS_NAME;
322
1b1a35ee 323 fn bottom_value(&self, body: &mir::Body<'tcx>) -> Self::Domain {
3c0e092e
XL
324 State {
325 qualif: BitSet::new_empty(body.local_decls.len()),
326 borrow: BitSet::new_empty(body.local_decls.len()),
327 }
e74abb32
XL
328 }
329
1b1a35ee 330 fn initialize_start_block(&self, _body: &mir::Body<'tcx>, state: &mut Self::Domain) {
e74abb32
XL
331 self.transfer_function(state).initialize_state();
332 }
dfeec247 333}
e74abb32 334
a2a8927a 335impl<'tcx, Q> Analysis<'tcx> for FlowSensitiveAnalysis<'_, '_, 'tcx, Q>
dfeec247
XL
336where
337 Q: Qualif,
338{
e74abb32
XL
339 fn apply_statement_effect(
340 &self,
1b1a35ee 341 state: &mut Self::Domain,
e74abb32
XL
342 statement: &mir::Statement<'tcx>,
343 location: Location,
344 ) {
345 self.transfer_function(state).visit_statement(statement, location);
346 }
347
348 fn apply_terminator_effect(
349 &self,
1b1a35ee 350 state: &mut Self::Domain,
e74abb32
XL
351 terminator: &mir::Terminator<'tcx>,
352 location: Location,
353 ) {
354 self.transfer_function(state).visit_terminator(terminator, location);
355 }
356
357 fn apply_call_return_effect(
358 &self,
1b1a35ee 359 state: &mut Self::Domain,
e74abb32 360 block: BasicBlock,
a2a8927a 361 return_places: CallReturnPlaces<'_, 'tcx>,
e74abb32 362 ) {
a2a8927a 363 self.transfer_function(state).apply_call_return_effect(block, return_places)
e74abb32
XL
364 }
365}