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