]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/qualify_min_const_fn.rs
Convert Place's projection to a boxed slice
[rust.git] / src / librustc_mir / transform / qualify_min_const_fn.rs
1 use rustc::hir::def_id::DefId;
2 use rustc::hir;
3 use rustc::mir::*;
4 use rustc::ty::{self, Predicate, Ty, TyCtxt, adjustment::{PointerCast}};
5 use rustc_target::spec::abi;
6 use std::borrow::Cow;
7 use syntax_pos::Span;
8
9 type McfResult = Result<(), (Span, Cow<'static, str>)>;
10
11 pub fn is_min_const_fn(tcx: TyCtxt<'tcx>, def_id: DefId, body: &'a Body<'tcx>) -> McfResult {
12     let mut current = def_id;
13     loop {
14         let predicates = tcx.predicates_of(current);
15         for (predicate, _) in &predicates.predicates {
16             match predicate {
17                 | Predicate::RegionOutlives(_)
18                 | Predicate::TypeOutlives(_)
19                 | Predicate::WellFormed(_)
20                 | Predicate::Projection(_)
21                 | Predicate::ConstEvaluatable(..) => continue,
22                 | Predicate::ObjectSafe(_) => {
23                     bug!("object safe predicate on function: {:#?}", predicate)
24                 }
25                 Predicate::ClosureKind(..) => {
26                     bug!("closure kind predicate on function: {:#?}", predicate)
27                 }
28                 Predicate::Subtype(_) => bug!("subtype predicate on function: {:#?}", predicate),
29                 Predicate::Trait(pred) => {
30                     if Some(pred.def_id()) == tcx.lang_items().sized_trait() {
31                         continue;
32                     }
33                     match pred.skip_binder().self_ty().sty {
34                         ty::Param(ref p) => {
35                             let generics = tcx.generics_of(current);
36                             let def = generics.type_param(p, tcx);
37                             let span = tcx.def_span(def.def_id);
38                             return Err((
39                                 span,
40                                 "trait bounds other than `Sized` \
41                                  on const fn parameters are unstable"
42                                     .into(),
43                             ));
44                         }
45                         // other kinds of bounds are either tautologies
46                         // or cause errors in other passes
47                         _ => continue,
48                     }
49                 }
50             }
51         }
52         match predicates.parent {
53             Some(parent) => current = parent,
54             None => break,
55         }
56     }
57
58     for local in &body.local_decls {
59         check_ty(tcx, local.ty, local.source_info.span, def_id)?;
60     }
61     // impl trait is gone in MIR, so check the return type manually
62     check_ty(
63         tcx,
64         tcx.fn_sig(def_id).output().skip_binder(),
65         body.local_decls.iter().next().unwrap().source_info.span,
66         def_id,
67     )?;
68
69     for bb in body.basic_blocks() {
70         check_terminator(tcx, body, bb.terminator())?;
71         for stmt in &bb.statements {
72             check_statement(tcx, body, stmt)?;
73         }
74     }
75     Ok(())
76 }
77
78 fn check_ty(tcx: TyCtxt<'tcx>, ty: Ty<'tcx>, span: Span, fn_def_id: DefId) -> McfResult {
79     for ty in ty.walk() {
80         match ty.sty {
81             ty::Ref(_, _, hir::Mutability::MutMutable) => return Err((
82                 span,
83                 "mutable references in const fn are unstable".into(),
84             )),
85             ty::Opaque(..) => return Err((span, "`impl Trait` in const fn is unstable".into())),
86             ty::FnPtr(..) => {
87                 if !tcx.const_fn_is_allowed_fn_ptr(fn_def_id) {
88                     return Err((span, "function pointers in const fn are unstable".into()))
89                 }
90             }
91             ty::Dynamic(preds, _) => {
92                 for pred in preds.iter() {
93                     match pred.skip_binder() {
94                         | ty::ExistentialPredicate::AutoTrait(_)
95                         | ty::ExistentialPredicate::Projection(_) => {
96                             return Err((
97                                 span,
98                                 "trait bounds other than `Sized` \
99                                  on const fn parameters are unstable"
100                                     .into(),
101                             ))
102                         }
103                         ty::ExistentialPredicate::Trait(trait_ref) => {
104                             if Some(trait_ref.def_id) != tcx.lang_items().sized_trait() {
105                                 return Err((
106                                     span,
107                                     "trait bounds other than `Sized` \
108                                      on const fn parameters are unstable"
109                                         .into(),
110                                 ));
111                             }
112                         }
113                     }
114                 }
115             }
116             _ => {}
117         }
118     }
119     Ok(())
120 }
121
122 fn check_rvalue(
123     tcx: TyCtxt<'tcx>,
124     body: &'a Body<'tcx>,
125     rvalue: &Rvalue<'tcx>,
126     span: Span,
127 ) -> McfResult {
128     match rvalue {
129         Rvalue::Repeat(operand, _) | Rvalue::Use(operand) => {
130             check_operand(operand, span)
131         }
132         Rvalue::Len(place) | Rvalue::Discriminant(place) | Rvalue::Ref(_, _, place) => {
133             check_place(place, span)
134         }
135         Rvalue::Cast(CastKind::Misc, operand, cast_ty) => {
136             use rustc::ty::cast::CastTy;
137             let cast_in = CastTy::from_ty(operand.ty(body, tcx)).expect("bad input type for cast");
138             let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
139             match (cast_in, cast_out) {
140                 (CastTy::Ptr(_), CastTy::Int(_)) | (CastTy::FnPtr, CastTy::Int(_)) => Err((
141                     span,
142                     "casting pointers to ints is unstable in const fn".into(),
143                 )),
144                 (CastTy::RPtr(_), CastTy::Float) => bug!(),
145                 (CastTy::RPtr(_), CastTy::Int(_)) => bug!(),
146                 (CastTy::Ptr(_), CastTy::RPtr(_)) => bug!(),
147                 _ => check_operand(operand, span),
148             }
149         }
150         Rvalue::Cast(CastKind::Pointer(PointerCast::MutToConstPointer), operand, _) => {
151             check_operand(operand, span)
152         }
153         Rvalue::Cast(CastKind::Pointer(PointerCast::UnsafeFnPointer), _, _) |
154         Rvalue::Cast(CastKind::Pointer(PointerCast::ClosureFnPointer(_)), _, _) |
155         Rvalue::Cast(CastKind::Pointer(PointerCast::ReifyFnPointer), _, _) => Err((
156             span,
157             "function pointer casts are not allowed in const fn".into(),
158         )),
159         Rvalue::Cast(CastKind::Pointer(PointerCast::Unsize), _, _) => Err((
160             span,
161             "unsizing casts are not allowed in const fn".into(),
162         )),
163         // binops are fine on integers
164         Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
165             check_operand(lhs, span)?;
166             check_operand(rhs, span)?;
167             let ty = lhs.ty(body, tcx);
168             if ty.is_integral() || ty.is_bool() || ty.is_char() {
169                 Ok(())
170             } else {
171                 Err((
172                     span,
173                     "only int, `bool` and `char` operations are stable in const fn".into(),
174                 ))
175             }
176         }
177         Rvalue::NullaryOp(NullOp::SizeOf, _) => Ok(()),
178         Rvalue::NullaryOp(NullOp::Box, _) => Err((
179             span,
180             "heap allocations are not allowed in const fn".into(),
181         )),
182         Rvalue::UnaryOp(_, operand) => {
183             let ty = operand.ty(body, tcx);
184             if ty.is_integral() || ty.is_bool() {
185                 check_operand(operand, span)
186             } else {
187                 Err((
188                     span,
189                     "only int and `bool` operations are stable in const fn".into(),
190                 ))
191             }
192         }
193         Rvalue::Aggregate(_, operands) => {
194             for operand in operands {
195                 check_operand(operand, span)?;
196             }
197             Ok(())
198         }
199     }
200 }
201
202 fn check_statement(
203     tcx: TyCtxt<'tcx>,
204     body: &'a Body<'tcx>,
205     statement: &Statement<'tcx>,
206 ) -> McfResult {
207     let span = statement.source_info.span;
208     match &statement.kind {
209         StatementKind::Assign(place, rval) => {
210             check_place(place, span)?;
211             check_rvalue(tcx, body, rval, span)
212         }
213
214         StatementKind::FakeRead(FakeReadCause::ForMatchedPlace, _) => {
215             Err((span, "loops and conditional expressions are not stable in const fn".into()))
216         }
217
218         StatementKind::FakeRead(_, place) => check_place(place, span),
219
220         // just an assignment
221         StatementKind::SetDiscriminant { .. } => Ok(()),
222
223         | StatementKind::InlineAsm { .. } => {
224             Err((span, "cannot use inline assembly in const fn".into()))
225         }
226
227         // These are all NOPs
228         | StatementKind::StorageLive(_)
229         | StatementKind::StorageDead(_)
230         | StatementKind::Retag { .. }
231         | StatementKind::AscribeUserType(..)
232         | StatementKind::Nop => Ok(()),
233     }
234 }
235
236 fn check_operand(
237     operand: &Operand<'tcx>,
238     span: Span,
239 ) -> McfResult {
240     match operand {
241         Operand::Move(place) | Operand::Copy(place) => {
242             check_place(place, span)
243         }
244         Operand::Constant(_) => Ok(()),
245     }
246 }
247
248 fn check_place(
249     place: &Place<'tcx>,
250     span: Span,
251 ) -> McfResult {
252     for elem in place.projection.iter() {
253         match elem {
254             ProjectionElem::Downcast(..) => {
255                 return Err((span, "`match` or `if let` in `const fn` is unstable".into()));
256             }
257             ProjectionElem::ConstantIndex { .. }
258             | ProjectionElem::Subslice { .. }
259             | ProjectionElem::Deref
260             | ProjectionElem::Field(..)
261             | ProjectionElem::Index(_) => {}
262         }
263     }
264
265     match place.base {
266         PlaceBase::Static(box Static { kind: StaticKind::Static, .. }) => {
267             Err((span, "cannot access `static` items in const fn".into()))
268         }
269         PlaceBase::Local(_)
270         | PlaceBase::Static(box Static { kind: StaticKind::Promoted(_, _), .. }) => Ok(()),
271     }
272 }
273
274 fn check_terminator(
275     tcx: TyCtxt<'tcx>,
276     body: &'a Body<'tcx>,
277     terminator: &Terminator<'tcx>,
278 ) -> McfResult {
279     let span = terminator.source_info.span;
280     match &terminator.kind {
281         | TerminatorKind::Goto { .. }
282         | TerminatorKind::Return
283         | TerminatorKind::Resume => Ok(()),
284
285         TerminatorKind::Drop { location, .. } => {
286             check_place(location, span)
287         }
288         TerminatorKind::DropAndReplace { location, value, .. } => {
289             check_place(location, span)?;
290             check_operand(value, span)
291         },
292
293         TerminatorKind::FalseEdges { .. } | TerminatorKind::SwitchInt { .. } => Err((
294             span,
295             "loops and conditional expressions are not stable in const fn".into(),
296         )),
297         | TerminatorKind::Abort | TerminatorKind::Unreachable => {
298             Err((span, "const fn with unreachable code is not stable".into()))
299         }
300         | TerminatorKind::GeneratorDrop | TerminatorKind::Yield { .. } => {
301             Err((span, "const fn generators are unstable".into()))
302         }
303
304         TerminatorKind::Call {
305             func,
306             args,
307             from_hir_call: _,
308             destination: _,
309             cleanup: _,
310         } => {
311             let fn_ty = func.ty(body, tcx);
312             if let ty::FnDef(def_id, _) = fn_ty.sty {
313
314                 // some intrinsics are waved through if called inside the
315                 // standard library. Users never need to call them directly
316                 match tcx.fn_sig(def_id).abi() {
317                     abi::Abi::RustIntrinsic => if !is_intrinsic_whitelisted(tcx, def_id) {
318                         return Err((
319                             span,
320                             "can only call a curated list of intrinsics in `min_const_fn`".into(),
321                         ))
322                     },
323                     abi::Abi::Rust if tcx.is_min_const_fn(def_id) => {},
324                     abi::Abi::Rust => return Err((
325                         span,
326                         format!(
327                             "can only call other `const fn` within a `const fn`, \
328                              but `{:?}` is not stable as `const fn`",
329                             func,
330                         )
331                         .into(),
332                     )),
333                     abi => return Err((
334                         span,
335                         format!(
336                             "cannot call functions with `{}` abi in `min_const_fn`",
337                             abi,
338                         ).into(),
339                     )),
340                 }
341
342                 check_operand(func, span)?;
343
344                 for arg in args {
345                     check_operand(arg, span)?;
346                 }
347                 Ok(())
348             } else {
349                 Err((span, "can only call other const fns within const fn".into()))
350             }
351         }
352
353         TerminatorKind::Assert {
354             cond,
355             expected: _,
356             msg: _,
357             target: _,
358             cleanup: _,
359         } => check_operand(cond, span),
360
361         TerminatorKind::FalseUnwind { .. } => {
362             Err((span, "loops are not allowed in const fn".into()))
363         },
364     }
365 }
366
367 /// Returns `true` if the `def_id` refers to an intrisic which we've whitelisted
368 /// for being called from stable `const fn`s (`min_const_fn`).
369 ///
370 /// Adding more intrinsics requires sign-off from @rust-lang/lang.
371 fn is_intrinsic_whitelisted(tcx: TyCtxt<'tcx>, def_id: DefId) -> bool {
372     match &tcx.item_name(def_id).as_str()[..] {
373         | "size_of"
374         | "min_align_of"
375         | "needs_drop"
376         // Arithmetic:
377         | "add_with_overflow" // ~> .overflowing_add
378         | "sub_with_overflow" // ~> .overflowing_sub
379         | "mul_with_overflow" // ~> .overflowing_mul
380         | "wrapping_add" // ~> .wrapping_add
381         | "wrapping_sub" // ~> .wrapping_sub
382         | "wrapping_mul" // ~> .wrapping_mul
383         | "saturating_add" // ~> .saturating_add
384         | "saturating_sub" // ~> .saturating_sub
385         | "unchecked_shl" // ~> .wrapping_shl
386         | "unchecked_shr" // ~> .wrapping_shr
387         | "rotate_left" // ~> .rotate_left
388         | "rotate_right" // ~> .rotate_right
389         | "ctpop" // ~> .count_ones
390         | "ctlz" // ~> .leading_zeros
391         | "cttz" // ~> .trailing_zeros
392         | "bswap" // ~> .swap_bytes
393         | "bitreverse" // ~> .reverse_bits
394         => true,
395         _ => false,
396     }
397 }