]> git.lizzy.rs Git - rust.git/blob - src/librustc_mir/transform/qualify_min_const_fn.rs
Put Local, Static and Promoted as one Base variant of Place
[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::UnsafeFnPointer, _, _) |
156         Rvalue::Cast(CastKind::ClosureFnPointer, _, _) |
157         Rvalue::Cast(CastKind::ReifyFnPointer, _, _) => Err((
158             span,
159             "function pointer casts are not allowed in const fn".into(),
160         )),
161         Rvalue::Cast(CastKind::Unsize, _, _) => Err((
162             span,
163             "unsizing casts are not allowed in const fn".into(),
164         )),
165         // binops are fine on integers
166         Rvalue::BinaryOp(_, lhs, rhs) | Rvalue::CheckedBinaryOp(_, lhs, rhs) => {
167             check_operand(tcx, mir, lhs, span)?;
168             check_operand(tcx, mir, rhs, span)?;
169             let ty = lhs.ty(mir, tcx);
170             if ty.is_integral() || ty.is_bool() || ty.is_char() {
171                 Ok(())
172             } else {
173                 Err((
174                     span,
175                     "only int, `bool` and `char` operations are stable in const fn".into(),
176                 ))
177             }
178         }
179         Rvalue::NullaryOp(NullOp::SizeOf, _) => Ok(()),
180         Rvalue::NullaryOp(NullOp::Box, _) => Err((
181             span,
182             "heap allocations are not allowed in const fn".into(),
183         )),
184         Rvalue::UnaryOp(_, operand) => {
185             let ty = operand.ty(mir, tcx);
186             if ty.is_integral() || ty.is_bool() {
187                 check_operand(tcx, mir, operand, span)
188             } else {
189                 Err((
190                     span,
191                     "only int and `bool` operations are stable in const fn".into(),
192                 ))
193             }
194         }
195         Rvalue::Aggregate(_, operands) => {
196             for operand in operands {
197                 check_operand(tcx, mir, operand, span)?;
198             }
199             Ok(())
200         }
201     }
202 }
203
204 fn check_statement(
205     tcx: TyCtxt<'a, 'tcx, 'tcx>,
206     mir: &'a Mir<'tcx>,
207     statement: &Statement<'tcx>,
208 ) -> McfResult {
209     let span = statement.source_info.span;
210     match &statement.kind {
211         StatementKind::Assign(place, rval) => {
212             check_place(tcx, mir, place, span)?;
213             check_rvalue(tcx, mir, rval, span)
214         }
215
216         StatementKind::FakeRead(_, place) => check_place(tcx, mir, place, span),
217
218         // just an assignment
219         StatementKind::SetDiscriminant { .. } => Ok(()),
220
221         | StatementKind::InlineAsm { .. } => {
222             Err((span, "cannot use inline assembly in const fn".into()))
223         }
224
225         // These are all NOPs
226         | StatementKind::StorageLive(_)
227         | StatementKind::StorageDead(_)
228         | StatementKind::Retag { .. }
229         | StatementKind::AscribeUserType(..)
230         | StatementKind::Nop => Ok(()),
231     }
232 }
233
234 fn check_operand(
235     tcx: TyCtxt<'a, 'tcx, 'tcx>,
236     mir: &'a Mir<'tcx>,
237     operand: &Operand<'tcx>,
238     span: Span,
239 ) -> McfResult {
240     match operand {
241         Operand::Move(place) | Operand::Copy(place) => {
242             check_place(tcx, mir, place, span)
243         }
244         Operand::Constant(_) => Ok(()),
245     }
246 }
247
248 fn check_place(
249     tcx: TyCtxt<'a, 'tcx, 'tcx>,
250     mir: &'a Mir<'tcx>,
251     place: &Place<'tcx>,
252     span: Span,
253 ) -> McfResult {
254     match place {
255         Place::Base(PlaceBase::Local(_)) => Ok(()),
256         // promoteds are always fine, they are essentially constants
257         Place::Base(PlaceBase::Promoted(_)) => Ok(()),
258         Place::Base(PlaceBase::Static(_)) =>
259             Err((span, "cannot access `static` items in const fn".into())),
260         Place::Projection(proj) => {
261             match proj.elem {
262                 | ProjectionElem::ConstantIndex { .. } | ProjectionElem::Subslice { .. }
263                 | ProjectionElem::Deref | ProjectionElem::Field(..) | ProjectionElem::Index(_) => {
264                     check_place(tcx, mir, &proj.base, span)
265                 }
266                 | ProjectionElem::Downcast(..) => {
267                     Err((span, "`match` or `if let` in `const fn` is unstable".into()))
268                 }
269             }
270         }
271     }
272 }
273
274 fn check_terminator(
275     tcx: TyCtxt<'a, 'tcx, 'tcx>,
276     mir: &'a Mir<'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(tcx, mir, location, span)
287         }
288         TerminatorKind::DropAndReplace { location, value, .. } => {
289             check_place(tcx, mir, location, span)?;
290             check_operand(tcx, mir, value, span)
291         },
292
293         TerminatorKind::FalseEdges { .. } | TerminatorKind::SwitchInt { .. } => Err((
294             span,
295             "`if`, `match`, `&&` and `||` 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(mir, 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                         "can only call other `min_const_fn` within a `min_const_fn`".into(),
327                     )),
328                     abi => return Err((
329                         span,
330                         format!(
331                             "cannot call functions with `{}` abi in `min_const_fn`",
332                             abi,
333                         ).into(),
334                     )),
335                 }
336
337                 check_operand(tcx, mir, func, span)?;
338
339                 for arg in args {
340                     check_operand(tcx, mir, arg, span)?;
341                 }
342                 Ok(())
343             } else {
344                 Err((span, "can only call other const fns within const fn".into()))
345             }
346         }
347
348         TerminatorKind::Assert {
349             cond,
350             expected: _,
351             msg: _,
352             target: _,
353             cleanup: _,
354         } => check_operand(tcx, mir, cond, span),
355
356         TerminatorKind::FalseUnwind { .. } => {
357             Err((span, "loops are not allowed in const fn".into()))
358         },
359     }
360 }
361
362 /// Returns `true` if the `def_id` refers to an intrisic which we've whitelisted
363 /// for being called from stable `const fn`s (`min_const_fn`).
364 ///
365 /// Adding more intrinsics requires sign-off from @rust-lang/lang.
366 fn is_intrinsic_whitelisted(tcx: TyCtxt<'a, 'tcx, 'tcx>, def_id: DefId) -> bool {
367     match &tcx.item_name(def_id).as_str()[..] {
368         | "size_of"
369         | "min_align_of"
370         | "needs_drop"
371         // Arithmetic:
372         | "add_with_overflow" // ~> .overflowing_add
373         | "sub_with_overflow" // ~> .overflowing_sub
374         | "mul_with_overflow" // ~> .overflowing_mul
375         | "overflowing_add" // ~> .wrapping_add
376         | "overflowing_sub" // ~> .wrapping_sub
377         | "overflowing_mul" // ~> .wrapping_mul
378         | "saturating_add" // ~> .saturating_add
379         | "saturating_sub" // ~> .saturating_sub
380         | "unchecked_shl" // ~> .wrapping_shl
381         | "unchecked_shr" // ~> .wrapping_shr
382         | "rotate_left" // ~> .rotate_left
383         | "rotate_right" // ~> .rotate_right
384         | "ctpop" // ~> .count_ones
385         | "ctlz" // ~> .leading_zeros
386         | "cttz" // ~> .trailing_zeros
387         | "bswap" // ~> .swap_bytes
388         | "bitreverse" // ~> .reverse_bits
389         => true,
390         _ => false,
391     }
392 }