]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/qualify_min_const_fn.rs
Rollup merge of #74161 - tblah:riscv64gc-dockerfile-improvment, r=Mark-Simulacrum
[rust.git] / src / librustc_mir / transform / qualify_min_const_fn.rs
1 use rustc_attr as attr;
2 use rustc_hir as hir;
3 use rustc_hir::def_id::DefId;
4 use rustc_middle::mir::*;
5 use rustc_middle::ty::subst::GenericArgKind;
6 use rustc_middle::ty::{self, adjustment::PointerCast, Ty, TyCtxt};
7 use rustc_span::symbol::{sym, Symbol};
8 use rustc_span::Span;
9 use std::borrow::Cow;
10
11 type McfResult = Result<(), (Span, Cow<'static, str>)>;
12
13 pub fn is_min_const_fn(tcx: TyCtxt<'tcx>, def_id: DefId, body: &'a Body<'tcx>) -> McfResult {
14     // Prevent const trait methods from being annotated as `stable`.
15     if tcx.features().staged_api {
16         let hir_id = tcx.hir().as_local_hir_id(def_id.expect_local());
17         if crate::const_eval::is_parent_const_impl_raw(tcx, hir_id) {
18             return Err((body.span, "trait methods cannot be stable const fn".into()));
19         }
20     }
21
22     let mut current = def_id;
23     loop {
24         let predicates = tcx.predicates_of(current);
25         for (predicate, _) in predicates.predicates {
26             match predicate.kind() {
27                 ty::PredicateKind::RegionOutlives(_)
28                 | ty::PredicateKind::TypeOutlives(_)
29                 | ty::PredicateKind::WellFormed(_)
30                 | ty::PredicateKind::Projection(_)
31                 | ty::PredicateKind::ConstEvaluatable(..)
32                 | ty::PredicateKind::ConstEquate(..) => continue,
33                 ty::PredicateKind::ObjectSafe(_) => {
34                     bug!("object safe predicate on function: {:#?}", predicate)
35                 }
36                 ty::PredicateKind::ClosureKind(..) => {
37                     bug!("closure kind predicate on function: {:#?}", predicate)
38                 }
39                 ty::PredicateKind::Subtype(_) => {
40                     bug!("subtype predicate on function: {:#?}", predicate)
41                 }
42                 &ty::PredicateKind::Trait(pred, constness) => {
43                     if Some(pred.def_id()) == tcx.lang_items().sized_trait() {
44                         continue;
45                     }
46                     match pred.skip_binder().self_ty().kind {
47                         ty::Param(ref p) => {
48                             // Allow `T: ?const Trait`
49                             if constness == hir::Constness::NotConst
50                                 && feature_allowed(tcx, def_id, sym::const_trait_bound_opt_out)
51                             {
52                                 continue;
53                             }
54
55                             let generics = tcx.generics_of(current);
56                             let def = generics.type_param(p, tcx);
57                             let span = tcx.def_span(def.def_id);
58                             return Err((
59                                 span,
60                                 "trait bounds other than `Sized` \
61                                  on const fn parameters are unstable"
62                                     .into(),
63                             ));
64                         }
65                         // other kinds of bounds are either tautologies
66                         // or cause errors in other passes
67                         _ => continue,
68                     }
69                 }
70             }
71         }
72         match predicates.parent {
73             Some(parent) => current = parent,
74             None => break,
75         }
76     }
77
78     for local in &body.local_decls {
79         check_ty(tcx, local.ty, local.source_info.span, def_id)?;
80     }
81     // impl trait is gone in MIR, so check the return type manually
82     check_ty(
83         tcx,
84         tcx.fn_sig(def_id).output().skip_binder(),
85         body.local_decls.iter().next().unwrap().source_info.span,
86         def_id,
87     )?;
88
89     for bb in body.basic_blocks() {
90         check_terminator(tcx, body, def_id, bb.terminator())?;
91         for stmt in &bb.statements {
92             check_statement(tcx, body, def_id, stmt)?;
93         }
94     }
95     Ok(())
96 }
97
98 fn check_ty(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span, fn_def_id: DefId) -> McfResult {
99     for arg in ty.walk() {
100         let ty = match arg.unpack() {
101             GenericArgKind::Type(ty) => ty,
102
103             // No constraints on lifetimes or constants, except potentially
104             // constants' types, but `walk` will get to them as well.
105             GenericArgKind::Lifetime(_) | GenericArgKind::Const(_) => continue,
106         };
107
108         match ty.kind {
109             ty::Ref(_, _, hir::Mutability::Mut) => {
110                 if !feature_allowed(tcx, fn_def_id, sym::const_mut_refs) {
111                     return Err((span, "mutable references in const fn are unstable".into()));
112                 }
113             }
114             ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
115             ty::FnPtr(..) => {
116                 if !tcx.const_fn_is_allowed_fn_ptr(fn_def_id) {
117                     return Err((span, "function pointers in const fn are unstable".into()));
118                 }
119             }
120             ty::Dynamic(preds, _) => {
121                 for pred in preds.iter() {
122                     match pred.skip_binder() {
123                         ty::ExistentialPredicate::AutoTrait(_)
124                         | ty::ExistentialPredicate::Projection(_) => {
125                             return Err((
126                                 span,
127                                 "trait bounds other than `Sized` \
128                                  on const fn parameters are unstable"
129                                     .into(),
130                             ));
131                         }
132                         ty::ExistentialPredicate::Trait(trait_ref) => {
133                             if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
134                                 return Err((
135                                     span,
136                                     "trait bounds other than `Sized` \
137                                      on const fn parameters are unstable"
138                                         .into(),
139                                 ));
140                             }
141                         }
142                     }
143                 }
144             }
145             _ => {}
146         }
147     }
148     Ok(())
149 }
150
151 fn check_rvalue(
152     tcx: TyCtxt<'tcx>,
153     body: &Body<'tcx>,
154     def_id: DefId,
155     rvalue: &Rvalue<'tcx>,
156     span: Span,
157 ) -> McfResult {
158     match rvalue {
159         Rvalue::ThreadLocalRef(_) => {
160             Err((span, "cannot access thread local storage in const fn".into()))
161         }
162         Rvalue::Repeat(operand, _) | Rvalue::Use(operand) => {
163             check_operand(tcx, operand, span, def_id, body)
164         }
165         Rvalue::Len(place)
166         | Rvalue::Discriminant(place)
167         | Rvalue::Ref(_, _, place)
168         | Rvalue::AddressOf(_, place) => check_place(tcx, *place, span, def_id, body),
169         Rvalue::Cast(CastKind::Misc, operand, cast_ty) => {
170             use rustc_middle::ty::cast::CastTy;
171             let cast_in = CastTy::from_ty(operand.ty(body, tcx)).expect("bad input type for cast");
172             let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
173             match (cast_in, cast_out) {
174                 (CastTy::Ptr(_) | CastTy::FnPtr, CastTy::Int(_)) => {
175                     Err((span, "casting pointers to ints is unstable in const fn".into()))
176                 }
177                 _ => check_operand(tcx, operand, span, def_id, body),
178             }
179         }
180         Rvalue::Cast(
181             CastKind::Pointer(PointerCast::MutToConstPointer | PointerCast::ArrayToPointer),
182             operand,
183             _,
184         ) => check_operand(tcx, operand, span, def_id, body),
185         Rvalue::Cast(
186             CastKind::Pointer(
187                 PointerCast::UnsafeFnPointer
188                 | PointerCast::ClosureFnPointer(_)
189                 | PointerCast::ReifyFnPointer,
190             ),
191             _,
192             _,
193         ) => Err((span, "function pointer casts are not allowed in const fn".into())),
194         Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), op, cast_ty) => {
195             let pointee_ty = cast_ty.builtin_deref(true).unwrap().ty;
196             let unsized_ty = tcx.struct_tail_erasing_lifetimes(pointee_ty, tcx.param_env(def_id));
197             if let ty::Slice(_) | ty::Str = unsized_ty.kind {
198                 check_operand(tcx, op, span, def_id, body)?;
199                 // Casting/coercing things to slices is fine.
200                 Ok(())
201             } else {
202                 // We just can't allow trait objects until we have figured out trait method calls.
203                 Err((span, "unsizing casts are not allowed in const fn".into()))
204             }
205         }
206         // binops are fine on integers
207         Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
208             check_operand(tcx, lhs, span, def_id, body)?;
209             check_operand(tcx, rhs, span, def_id, body)?;
210             let ty = lhs.ty(body, tcx);
211             if ty.is_integral() || ty.is_bool() || ty.is_char() {
212                 Ok(())
213             } else {
214                 Err((span, "only int, `bool` and `char` operations are stable in const fn".into()))
215             }
216         }
217         Rvalue::NullaryOp(NullOp::SizeOf, _) => Ok(()),
218         Rvalue::NullaryOp(NullOp::Box, _) => {
219             Err((span, "heap allocations are not allowed in const fn".into()))
220         }
221         Rvalue::UnaryOp(_, operand) => {
222             let ty = operand.ty(body, tcx);
223             if ty.is_integral() || ty.is_bool() {
224                 check_operand(tcx, operand, span, def_id, body)
225             } else {
226                 Err((span, "only int and `bool` operations are stable in const fn".into()))
227             }
228         }
229         Rvalue::Aggregate(_, operands) => {
230             for operand in operands {
231                 check_operand(tcx, operand, span, def_id, body)?;
232             }
233             Ok(())
234         }
235     }
236 }
237
238 fn check_statement(
239     tcx: TyCtxt<'tcx>,
240     body: &Body<'tcx>,
241     def_id: DefId,
242     statement: &Statement<'tcx>,
243 ) -> McfResult {
244     let span = statement.source_info.span;
245     match &statement.kind {
246         StatementKind::Assign(box (place, rval)) => {
247             check_place(tcx, *place, span, def_id, body)?;
248             check_rvalue(tcx, body, def_id, rval, span)
249         }
250
251         StatementKind::FakeRead(_, place) => check_place(tcx, **place, span, def_id, body),
252
253         // just an assignment
254         StatementKind::SetDiscriminant { place, .. } => {
255             check_place(tcx, **place, span, def_id, body)
256         }
257
258         StatementKind::LlvmInlineAsm { .. } => {
259             Err((span, "cannot use inline assembly in const fn".into()))
260         }
261
262         // These are all NOPs
263         StatementKind::StorageLive(_)
264         | StatementKind::StorageDead(_)
265         | StatementKind::Retag { .. }
266         | StatementKind::AscribeUserType(..)
267         | StatementKind::Nop => Ok(()),
268     }
269 }
270
271 fn check_operand(
272     tcx: TyCtxt<'tcx>,
273     operand: &Operand<'tcx>,
274     span: Span,
275     def_id: DefId,
276     body: &Body<'tcx>,
277 ) -> McfResult {
278     match operand {
279         Operand::Move(place) | Operand::Copy(place) => check_place(tcx, *place, span, def_id, body),
280         Operand::Constant(c) => match c.check_static_ptr(tcx) {
281             Some(_) => Err((span, "cannot access `static` items in const fn".into())),
282             None => Ok(()),
283         },
284     }
285 }
286
287 fn check_place(
288     tcx: TyCtxt<'tcx>,
289     place: Place<'tcx>,
290     span: Span,
291     def_id: DefId,
292     body: &Body<'tcx>,
293 ) -> McfResult {
294     let mut cursor = place.projection.as_ref();
295     while let &[ref proj_base @ .., elem] = cursor {
296         cursor = proj_base;
297         match elem {
298             ProjectionElem::Field(..) => {
299                 let base_ty = Place::ty_from(place.local, &proj_base, body, tcx).ty;
300                 if let Some(def) = base_ty.ty_adt_def() {
301                     // No union field accesses in `const fn`
302                     if def.is_union() {
303                         if !feature_allowed(tcx, def_id, sym::const_fn_union) {
304                             return Err((span, "accessing union fields is unstable".into()));
305                         }
306                     }
307                 }
308             }
309             ProjectionElem::ConstantIndex { .. }
310             | ProjectionElem::Downcast(..)
311             | ProjectionElem::Subslice { .. }
312             | ProjectionElem::Deref
313             | ProjectionElem::Index(_) => {}
314         }
315     }
316
317     Ok(())
318 }
319
320 /// Returns `true` if the given feature gate is allowed within the function with the given `DefId`.
321 fn feature_allowed(tcx: TyCtxt<'tcx>, def_id: DefId, feature_gate: Symbol) -> bool {
322     // All features require that the corresponding gate be enabled,
323     // even if the function has `#[allow_internal_unstable(the_gate)]`.
324     if !tcx.features().enabled(feature_gate) {
325         return false;
326     }
327
328     // If this crate is not using stability attributes, or this function is not claiming to be a
329     // stable `const fn`, that is all that is required.
330     if !tcx.features().staged_api || tcx.has_attr(def_id, sym::rustc_const_unstable) {
331         return true;
332     }
333
334     // However, we cannot allow stable `const fn`s to use unstable features without an explicit
335     // opt-in via `allow_internal_unstable`.
336     attr::allow_internal_unstable(&tcx.get_attrs(def_id), &tcx.sess.diagnostic())
337         .map_or(false, |mut features| features.any(|name| name == feature_gate))
338 }
339
340 /// Returns `true` if the given library feature gate is allowed within the function with the given `DefId`.
341 pub fn lib_feature_allowed(tcx: TyCtxt<'tcx>, def_id: DefId, feature_gate: Symbol) -> bool {
342     // All features require that the corresponding gate be enabled,
343     // even if the function has `#[allow_internal_unstable(the_gate)]`.
344     if !tcx.features().declared_lib_features.iter().any(|&(sym, _)| sym == feature_gate) {
345         return false;
346     }
347
348     // If this crate is not using stability attributes, or this function is not claiming to be a
349     // stable `const fn`, that is all that is required.
350     if !tcx.features().staged_api || tcx.has_attr(def_id, sym::rustc_const_unstable) {
351         return true;
352     }
353
354     // However, we cannot allow stable `const fn`s to use unstable features without an explicit
355     // opt-in via `allow_internal_unstable`.
356     attr::allow_internal_unstable(&tcx.get_attrs(def_id), &tcx.sess.diagnostic())
357         .map_or(false, |mut features| features.any(|name| name == feature_gate))
358 }
359
360 fn check_terminator(
361     tcx: TyCtxt<'tcx>,
362     body: &'a Body<'tcx>,
363     def_id: DefId,
364     terminator: &Terminator<'tcx>,
365 ) -> McfResult {
366     let span = terminator.source_info.span;
367     match &terminator.kind {
368         TerminatorKind::FalseEdge { .. }
369         | TerminatorKind::FalseUnwind { .. }
370         | TerminatorKind::Goto { .. }
371         | TerminatorKind::Return
372         | TerminatorKind::Resume
373         | TerminatorKind::Unreachable => Ok(()),
374
375         TerminatorKind::Drop { place, .. } => check_place(tcx, *place, span, def_id, body),
376         TerminatorKind::DropAndReplace { place, value, .. } => {
377             check_place(tcx, *place, span, def_id, body)?;
378             check_operand(tcx, value, span, def_id, body)
379         }
380
381         TerminatorKind::SwitchInt { discr, switch_ty: _, values: _, targets: _ } => {
382             check_operand(tcx, discr, span, def_id, body)
383         }
384
385         TerminatorKind::Abort => Err((span, "abort is not stable in const fn".into())),
386         TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
387             Err((span, "const fn generators are unstable".into()))
388         }
389
390         TerminatorKind::Call {
391             func,
392             args,
393             from_hir_call: _,
394             destination: _,
395             cleanup: _,
396             fn_span: _,
397         } => {
398             let fn_ty = func.ty(body, tcx);
399             if let ty::FnDef(fn_def_id, _) = fn_ty.kind {
400                 // Allow unstable const if we opt in by using #[allow_internal_unstable]
401                 // on function or macro declaration.
402                 if !crate::const_eval::is_min_const_fn(tcx, fn_def_id)
403                     && !crate::const_eval::is_unstable_const_fn(tcx, fn_def_id)
404                         .map(|feature| {
405                             span.allows_unstable(feature)
406                                 || lib_feature_allowed(tcx, def_id, feature)
407                         })
408                         .unwrap_or(false)
409                 {
410                     return Err((
411                         span,
412                         format!(
413                             "can only call other `const fn` within a `const fn`, \
414                              but `{:?}` is not stable as `const fn`",
415                             func,
416                         )
417                         .into(),
418                     ));
419                 }
420
421                 check_operand(tcx, func, span, fn_def_id, body)?;
422
423                 for arg in args {
424                     check_operand(tcx, arg, span, fn_def_id, body)?;
425                 }
426                 Ok(())
427             } else {
428                 Err((span, "can only call other const fns within const fn".into()))
429             }
430         }
431
432         TerminatorKind::Assert { cond, expected: _, msg: _, target: _, cleanup: _ } => {
433             check_operand(tcx, cond, span, def_id, body)
434         }
435
436         TerminatorKind::InlineAsm { .. } => {
437             Err((span, "cannot use inline assembly in const fn".into()))
438         }
439     }
440 }