1 // Copyright 2016 The Rust Project Developers. See the COPYRIGHT
2 // file at the top-level directory of this distribution and at
3 // http://rust-lang.org/COPYRIGHT.
5 // Licensed under the Apache License, Version 2.0 <LICENSE-APACHE or
6 // http://www.apache.org/licenses/LICENSE-2.0> or the MIT license
7 // <LICENSE-MIT or http://opensource.org/licenses/MIT>, at your
8 // option. This file may not be copied, modified, or distributed
9 // except according to those terms.
11 //! A pass that qualifies constness of temporaries in constants,
12 //! static initializers and functions and also drives promotion.
14 //! The Qualif flags below can be used to also provide better
15 //! diagnostics as to why a constant rvalue wasn't promoted.
17 use rustc_data_structures::bitvec::BitArray;
18 use rustc_data_structures::indexed_set::IdxSetBuf;
19 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
20 use rustc_data_structures::fx::FxHashSet;
22 use rustc::hir::def_id::DefId;
23 use rustc::mir::interpret::ConstValue;
24 use rustc::traits::{self, TraitEngine};
25 use rustc::ty::{self, TyCtxt, Ty, TypeFoldable};
26 use rustc::ty::cast::CastTy;
27 use rustc::ty::query::Providers;
29 use rustc::mir::traversal::ReversePostorder;
30 use rustc::mir::visit::{PlaceContext, Visitor};
31 use rustc::middle::lang_items;
32 use rustc_target::spec::abi::Abi;
34 use syntax::ast::LitKind;
35 use syntax::feature_gate::{UnstableFeatures, feature_err, emit_feature_err, GateIssue};
36 use syntax_pos::{Span, DUMMY_SP};
39 use rustc_data_structures::sync::Lrc;
42 use transform::{MirPass, MirSource};
43 use super::promote_consts::{self, Candidate, TempState};
46 // Borrows of temporaries can be promoted only if
47 // they have none of these qualifications, with
48 // the exception of `STATIC_REF` (in statics only).
50 // Constant containing interior mutability (UnsafeCell).
51 const MUTABLE_INTERIOR = 1 << 0;
53 // Constant containing an ADT that implements Drop.
54 const NEEDS_DROP = 1 << 1;
57 const FN_ARGUMENT = 1 << 2;
59 // Not constant at all - non-`const fn` calls, asm!,
60 // pointer comparisons, ptr-to-int casts, etc.
61 const NOT_CONST = 1 << 3;
63 // Refers to temporaries which cannot be promoted as
64 // promote_consts decided they weren't simple enough.
65 const NOT_PROMOTABLE = 1 << 4;
67 // Const items can only have MUTABLE_INTERIOR
68 // and NOT_PROMOTABLE without producing an error.
69 const CONST_ERROR = !Qualif::MUTABLE_INTERIOR.bits &
70 !Qualif::NOT_PROMOTABLE.bits;
74 impl<'a, 'tcx> Qualif {
75 /// Remove flags which are impossible for the given type.
76 fn restrict(&mut self, ty: Ty<'tcx>,
77 tcx: TyCtxt<'a, 'tcx, 'tcx>,
78 param_env: ty::ParamEnv<'tcx>) {
79 if ty.is_freeze(tcx, param_env, DUMMY_SP) {
80 *self = *self - Qualif::MUTABLE_INTERIOR;
82 if !ty.needs_drop(tcx, param_env) {
83 *self = *self - Qualif::NEEDS_DROP;
88 /// What kind of item we are in.
89 #[derive(Copy, Clone, PartialEq, Eq)]
98 impl fmt::Display for Mode {
99 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
101 Mode::Const => write!(f, "constant"),
102 Mode::Static | Mode::StaticMut => write!(f, "static"),
103 Mode::ConstFn => write!(f, "constant function"),
104 Mode::Fn => write!(f, "function")
109 struct Qualifier<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
114 rpo: ReversePostorder<'a, 'tcx>,
115 tcx: TyCtxt<'a, 'gcx, 'tcx>,
116 param_env: ty::ParamEnv<'tcx>,
117 local_qualif: IndexVec<Local, Option<Qualif>>,
119 const_fn_arg_vars: BitArray<Local>,
120 temp_promotion_state: IndexVec<Local, TempState>,
121 promotion_candidates: Vec<Candidate>
124 impl<'a, 'tcx> Qualifier<'a, 'tcx, 'tcx> {
125 fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
129 -> Qualifier<'a, 'tcx, 'tcx> {
130 let mut rpo = traversal::reverse_postorder(mir);
131 let temps = promote_consts::collect_temps(mir, &mut rpo);
134 let param_env = tcx.param_env(def_id);
136 let mut local_qualif = IndexVec::from_elem(None, &mir.local_decls);
137 for arg in mir.args_iter() {
138 let mut qualif = Qualif::NEEDS_DROP;
139 qualif.restrict(mir.local_decls[arg].ty, tcx, param_env);
140 local_qualif[arg] = Some(qualif);
152 qualif: Qualif::empty(),
153 const_fn_arg_vars: BitArray::new(mir.local_decls.len()),
154 temp_promotion_state: temps,
155 promotion_candidates: vec![]
159 // FIXME(eddyb) we could split the errors into meaningful
160 // categories, but enabling full miri would make that
161 // slightly pointless (even with feature-gating).
162 fn not_const(&mut self) {
163 self.add(Qualif::NOT_CONST);
164 if self.mode != Mode::Fn {
165 let mut err = struct_span_err!(
169 "{} contains unimplemented expression type",
172 if self.tcx.sess.teach(&err.get_code().unwrap()) {
173 err.note("A function call isn't allowed in the const's initialization expression \
174 because the expression's value must be known at compile-time.");
175 err.note("Remember: you can't use a function call inside a const's initialization \
176 expression! However, you can use it anywhere else.");
182 /// Error about extra statements in a constant.
183 fn statement_like(&mut self) {
184 self.add(Qualif::NOT_CONST);
185 if self.mode != Mode::Fn {
186 let mut err = feature_err(
187 &self.tcx.sess.parse_sess,
191 &format!("statements in {}s are unstable", self.mode),
193 if self.tcx.sess.teach(&err.get_code().unwrap()) {
194 err.note("Blocks in constants may only contain items (such as constant, function \
195 definition, etc...) and a tail expression.");
196 err.help("To avoid it, you have to replace the non-item object.");
202 /// Add the given qualification to self.qualif.
203 fn add(&mut self, qualif: Qualif) {
204 self.qualif = self.qualif | qualif;
207 /// Add the given type's qualification to self.qualif.
208 fn add_type(&mut self, ty: Ty<'tcx>) {
209 self.add(Qualif::MUTABLE_INTERIOR | Qualif::NEEDS_DROP);
210 self.qualif.restrict(ty, self.tcx, self.param_env);
213 /// Within the provided closure, self.qualif will start
214 /// out empty, and its value after the closure returns will
215 /// be combined with the value before the call to nest.
216 fn nest<F: FnOnce(&mut Self)>(&mut self, f: F) {
217 let original = self.qualif;
218 self.qualif = Qualif::empty();
223 /// Assign the current qualification to the given destination.
224 fn assign(&mut self, dest: &Place<'tcx>, location: Location) {
225 trace!("assign: {:?}", dest);
226 let qualif = self.qualif;
227 let span = self.span;
228 let store = |slot: &mut Option<Qualif>| {
230 span_bug!(span, "multiple assignments to {:?}", dest);
232 *slot = Some(qualif);
235 // Only handle promotable temps in non-const functions.
236 if self.mode == Mode::Fn {
237 if let Place::Local(index) = *dest {
238 if self.mir.local_kind(index) == LocalKind::Temp
239 && self.temp_promotion_state[index].is_promotable() {
240 debug!("store to promotable temp {:?} ({:?})", index, qualif);
241 store(&mut self.local_qualif[index]);
248 Place::Local(index) if (self.mir.local_kind(index) == LocalKind::Var ||
249 self.mir.local_kind(index) == LocalKind::Arg) &&
250 self.tcx.sess.features_untracked().const_let => {
251 debug!("store to var {:?}", index);
252 self.local_qualif[index] = Some(self.qualif);
254 Place::Local(index) if self.mir.local_kind(index) == LocalKind::Temp ||
255 self.mir.local_kind(index) == LocalKind::ReturnPointer => {
256 debug!("store to {:?} (temp or return pointer)", index);
257 store(&mut self.local_qualif[index])
260 Place::Projection(box Projection {
261 base: Place::Local(index),
262 elem: ProjectionElem::Deref
263 }) if self.mir.local_kind(index) == LocalKind::Temp
264 && self.mir.local_decls[index].ty.is_box()
265 && self.local_qualif[index].map_or(false, |qualif| {
266 qualif.contains(Qualif::NOT_CONST)
268 // Part of `box expr`, we should've errored
269 // already for the Box allocation Rvalue.
272 // This must be an explicit assignment.
274 // Catch more errors in the destination.
275 self.visit_place(dest, PlaceContext::Store, location);
276 self.statement_like();
281 /// Qualify a whole const, static initializer or const fn.
282 fn qualify_const(&mut self) -> (Qualif, Lrc<IdxSetBuf<Local>>) {
283 debug!("qualifying {} {:?}", self.mode, self.def_id);
287 let mut seen_blocks = BitArray::new(mir.basic_blocks().len());
288 let mut bb = START_BLOCK;
290 seen_blocks.insert(bb.index());
292 self.visit_basic_block_data(bb, &mir[bb]);
294 let target = match mir[bb].terminator().kind {
295 TerminatorKind::Goto { target } |
296 TerminatorKind::Drop { target, .. } |
297 TerminatorKind::Assert { target, .. } |
298 TerminatorKind::Call { destination: Some((_, target)), .. } => {
302 // Non-terminating calls cannot produce any value.
303 TerminatorKind::Call { destination: None, .. } => {
307 TerminatorKind::SwitchInt {..} |
308 TerminatorKind::DropAndReplace { .. } |
309 TerminatorKind::Resume |
310 TerminatorKind::Abort |
311 TerminatorKind::GeneratorDrop |
312 TerminatorKind::Yield { .. } |
313 TerminatorKind::Unreachable |
314 TerminatorKind::FalseEdges { .. } |
315 TerminatorKind::FalseUnwind { .. } => None,
317 TerminatorKind::Return => {
318 if !self.tcx.sess.features_untracked().const_let {
319 // Check for unused values. This usually means
320 // there are extra statements in the AST.
321 for temp in mir.temps_iter() {
322 if self.local_qualif[temp].is_none() {
326 let state = self.temp_promotion_state[temp];
327 if let TempState::Defined { location, uses: 0 } = state {
328 let data = &mir[location.block];
329 let stmt_idx = location.statement_index;
331 // Get the span for the initialization.
332 let source_info = if stmt_idx < data.statements.len() {
333 data.statements[stmt_idx].source_info
335 data.terminator().source_info
337 self.span = source_info.span;
339 // Treat this as a statement in the AST.
340 self.statement_like();
344 // Make sure there are no extra unassigned variables.
345 self.qualif = Qualif::NOT_CONST;
346 for index in mir.vars_iter() {
347 if !self.const_fn_arg_vars.contains(index) {
348 debug!("unassigned variable {:?}", index);
349 self.assign(&Place::Local(index), Location {
351 statement_index: usize::MAX,
363 Some(target) if !seen_blocks.contains(target.index()) => {
373 self.qualif = self.local_qualif[RETURN_PLACE].unwrap_or(Qualif::NOT_CONST);
375 // Account for errors in consts by using the
376 // conservative type qualification instead.
377 if self.qualif.intersects(Qualif::CONST_ERROR) {
378 self.qualif = Qualif::empty();
379 let return_ty = mir.return_ty();
380 self.add_type(return_ty);
384 // Collect all the temps we need to promote.
385 let mut promoted_temps = IdxSetBuf::new_empty(self.temp_promotion_state.len());
387 for candidate in &self.promotion_candidates {
389 Candidate::Ref(Location { block: bb, statement_index: stmt_idx }) => {
390 match self.mir[bb].statements[stmt_idx].kind {
391 StatementKind::Assign(_, Rvalue::Ref(_, _, Place::Local(index))) => {
392 promoted_temps.add(&index);
397 Candidate::Argument { .. } => {}
401 (self.qualif, Lrc::new(promoted_temps))
405 /// Accumulates an Rvalue or Call's effects in self.qualif.
406 /// For functions (constant or not), it also records
407 /// candidates for promotion in promotion_candidates.
408 impl<'a, 'tcx> Visitor<'tcx> for Qualifier<'a, 'tcx, 'tcx> {
409 fn visit_local(&mut self,
411 _: PlaceContext<'tcx>,
413 let kind = self.mir.local_kind(local);
415 LocalKind::ReturnPointer => {
418 LocalKind::Var if !self.tcx.sess.features_untracked().const_let => {
419 if self.mode != Mode::Fn {
420 emit_feature_err(&self.tcx.sess.parse_sess, "const_let",
421 self.span, GateIssue::Language,
422 &format!("let bindings in {}s are unstable",self.mode));
424 self.add(Qualif::NOT_CONST);
429 if let LocalKind::Arg = kind {
430 self.add(Qualif::FN_ARGUMENT);
433 if !self.temp_promotion_state[local].is_promotable() {
434 self.add(Qualif::NOT_PROMOTABLE);
437 if let Some(qualif) = self.local_qualif[local] {
446 fn visit_place(&mut self,
448 context: PlaceContext<'tcx>,
449 location: Location) {
451 Place::Local(ref local) => self.visit_local(local, context, location),
452 Place::Promoted(_) => bug!("promoting already promoted MIR"),
453 Place::Static(ref global) => {
455 .get_attrs(global.def_id)
457 .any(|attr| attr.check_name("thread_local")) {
458 if self.mode != Mode::Fn {
459 span_err!(self.tcx.sess, self.span, E0625,
460 "thread-local statics cannot be \
461 accessed at compile-time");
463 self.add(Qualif::NOT_CONST);
467 // Only allow statics (not consts) to refer to other statics.
468 if self.mode == Mode::Static || self.mode == Mode::StaticMut {
471 self.add(Qualif::NOT_CONST);
473 if self.mode != Mode::Fn {
474 let mut err = struct_span_err!(self.tcx.sess, self.span, E0013,
475 "{}s cannot refer to statics, use \
476 a constant instead", self.mode);
477 if self.tcx.sess.teach(&err.get_code().unwrap()) {
479 "Static and const variables can refer to other const variables. But a \
480 const variable cannot refer to a static variable."
483 "To fix this, the value can be extracted as a const and then used."
489 Place::Projection(ref proj) => {
491 this.super_place(place, context, location);
493 ProjectionElem::Deref => {
494 this.add(Qualif::NOT_CONST);
496 let base_ty = proj.base.ty(this.mir, this.tcx).to_ty(this.tcx);
497 if let ty::TyRawPtr(_) = base_ty.sty {
498 if this.mode != Mode::Fn &&
499 !this.tcx.sess.features_untracked().const_raw_ptr_deref {
501 &this.tcx.sess.parse_sess, "const_raw_ptr_deref",
502 this.span, GateIssue::Language,
504 "dereferencing raw pointers in {}s is unstable",
512 ProjectionElem::Field(..) |
513 ProjectionElem::Index(_) => {
514 let base_ty = proj.base.ty(this.mir, this.tcx).to_ty(this.tcx);
515 if let Some(def) = base_ty.ty_adt_def() {
520 if !this.tcx.sess.features_untracked().const_fn_union {
522 &this.tcx.sess.parse_sess, "const_fn_union",
523 this.span, GateIssue::Language,
524 "unions in const fn are unstable",
537 let ty = place.ty(this.mir, this.tcx).to_ty(this.tcx);
538 this.qualif.restrict(ty, this.tcx, this.param_env);
541 ProjectionElem::ConstantIndex {..} |
542 ProjectionElem::Subslice {..} |
543 ProjectionElem::Downcast(..) => {
552 fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
553 self.super_operand(operand, location);
557 Operand::Move(_) => {
558 // Mark the consumed locals to indicate later drops are noops.
559 if let Operand::Move(Place::Local(local)) = *operand {
560 self.local_qualif[local] = self.local_qualif[local].map(|q|
561 q - Qualif::NEEDS_DROP
565 Operand::Constant(ref constant) => {
566 if let ConstValue::Unevaluated(def_id, _) = constant.literal.val {
567 // Don't peek inside trait associated constants.
568 if self.tcx.trait_of_item(def_id).is_some() {
569 self.add_type(constant.literal.ty);
571 let (bits, _) = self.tcx.at(constant.span).mir_const_qualif(def_id);
573 let qualif = Qualif::from_bits(bits).expect("invalid mir_const_qualif");
576 // Just in case the type is more specific than
577 // the definition, e.g. impl associated const
578 // with type parameters, take it into account.
579 self.qualif.restrict(constant.literal.ty, self.tcx, self.param_env);
586 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
587 // Recurse through operands and places.
588 if let Rvalue::Ref(region, kind, ref place) = *rvalue {
589 let mut is_reborrow = false;
590 if let Place::Projection(ref proj) = *place {
591 if let ProjectionElem::Deref = proj.elem {
592 let base_ty = proj.base.ty(self.mir, self.tcx).to_ty(self.tcx);
593 if let ty::TyRef(..) = base_ty.sty {
600 self.super_place(place, PlaceContext::Borrow {
605 self.super_rvalue(rvalue, location);
608 self.super_rvalue(rvalue, location);
614 Rvalue::UnaryOp(UnOp::Neg, _) |
615 Rvalue::UnaryOp(UnOp::Not, _) |
616 Rvalue::NullaryOp(NullOp::SizeOf, _) |
617 Rvalue::CheckedBinaryOp(..) |
618 Rvalue::Cast(CastKind::ReifyFnPointer, ..) |
619 Rvalue::Cast(CastKind::UnsafeFnPointer, ..) |
620 Rvalue::Cast(CastKind::ClosureFnPointer, ..) |
621 Rvalue::Cast(CastKind::Unsize, ..) |
622 Rvalue::Discriminant(..) |
625 Rvalue::Ref(_, kind, ref place) => {
626 let ty = place.ty(self.mir, self.tcx).to_ty(self.tcx);
628 // Default to forbidding the borrow and/or its promotion,
629 // due to the potential for direct or interior mutability,
630 // and only proceed by setting `forbidden_mut` to `false`.
631 let mut forbidden_mut = true;
633 if let BorrowKind::Mut { .. } = kind {
634 // In theory, any zero-sized value could be borrowed
635 // mutably without consequences. However, only &mut []
636 // is allowed right now, and only in functions.
637 if self.mode == Mode::StaticMut {
638 // Inside a `static mut`, &mut [...] is also allowed.
640 ty::TyArray(..) | ty::TySlice(_) => forbidden_mut = false,
643 } else if let ty::TyArray(_, len) = ty.sty {
644 // FIXME(eddyb) the `self.mode == Mode::Fn` condition
645 // seems unnecessary, given that this is merely a ZST.
646 if len.unwrap_usize(self.tcx) == 0 && self.mode == Mode::Fn {
647 forbidden_mut = false;
652 self.add(Qualif::NOT_CONST);
653 if self.mode != Mode::Fn {
654 let mut err = struct_span_err!(self.tcx.sess, self.span, E0017,
655 "references in {}s may only refer \
656 to immutable values", self.mode);
657 err.span_label(self.span, format!("{}s require immutable values",
659 if self.tcx.sess.teach(&err.get_code().unwrap()) {
660 err.note("References in statics and constants may only refer to \
661 immutable values.\n\n\
662 Statics are shared everywhere, and if they refer to \
663 mutable data one might violate memory safety since \
664 holding multiple mutable references to shared data is \
666 If you really want global mutable state, try using \
667 static mut or a global UnsafeCell.");
673 // Constants cannot be borrowed if they contain interior mutability as
674 // it means that our "silent insertion of statics" could change
675 // initializer values (very bad).
676 if self.qualif.contains(Qualif::MUTABLE_INTERIOR) {
677 // A reference of a MUTABLE_INTERIOR place is instead
678 // NOT_CONST (see `if forbidden_mut` below), to avoid
679 // duplicate errors (from reborrowing, for example).
680 self.qualif = self.qualif - Qualif::MUTABLE_INTERIOR;
681 if self.mode != Mode::Fn {
682 span_err!(self.tcx.sess, self.span, E0492,
683 "cannot borrow a constant which may contain \
684 interior mutability, create a static instead");
687 // We allow immutable borrows of frozen data.
688 forbidden_mut = false;
693 self.add(Qualif::NOT_CONST);
695 // We might have a candidate for promotion.
696 let candidate = Candidate::Ref(location);
697 // We can only promote interior borrows of promotable temps.
698 let mut place = place;
699 while let Place::Projection(ref proj) = *place {
700 if proj.elem == ProjectionElem::Deref {
705 if let Place::Local(local) = *place {
706 if self.mir.local_kind(local) == LocalKind::Temp {
707 if let Some(qualif) = self.local_qualif[local] {
708 // `forbidden_mut` is false, so we can safely ignore
709 // `MUTABLE_INTERIOR` from the local's qualifications.
710 // This allows borrowing fields which don't have
711 // `MUTABLE_INTERIOR`, from a type that does, e.g.:
712 // `let _: &'static _ = &(Cell::new(1), 2).1;`
713 if (qualif - Qualif::MUTABLE_INTERIOR).is_empty() {
714 self.promotion_candidates.push(candidate);
722 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
723 let operand_ty = operand.ty(self.mir, self.tcx);
724 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
725 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
726 match (cast_in, cast_out) {
727 (CastTy::Ptr(_), CastTy::Int(_)) |
728 (CastTy::FnPtr, CastTy::Int(_)) => {
729 self.add(Qualif::NOT_CONST);
730 if self.mode != Mode::Fn &&
731 !self.tcx.sess.features_untracked().const_raw_ptr_deref {
733 &self.tcx.sess.parse_sess, "const_raw_ptr_deref",
734 self.span, GateIssue::Language,
736 "casting pointers to integers in {}s is unstable",
746 Rvalue::BinaryOp(op, ref lhs, _) => {
747 if let ty::TyRawPtr(_) = lhs.ty(self.mir, self.tcx).sty {
748 assert!(op == BinOp::Eq || op == BinOp::Ne ||
749 op == BinOp::Le || op == BinOp::Lt ||
750 op == BinOp::Ge || op == BinOp::Gt ||
751 op == BinOp::Offset);
753 self.add(Qualif::NOT_CONST);
754 if self.mode != Mode::Fn {
756 self.tcx.sess, self.span, E0395,
757 "raw pointers cannot be compared in {}s",
761 "comparing raw pointers in static")
767 Rvalue::NullaryOp(NullOp::Box, _) => {
768 self.add(Qualif::NOT_CONST);
769 if self.mode != Mode::Fn {
770 let mut err = struct_span_err!(self.tcx.sess, self.span, E0010,
771 "allocations are not allowed in {}s", self.mode);
772 err.span_label(self.span, format!("allocation not allowed in {}s", self.mode));
773 if self.tcx.sess.teach(&err.get_code().unwrap()) {
775 "The value of statics and constants must be known at compile time, \
776 and they live for the entire lifetime of a program. Creating a boxed \
777 value allocates memory on the heap at runtime, and therefore cannot \
778 be done at compile time."
785 Rvalue::Aggregate(ref kind, _) => {
786 if let AggregateKind::Adt(def, ..) = **kind {
787 if def.has_dtor(self.tcx) {
788 self.add(Qualif::NEEDS_DROP);
791 if Some(def.did) == self.tcx.lang_items().unsafe_cell_type() {
792 let ty = rvalue.ty(self.mir, self.tcx);
794 assert!(self.qualif.contains(Qualif::MUTABLE_INTERIOR));
801 fn visit_terminator_kind(&mut self,
803 kind: &TerminatorKind<'tcx>,
804 location: Location) {
805 if let TerminatorKind::Call { ref func, ref args, ref destination, .. } = *kind {
806 self.visit_operand(func, location);
808 let fn_ty = func.ty(self.mir, self.tcx);
809 let mut callee_def_id = None;
810 let (mut is_shuffle, mut is_const_fn) = (false, None);
811 if let ty::TyFnDef(def_id, _) = fn_ty.sty {
812 callee_def_id = Some(def_id);
813 match self.tcx.fn_sig(def_id).abi() {
815 Abi::PlatformIntrinsic => {
816 assert!(!self.tcx.is_const_fn(def_id));
817 match &self.tcx.item_name(def_id).as_str()[..] {
826 | "ctlz_nonzero" => is_const_fn = Some(def_id),
828 name if name.starts_with("simd_shuffle") => {
836 if self.tcx.is_const_fn(def_id) {
837 is_const_fn = Some(def_id);
843 let constant_arguments = callee_def_id.and_then(|id| {
844 args_required_const(self.tcx, id)
846 for (i, arg) in args.iter().enumerate() {
848 this.visit_operand(arg, location);
849 if this.mode != Mode::Fn {
852 let candidate = Candidate::Argument { bb, index: i };
853 if is_shuffle && i == 2 {
854 if this.qualif.is_empty() {
855 this.promotion_candidates.push(candidate);
857 span_err!(this.tcx.sess, this.span, E0526,
858 "shuffle indices are not constant");
863 let constant_arguments = match constant_arguments.as_ref() {
867 if !constant_arguments.contains(&i) {
870 if this.qualif.is_empty() {
871 this.promotion_candidates.push(candidate);
873 this.tcx.sess.span_err(this.span,
874 &format!("argument {} is required to be a constant",
881 if let Some(def_id) = is_const_fn {
882 // find corresponding rustc_const_unstable feature
883 if let Some(&attr::Stability {
884 rustc_const_unstable: Some(attr::RustcConstUnstable {
885 feature: ref feature_name
887 .. }) = self.tcx.lookup_stability(def_id) {
889 // feature-gate is not enabled,
891 .declared_lib_features
893 .any(|&(ref sym, _)| sym == feature_name) &&
895 // this doesn't come from a crate with the feature-gate enabled,
896 self.def_id.is_local() &&
898 // this doesn't come from a macro that has #[allow_internal_unstable]
899 !self.span.allows_unstable()
901 self.qualif = Qualif::NOT_CONST;
902 if self.mode != Mode::Fn {
903 // inside a constant environment, not having the feature gate is
905 let mut err = self.tcx.sess.struct_span_err(self.span,
906 &format!("`{}` is not yet stable as a const fn",
907 self.tcx.item_path_str(def_id)));
909 "in Nightly builds, add `#![feature({})]` \
910 to the crate attributes to enable",
917 self.qualif = Qualif::NOT_CONST;
918 if self.mode != Mode::Fn {
919 // FIXME(#24111) Remove this check when const fn stabilizes
920 let (msg, note) = if let UnstableFeatures::Disallow =
921 self.tcx.sess.opts.unstable_features {
922 (format!("calls in {}s are limited to \
923 tuple structs and tuple variants",
925 Some("a limited form of compile-time function \
926 evaluation is available on a nightly \
927 compiler via `const fn`"))
929 (format!("calls in {}s are limited \
930 to constant functions, \
931 tuple structs and tuple variants",
935 let mut err = struct_span_err!(self.tcx.sess, self.span, E0015, "{}", msg);
936 if let Some(note) = note {
937 err.span_note(self.span, note);
943 if let Some((ref dest, _)) = *destination {
944 // Avoid propagating irrelevant callee/argument qualifications.
945 if self.qualif.intersects(Qualif::CONST_ERROR) {
946 self.qualif = Qualif::NOT_CONST;
948 // Be conservative about the returned value of a const fn.
950 let ty = dest.ty(self.mir, tcx).to_ty(tcx);
951 self.qualif = Qualif::empty();
954 self.assign(dest, location);
956 } else if let TerminatorKind::Drop { location: ref place, .. } = *kind {
957 self.super_terminator_kind(bb, kind, location);
959 // Deny *any* live drops anywhere other than functions.
960 if self.mode != Mode::Fn {
961 // HACK(eddyb) Emulate a bit of dataflow analysis,
962 // conservatively, that drop elaboration will do.
963 let needs_drop = if let Place::Local(local) = *place {
964 if self.local_qualif[local].map_or(true, |q| q.contains(Qualif::NEEDS_DROP)) {
965 Some(self.mir.local_decls[local].source_info.span)
973 if let Some(span) = needs_drop {
974 // Double-check the type being dropped, to minimize false positives.
975 let ty = place.ty(self.mir, self.tcx).to_ty(self.tcx);
976 if ty.needs_drop(self.tcx, self.param_env) {
977 struct_span_err!(self.tcx.sess, span, E0493,
978 "destructors cannot be evaluated at compile-time")
979 .span_label(span, format!("{}s cannot evaluate destructors",
986 // Qualify any operands inside other terminators.
987 self.super_terminator_kind(bb, kind, location);
991 fn visit_assign(&mut self,
994 rvalue: &Rvalue<'tcx>,
995 location: Location) {
996 self.visit_rvalue(rvalue, location);
998 // Check the allowed const fn argument forms.
999 if let (Mode::ConstFn, &Place::Local(index)) = (self.mode, dest) {
1000 if self.mir.local_kind(index) == LocalKind::Var &&
1001 self.const_fn_arg_vars.insert(index) &&
1002 !self.tcx.sess.features_untracked().const_let {
1004 // Direct use of an argument is permitted.
1006 Rvalue::Use(Operand::Copy(Place::Local(local))) |
1007 Rvalue::Use(Operand::Move(Place::Local(local))) => {
1008 if self.mir.local_kind(local) == LocalKind::Arg {
1015 // Avoid a generic error for other uses of arguments.
1016 if self.qualif.contains(Qualif::FN_ARGUMENT) {
1017 let decl = &self.mir.local_decls[index];
1018 let mut err = feature_err(
1019 &self.tcx.sess.parse_sess,
1021 decl.source_info.span,
1022 GateIssue::Language,
1023 "arguments of constant functions can only be immutable by-value bindings"
1025 if self.tcx.sess.teach(&err.get_code().unwrap()) {
1026 err.note("Constant functions are not allowed to mutate anything. Thus, \
1027 binding to an argument with a mutable pattern is not allowed.");
1028 err.note("Remove any mutable bindings from the argument list to fix this \
1029 error. In case you need to mutate the argument, try lazily \
1030 initializing a global variable instead of using a const fn, or \
1031 refactoring the code to a functional style to avoid mutation if \
1040 self.assign(dest, location);
1043 fn visit_source_info(&mut self, source_info: &SourceInfo) {
1044 self.span = source_info.span;
1047 fn visit_statement(&mut self, bb: BasicBlock, statement: &Statement<'tcx>, location: Location) {
1049 this.visit_source_info(&statement.source_info);
1050 match statement.kind {
1051 StatementKind::Assign(ref place, ref rvalue) => {
1052 this.visit_assign(bb, place, rvalue, location);
1054 StatementKind::ReadForMatch(..) |
1055 StatementKind::SetDiscriminant { .. } |
1056 StatementKind::StorageLive(_) |
1057 StatementKind::StorageDead(_) |
1058 StatementKind::InlineAsm {..} |
1059 StatementKind::EndRegion(_) |
1060 StatementKind::Validate(..) |
1061 StatementKind::UserAssertTy(..) |
1062 StatementKind::Nop => {}
1067 fn visit_terminator(&mut self,
1069 terminator: &Terminator<'tcx>,
1070 location: Location) {
1071 self.nest(|this| this.super_terminator(bb, terminator, location));
1075 pub fn provide(providers: &mut Providers) {
1076 *providers = Providers {
1082 fn mir_const_qualif<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
1084 -> (u8, Lrc<IdxSetBuf<Local>>) {
1085 // NB: This `borrow()` is guaranteed to be valid (i.e., the value
1086 // cannot yet be stolen), because `mir_validated()`, which steals
1087 // from `mir_const(), forces this query to execute before
1088 // performing the steal.
1089 let mir = &tcx.mir_const(def_id).borrow();
1091 if mir.return_ty().references_error() {
1092 tcx.sess.delay_span_bug(mir.span, "mir_const_qualif: Mir had errors");
1093 return (Qualif::NOT_CONST.bits(), Lrc::new(IdxSetBuf::new_empty(0)));
1096 let mut qualifier = Qualifier::new(tcx, def_id, mir, Mode::Const);
1097 let (qualif, promoted_temps) = qualifier.qualify_const();
1098 (qualif.bits(), promoted_temps)
1101 pub struct QualifyAndPromoteConstants;
1103 impl MirPass for QualifyAndPromoteConstants {
1104 fn run_pass<'a, 'tcx>(&self,
1105 tcx: TyCtxt<'a, 'tcx, 'tcx>,
1107 mir: &mut Mir<'tcx>) {
1108 // There's not really any point in promoting errorful MIR.
1109 if mir.return_ty().references_error() {
1110 tcx.sess.delay_span_bug(mir.span, "QualifyAndPromoteConstants: Mir had errors");
1114 if src.promoted.is_some() {
1118 let def_id = src.def_id;
1119 let id = tcx.hir.as_local_node_id(def_id).unwrap();
1120 let mut const_promoted_temps = None;
1121 let mode = match tcx.hir.body_owner_kind(id) {
1122 hir::BodyOwnerKind::Fn => {
1123 if tcx.is_const_fn(def_id) {
1129 hir::BodyOwnerKind::Const => {
1130 const_promoted_temps = Some(tcx.mir_const_qualif(def_id).1);
1133 hir::BodyOwnerKind::Static(hir::MutImmutable) => Mode::Static,
1134 hir::BodyOwnerKind::Static(hir::MutMutable) => Mode::StaticMut,
1137 if mode == Mode::Fn || mode == Mode::ConstFn {
1138 // This is ugly because Qualifier holds onto mir,
1139 // which can't be mutated until its scope ends.
1140 let (temps, candidates) = {
1141 let mut qualifier = Qualifier::new(tcx, def_id, mir, mode);
1142 if mode == Mode::ConstFn {
1143 // Enforce a constant-like CFG for `const fn`.
1144 qualifier.qualify_const();
1146 while let Some((bb, data)) = qualifier.rpo.next() {
1147 qualifier.visit_basic_block_data(bb, data);
1151 (qualifier.temp_promotion_state, qualifier.promotion_candidates)
1154 // Do the actual promotion, now that we know what's viable.
1155 promote_consts::promote_candidates(mir, tcx, temps, candidates);
1157 let promoted_temps = if mode == Mode::Const {
1158 // Already computed by `mir_const_qualif`.
1159 const_promoted_temps.unwrap()
1161 Qualifier::new(tcx, def_id, mir, mode).qualify_const().1
1164 // In `const` and `static` everything without `StorageDead`
1165 // is `'static`, we don't have to create promoted MIR fragments,
1166 // just remove `Drop` and `StorageDead` on "promoted" locals.
1167 for block in mir.basic_blocks_mut() {
1168 block.statements.retain(|statement| {
1169 match statement.kind {
1170 StatementKind::StorageDead(index) => {
1171 !promoted_temps.contains(&index)
1176 let terminator = block.terminator_mut();
1177 match terminator.kind {
1178 TerminatorKind::Drop { location: Place::Local(index), target, .. } => {
1179 if promoted_temps.contains(&index) {
1180 terminator.kind = TerminatorKind::Goto {
1190 // Statics must be Sync.
1191 if mode == Mode::Static {
1192 // `#[thread_local]` statics don't have to be `Sync`.
1193 for attr in &tcx.get_attrs(def_id)[..] {
1194 if attr.check_name("thread_local") {
1198 let ty = mir.return_ty();
1199 tcx.infer_ctxt().enter(|infcx| {
1200 let param_env = ty::ParamEnv::empty();
1201 let cause = traits::ObligationCause::new(mir.span, id, traits::SharedStatic);
1202 let mut fulfillment_cx = traits::FulfillmentContext::new();
1203 fulfillment_cx.register_bound(&infcx,
1206 tcx.require_lang_item(lang_items::SyncTraitLangItem),
1208 if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) {
1209 infcx.report_fulfillment_errors(&err, None, false);
1216 fn args_required_const(tcx: TyCtxt, def_id: DefId) -> Option<FxHashSet<usize>> {
1217 let attrs = tcx.get_attrs(def_id);
1218 let attr = attrs.iter().find(|a| a.check_name("rustc_args_required_const"))?;
1219 let mut ret = FxHashSet();
1220 for meta in attr.meta_item_list()? {
1221 match meta.literal()?.node {
1222 LitKind::Int(a, _) => { ret.insert(a as usize); }