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::BitVector;
18 use rustc_data_structures::indexed_vec::{IndexVec, Idx};
19 use rustc::dep_graph::DepNode;
21 use rustc::hir::map as hir_map;
22 use rustc::hir::def_id::DefId;
23 use rustc::hir::map::blocks::FnLikeNode;
24 use rustc::traits::{self, Reveal};
25 use rustc::ty::{self, TyCtxt, Ty, TypeFoldable};
26 use rustc::ty::cast::CastTy;
27 use rustc::ty::maps::Providers;
29 use rustc::mir::traversal::ReversePostorder;
30 use rustc::mir::transform::{Pass, MirMapPass, MirPassHook, MirSource};
31 use rustc::mir::visit::{LvalueContext, Visitor};
32 use rustc::middle::lang_items;
34 use syntax::feature_gate::UnstableFeatures;
35 use syntax_pos::{Span, DUMMY_SP};
40 use super::promote_consts::{self, Candidate, TempState};
44 // Constant containing interior mutability (UnsafeCell).
45 const MUTABLE_INTERIOR = 1 << 0,
47 // Constant containing an ADT that implements Drop.
48 const NEEDS_DROP = 1 << 1,
51 const FN_ARGUMENT = 1 << 2,
53 // Static lvalue or move from a static.
54 const STATIC = 1 << 3,
56 // Reference to a static.
57 const STATIC_REF = 1 << 4,
59 // Not constant at all - non-`const fn` calls, asm!,
60 // pointer comparisons, ptr-to-int casts, etc.
61 const NOT_CONST = 1 << 5,
63 // Refers to temporaries which cannot be promoted as
64 // promote_consts decided they weren't simple enough.
65 const NOT_PROMOTABLE = 1 << 6,
67 // Borrows of temporaries can be promoted only
68 // if they have none of the above qualifications.
69 const NEVER_PROMOTE = 0b111_1111,
71 // Const items can only have MUTABLE_INTERIOR
72 // and NOT_PROMOTABLE without producing an error.
73 const CONST_ERROR = !Qualif::MUTABLE_INTERIOR.bits &
74 !Qualif::NOT_PROMOTABLE.bits
78 impl<'a, 'tcx> Qualif {
79 /// Remove flags which are impossible for the given type.
80 fn restrict(&mut self, ty: Ty<'tcx>,
81 tcx: TyCtxt<'a, 'tcx, 'tcx>,
82 param_env: &ty::ParameterEnvironment<'tcx>) {
83 if ty.is_freeze(tcx, param_env, DUMMY_SP) {
84 *self = *self - Qualif::MUTABLE_INTERIOR;
86 if !ty.needs_drop(tcx, param_env) {
87 *self = *self - Qualif::NEEDS_DROP;
92 /// What kind of item we are in.
93 #[derive(Copy, Clone, PartialEq, Eq)]
102 impl fmt::Display for Mode {
103 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
105 Mode::Const => write!(f, "constant"),
106 Mode::Static | Mode::StaticMut => write!(f, "static"),
107 Mode::ConstFn => write!(f, "constant function"),
108 Mode::Fn => write!(f, "function")
113 pub fn is_const_fn(tcx: TyCtxt, def_id: DefId) -> bool {
114 if let Some(node_id) = tcx.hir.as_local_node_id(def_id) {
115 if let Some(fn_like) = FnLikeNode::from_node(tcx.hir.get(node_id)) {
116 fn_like.constness() == hir::Constness::Const
121 tcx.sess.cstore.is_const_fn(def_id)
125 struct Qualifier<'a, 'gcx: 'a+'tcx, 'tcx: 'a> {
130 rpo: ReversePostorder<'a, 'tcx>,
131 tcx: TyCtxt<'a, 'gcx, 'tcx>,
132 param_env: ty::ParameterEnvironment<'tcx>,
133 temp_qualif: IndexVec<Local, Option<Qualif>>,
134 return_qualif: Option<Qualif>,
136 const_fn_arg_vars: BitVector,
137 temp_promotion_state: IndexVec<Local, TempState>,
138 promotion_candidates: Vec<Candidate>
141 impl<'a, 'tcx> Qualifier<'a, 'tcx, 'tcx> {
142 fn new(tcx: TyCtxt<'a, 'tcx, 'tcx>,
143 param_env: ty::ParameterEnvironment<'tcx>,
147 -> Qualifier<'a, 'tcx, 'tcx> {
148 let mut rpo = traversal::reverse_postorder(mir);
149 let temps = promote_consts::collect_temps(mir, &mut rpo);
158 param_env: param_env,
159 temp_qualif: IndexVec::from_elem(None, &mir.local_decls),
161 qualif: Qualif::empty(),
162 const_fn_arg_vars: BitVector::new(mir.local_decls.len()),
163 temp_promotion_state: temps,
164 promotion_candidates: vec![]
168 // FIXME(eddyb) we could split the errors into meaningful
169 // categories, but enabling full miri would make that
170 // slightly pointless (even with feature-gating).
171 fn not_const(&mut self) {
172 self.add(Qualif::NOT_CONST);
173 if self.mode != Mode::Fn {
174 span_err!(self.tcx.sess, self.span, E0019,
175 "{} contains unimplemented expression type", self.mode);
179 /// Error about extra statements in a constant.
180 fn statement_like(&mut self) {
181 self.add(Qualif::NOT_CONST);
182 if self.mode != Mode::Fn {
183 span_err!(self.tcx.sess, self.span, E0016,
184 "blocks in {}s are limited to items and tail expressions",
189 /// Add the given qualification to self.qualif.
190 fn add(&mut self, qualif: Qualif) {
191 self.qualif = self.qualif | qualif;
194 /// Add the given type's qualification to self.qualif.
195 fn add_type(&mut self, ty: Ty<'tcx>) {
196 self.add(Qualif::MUTABLE_INTERIOR | Qualif::NEEDS_DROP);
197 self.qualif.restrict(ty, self.tcx, &self.param_env);
200 /// Within the provided closure, self.qualif will start
201 /// out empty, and its value after the closure returns will
202 /// be combined with the value before the call to nest.
203 fn nest<F: FnOnce(&mut Self)>(&mut self, f: F) {
204 let original = self.qualif;
205 self.qualif = Qualif::empty();
210 /// Check for NEEDS_DROP (from an ADT or const fn call) and
211 /// error, unless we're in a function, or the feature-gate
212 /// for globals with destructors is enabled.
213 fn deny_drop(&self) {
214 if self.mode == Mode::Fn || !self.qualif.intersects(Qualif::NEEDS_DROP) {
218 // Static and const fn's allow destructors, but they're feature-gated.
219 let msg = if self.mode != Mode::Const {
220 // Feature-gate for globals with destructors is enabled.
221 if self.tcx.sess.features.borrow().drop_types_in_const {
225 // This comes from a macro that has #[allow_internal_unstable].
226 if self.span.allows_unstable() {
230 format!("destructors in {}s are an unstable feature",
233 format!("{}s are not allowed to have destructors",
238 struct_span_err!(self.tcx.sess, self.span, E0493, "{}", msg);
240 if self.mode != Mode::Const {
242 "in Nightly builds, add `#![feature(drop_types_in_const)]` \
243 to the crate attributes to enable");
245 self.find_drop_implementation_method_span()
246 .map(|span| err.span_label(span, &format!("destructor defined here")));
248 err.span_label(self.span, &format!("constants cannot have destructors"));
254 fn find_drop_implementation_method_span(&self) -> Option<Span> {
257 .and_then(|drop_trait_id| {
261 .lookup_trait_def(drop_trait_id)
262 .for_each_relevant_impl(self.tcx, self.mir.return_ty, |impl_did| {
264 .as_local_node_id(impl_did)
265 .and_then(|impl_node_id| self.tcx.hir.find(impl_node_id))
267 if let hir_map::NodeItem(item) = node {
268 if let hir::ItemImpl(.., ref impl_item_refs) = item.node {
269 span = impl_item_refs.first()
271 self.tcx.hir.impl_item(iiref.id)
283 /// Check if an Lvalue with the current qualifications could
284 /// be consumed, by either an operand or a Deref projection.
285 fn try_consume(&mut self) -> bool {
286 if self.qualif.intersects(Qualif::STATIC) && self.mode != Mode::Fn {
287 let msg = if self.mode == Mode::Static ||
288 self.mode == Mode::StaticMut {
289 "cannot refer to other statics by value, use the \
290 address-of operator or a constant instead"
292 "cannot refer to statics by value, use a constant instead"
294 struct_span_err!(self.tcx.sess, self.span, E0394, "{}", msg)
295 .span_label(self.span, &format!("referring to another static by value"))
296 .note(&format!("use the address-of operator or a constant instead"))
299 // Replace STATIC with NOT_CONST to avoid further errors.
300 self.qualif = self.qualif - Qualif::STATIC;
301 self.add(Qualif::NOT_CONST);
309 /// Assign the current qualification to the given destination.
310 fn assign(&mut self, dest: &Lvalue<'tcx>, location: Location) {
311 let qualif = self.qualif;
312 let span = self.span;
313 let store = |slot: &mut Option<Qualif>| {
315 span_bug!(span, "multiple assignments to {:?}", dest);
317 *slot = Some(qualif);
320 // Only handle promotable temps in non-const functions.
321 if self.mode == Mode::Fn {
322 if let Lvalue::Local(index) = *dest {
323 if self.mir.local_kind(index) == LocalKind::Temp
324 && self.temp_promotion_state[index].is_promotable() {
325 debug!("store to promotable temp {:?}", index);
326 store(&mut self.temp_qualif[index]);
333 Lvalue::Local(index) if self.mir.local_kind(index) == LocalKind::Temp => {
334 debug!("store to temp {:?}", index);
335 store(&mut self.temp_qualif[index])
337 Lvalue::Local(index) if self.mir.local_kind(index) == LocalKind::ReturnPointer => {
338 debug!("store to return pointer {:?}", index);
339 store(&mut self.return_qualif)
342 Lvalue::Projection(box Projection {
343 base: Lvalue::Local(index),
344 elem: ProjectionElem::Deref
345 }) if self.mir.local_kind(index) == LocalKind::Temp
346 && self.mir.local_decls[index].ty.is_box()
347 && self.temp_qualif[index].map_or(false, |qualif| {
348 qualif.intersects(Qualif::NOT_CONST)
350 // Part of `box expr`, we should've errored
351 // already for the Box allocation Rvalue.
354 // This must be an explicit assignment.
356 // Catch more errors in the destination.
357 self.visit_lvalue(dest, LvalueContext::Store, location);
358 self.statement_like();
363 /// Qualify a whole const, static initializer or const fn.
364 fn qualify_const(&mut self) -> Qualif {
365 debug!("qualifying {} {}", self.mode, self.tcx.item_path_str(self.def_id));
369 let mut seen_blocks = BitVector::new(mir.basic_blocks().len());
370 let mut bb = START_BLOCK;
372 seen_blocks.insert(bb.index());
374 self.visit_basic_block_data(bb, &mir[bb]);
376 let target = match mir[bb].terminator().kind {
377 TerminatorKind::Goto { target } |
378 // Drops are considered noops.
379 TerminatorKind::Drop { target, .. } |
380 TerminatorKind::Assert { target, .. } |
381 TerminatorKind::Call { destination: Some((_, target)), .. } => {
385 // Non-terminating calls cannot produce any value.
386 TerminatorKind::Call { destination: None, .. } => {
387 return Qualif::empty();
390 TerminatorKind::SwitchInt {..} |
391 TerminatorKind::DropAndReplace { .. } |
392 TerminatorKind::Resume |
393 TerminatorKind::Unreachable => None,
395 TerminatorKind::Return => {
396 // Check for unused values. This usually means
397 // there are extra statements in the AST.
398 for temp in mir.temps_iter() {
399 if self.temp_qualif[temp].is_none() {
403 let state = self.temp_promotion_state[temp];
404 if let TempState::Defined { location, uses: 0 } = state {
405 let data = &mir[location.block];
406 let stmt_idx = location.statement_index;
408 // Get the span for the initialization.
409 let source_info = if stmt_idx < data.statements.len() {
410 data.statements[stmt_idx].source_info
412 data.terminator().source_info
414 self.span = source_info.span;
416 // Treat this as a statement in the AST.
417 self.statement_like();
421 // Make sure there are no extra unassigned variables.
422 self.qualif = Qualif::NOT_CONST;
423 for index in mir.vars_iter() {
424 if !self.const_fn_arg_vars.contains(index.index()) {
425 debug!("unassigned variable {:?}", index);
426 self.assign(&Lvalue::Local(index), Location {
428 statement_index: usize::MAX,
439 Some(target) if !seen_blocks.contains(target.index()) => {
449 let return_ty = mir.return_ty;
450 self.qualif = self.return_qualif.unwrap_or(Qualif::NOT_CONST);
454 // Check for destructors in static mut.
455 self.add_type(return_ty);
459 // Account for errors in consts by using the
460 // conservative type qualification instead.
461 if self.qualif.intersects(Qualif::CONST_ERROR) {
462 self.qualif = Qualif::empty();
463 self.add_type(return_ty);
471 /// Accumulates an Rvalue or Call's effects in self.qualif.
472 /// For functions (constant or not), it also records
473 /// candidates for promotion in promotion_candidates.
474 impl<'a, 'tcx> Visitor<'tcx> for Qualifier<'a, 'tcx, 'tcx> {
475 fn visit_lvalue(&mut self,
476 lvalue: &Lvalue<'tcx>,
477 context: LvalueContext<'tcx>,
478 location: Location) {
480 Lvalue::Local(local) => match self.mir.local_kind(local) {
481 LocalKind::ReturnPointer => {
485 self.add(Qualif::FN_ARGUMENT);
488 self.add(Qualif::NOT_CONST);
491 if !self.temp_promotion_state[local].is_promotable() {
492 self.add(Qualif::NOT_PROMOTABLE);
495 if let Some(qualif) = self.temp_qualif[local] {
502 Lvalue::Static(_) => {
503 self.add(Qualif::STATIC);
504 if self.mode == Mode::Const || self.mode == Mode::ConstFn {
505 span_err!(self.tcx.sess, self.span, E0013,
506 "{}s cannot refer to statics, use \
507 a constant instead", self.mode);
510 Lvalue::Projection(ref proj) => {
512 this.super_lvalue(lvalue, context, location);
514 ProjectionElem::Deref => {
515 if !this.try_consume() {
519 if this.qualif.intersects(Qualif::STATIC_REF) {
520 this.qualif = this.qualif - Qualif::STATIC_REF;
521 this.add(Qualif::STATIC);
524 let base_ty = proj.base.ty(this.mir, this.tcx).to_ty(this.tcx);
525 if let ty::TyRawPtr(_) = base_ty.sty {
526 this.add(Qualif::NOT_CONST);
527 if this.mode != Mode::Fn {
528 struct_span_err!(this.tcx.sess,
530 "raw pointers cannot be dereferenced in {}s",
532 .span_label(this.span,
533 &format!("dereference of raw pointer in constant"))
539 ProjectionElem::Field(..) |
540 ProjectionElem::Index(_) => {
541 if this.mode != Mode::Fn &&
542 this.qualif.intersects(Qualif::STATIC) {
543 span_err!(this.tcx.sess, this.span, E0494,
544 "cannot refer to the interior of another \
545 static, use a constant instead");
547 let ty = lvalue.ty(this.mir, this.tcx).to_ty(this.tcx);
548 this.qualif.restrict(ty, this.tcx, &this.param_env);
551 ProjectionElem::ConstantIndex {..} |
552 ProjectionElem::Subslice {..} |
553 ProjectionElem::Downcast(..) => {
562 fn visit_operand(&mut self, operand: &Operand<'tcx>, location: Location) {
564 Operand::Consume(_) => {
566 this.super_operand(operand, location);
570 Operand::Constant(ref constant) => {
571 if let Literal::Item { def_id, substs } = constant.literal {
572 // Don't peek inside generic (associated) constants.
573 if substs.types().next().is_some() {
574 self.add_type(constant.ty);
576 let bits = ty::queries::mir_const_qualif::get(self.tcx,
580 let qualif = Qualif::from_bits(bits).expect("invalid mir_const_qualif");
584 // Let `const fn` transitively have destructors,
585 // but they do get stopped in `const` or `static`.
586 if self.mode != Mode::ConstFn {
594 fn visit_rvalue(&mut self, rvalue: &Rvalue<'tcx>, location: Location) {
595 // Recurse through operands and lvalues.
596 self.super_rvalue(rvalue, location);
601 Rvalue::UnaryOp(..) |
602 Rvalue::CheckedBinaryOp(..) |
603 Rvalue::Cast(CastKind::ReifyFnPointer, ..) |
604 Rvalue::Cast(CastKind::UnsafeFnPointer, ..) |
605 Rvalue::Cast(CastKind::ClosureFnPointer, ..) |
606 Rvalue::Cast(CastKind::Unsize, ..) |
607 Rvalue::Discriminant(..) => {}
610 // Static lvalues in consts would have errored already,
611 // don't treat length checks as reads from statics.
612 self.qualif = self.qualif - Qualif::STATIC;
615 Rvalue::Ref(_, kind, ref lvalue) => {
616 // Static lvalues in consts would have errored already,
617 // only keep track of references to them here.
618 if self.qualif.intersects(Qualif::STATIC) {
619 self.qualif = self.qualif - Qualif::STATIC;
620 self.add(Qualif::STATIC_REF);
623 let ty = lvalue.ty(self.mir, self.tcx).to_ty(self.tcx);
624 if kind == BorrowKind::Mut {
625 // In theory, any zero-sized value could be borrowed
626 // mutably without consequences. However, only &mut []
627 // is allowed right now, and only in functions.
628 let allow = if self.mode == Mode::StaticMut {
629 // Inside a `static mut`, &mut [...] is also allowed.
631 ty::TyArray(..) | ty::TySlice(_) => {
632 // Mutating can expose drops, be conservative.
639 } else if let ty::TyArray(_, 0) = ty.sty {
640 self.mode == Mode::Fn
646 self.add(Qualif::NOT_CONST);
647 if self.mode != Mode::Fn {
648 struct_span_err!(self.tcx.sess, self.span, E0017,
649 "references in {}s may only refer \
650 to immutable values", self.mode)
651 .span_label(self.span, &format!("{}s require immutable values",
657 // Constants cannot be borrowed if they contain interior mutability as
658 // it means that our "silent insertion of statics" could change
659 // initializer values (very bad).
660 if self.qualif.intersects(Qualif::MUTABLE_INTERIOR) {
661 // Replace MUTABLE_INTERIOR with NOT_CONST to avoid
662 // duplicate errors (from reborrowing, for example).
663 self.qualif = self.qualif - Qualif::MUTABLE_INTERIOR;
664 self.add(Qualif::NOT_CONST);
665 if self.mode != Mode::Fn {
666 span_err!(self.tcx.sess, self.span, E0492,
667 "cannot borrow a constant which contains \
668 interior mutability, create a static instead");
673 // We might have a candidate for promotion.
674 let candidate = Candidate::Ref(location);
675 if self.mode == Mode::Fn || self.mode == Mode::ConstFn {
676 if !self.qualif.intersects(Qualif::NEVER_PROMOTE) {
677 // We can only promote direct borrows of temps.
678 if let Lvalue::Local(local) = *lvalue {
679 if self.mir.local_kind(local) == LocalKind::Temp {
680 self.promotion_candidates.push(candidate);
687 Rvalue::Cast(CastKind::Misc, ref operand, cast_ty) => {
688 let operand_ty = operand.ty(self.mir, self.tcx);
689 let cast_in = CastTy::from_ty(operand_ty).expect("bad input type for cast");
690 let cast_out = CastTy::from_ty(cast_ty).expect("bad output type for cast");
691 match (cast_in, cast_out) {
692 (CastTy::Ptr(_), CastTy::Int(_)) |
693 (CastTy::FnPtr, CastTy::Int(_)) => {
694 self.add(Qualif::NOT_CONST);
695 if self.mode != Mode::Fn {
696 span_err!(self.tcx.sess, self.span, E0018,
697 "raw pointers cannot be cast to integers in {}s",
705 Rvalue::BinaryOp(op, ref lhs, _) => {
706 if let ty::TyRawPtr(_) = lhs.ty(self.mir, self.tcx).sty {
707 assert!(op == BinOp::Eq || op == BinOp::Ne ||
708 op == BinOp::Le || op == BinOp::Lt ||
709 op == BinOp::Ge || op == BinOp::Gt);
711 self.add(Qualif::NOT_CONST);
712 if self.mode != Mode::Fn {
714 self.tcx.sess, self.span, E0395,
715 "raw pointers cannot be compared in {}s",
719 &format!("comparing raw pointers in static"))
726 self.add(Qualif::NOT_CONST);
727 if self.mode != Mode::Fn {
728 struct_span_err!(self.tcx.sess, self.span, E0010,
729 "allocations are not allowed in {}s", self.mode)
730 .span_label(self.span, &format!("allocation not allowed in {}s", self.mode))
735 Rvalue::Aggregate(ref kind, _) => {
736 if let AggregateKind::Adt(def, ..) = *kind {
737 if def.has_dtor(self.tcx) {
738 self.add(Qualif::NEEDS_DROP);
742 if Some(def.did) == self.tcx.lang_items.unsafe_cell_type() {
743 let ty = rvalue.ty(self.mir, self.tcx);
745 assert!(self.qualif.intersects(Qualif::MUTABLE_INTERIOR));
746 // Even if the value inside may not need dropping,
747 // mutating it would change that.
748 if !self.qualif.intersects(Qualif::NOT_CONST) {
757 fn visit_terminator_kind(&mut self,
759 kind: &TerminatorKind<'tcx>,
760 location: Location) {
761 if let TerminatorKind::Call { ref func, ref args, ref destination, .. } = *kind {
762 self.visit_operand(func, location);
764 let fn_ty = func.ty(self.mir, self.tcx);
765 let (is_shuffle, is_const_fn) = match fn_ty.sty {
766 ty::TyFnDef(def_id, _, f) => {
767 (f.abi() == Abi::PlatformIntrinsic &&
768 self.tcx.item_name(def_id).as_str().starts_with("simd_shuffle"),
769 is_const_fn(self.tcx, def_id))
774 for (i, arg) in args.iter().enumerate() {
776 this.visit_operand(arg, location);
777 if is_shuffle && i == 2 && this.mode == Mode::Fn {
778 let candidate = Candidate::ShuffleIndices(bb);
779 if !this.qualif.intersects(Qualif::NEVER_PROMOTE) {
780 this.promotion_candidates.push(candidate);
782 span_err!(this.tcx.sess, this.span, E0526,
783 "shuffle indices are not constant");
791 // We are in a const or static initializer,
792 if self.mode != Mode::Fn &&
794 // feature-gate is not enabled,
795 !self.tcx.sess.features.borrow().const_fn &&
797 // this doesn't come from a crate with the feature-gate enabled,
798 self.def_id.is_local() &&
800 // this doesn't come from a macro that has #[allow_internal_unstable]
801 !self.span.allows_unstable()
803 let mut err = self.tcx.sess.struct_span_err(self.span,
804 "const fns are an unstable feature");
806 "in Nightly builds, add `#![feature(const_fn)]` \
807 to the crate attributes to enable");
811 self.qualif = Qualif::NOT_CONST;
812 if self.mode != Mode::Fn {
813 // FIXME(#24111) Remove this check when const fn stabilizes
814 let (msg, note) = if let UnstableFeatures::Disallow =
815 self.tcx.sess.opts.unstable_features {
816 (format!("calls in {}s are limited to \
817 struct and enum constructors",
819 Some("a limited form of compile-time function \
820 evaluation is available on a nightly \
821 compiler via `const fn`"))
823 (format!("calls in {}s are limited \
824 to constant functions, \
825 struct and enum constructors",
829 let mut err = struct_span_err!(self.tcx.sess, self.span, E0015, "{}", msg);
830 if let Some(note) = note {
831 err.span_note(self.span, note);
837 if let Some((ref dest, _)) = *destination {
838 // Avoid propagating irrelevant callee/argument qualifications.
839 if self.qualif.intersects(Qualif::CONST_ERROR) {
840 self.qualif = Qualif::NOT_CONST;
842 // Be conservative about the returned value of a const fn.
844 let ty = dest.ty(self.mir, tcx).to_ty(tcx);
845 self.qualif = Qualif::empty();
848 // Let `const fn` transitively have destructors,
849 // but they do get stopped in `const` or `static`.
850 if self.mode != Mode::ConstFn {
854 self.assign(dest, location);
857 // Qualify any operands inside other terminators.
858 self.super_terminator_kind(bb, kind, location);
862 fn visit_assign(&mut self,
865 rvalue: &Rvalue<'tcx>,
866 location: Location) {
867 self.visit_rvalue(rvalue, location);
869 // Check the allowed const fn argument forms.
870 if let (Mode::ConstFn, &Lvalue::Local(index)) = (self.mode, dest) {
871 if self.mir.local_kind(index) == LocalKind::Var &&
872 self.const_fn_arg_vars.insert(index.index()) {
874 // Direct use of an argument is permitted.
875 if let Rvalue::Use(Operand::Consume(Lvalue::Local(local))) = *rvalue {
876 if self.mir.local_kind(local) == LocalKind::Arg {
881 // Avoid a generic error for other uses of arguments.
882 if self.qualif.intersects(Qualif::FN_ARGUMENT) {
883 let decl = &self.mir.local_decls[index];
884 span_err!(self.tcx.sess, decl.source_info.span, E0022,
885 "arguments of constant functions can only \
886 be immutable by-value bindings");
892 self.assign(dest, location);
895 fn visit_source_info(&mut self, source_info: &SourceInfo) {
896 self.span = source_info.span;
899 fn visit_statement(&mut self, bb: BasicBlock, statement: &Statement<'tcx>, location: Location) {
901 this.visit_source_info(&statement.source_info);
902 match statement.kind {
903 StatementKind::Assign(ref lvalue, ref rvalue) => {
904 this.visit_assign(bb, lvalue, rvalue, location);
906 StatementKind::SetDiscriminant { .. } |
907 StatementKind::StorageLive(_) |
908 StatementKind::StorageDead(_) |
909 StatementKind::InlineAsm {..} |
910 StatementKind::Nop => {}
915 fn visit_terminator(&mut self,
917 terminator: &Terminator<'tcx>,
918 location: Location) {
919 self.nest(|this| this.super_terminator(bb, terminator, location));
923 pub fn provide(providers: &mut Providers) {
924 providers.mir_const_qualif = qualify_const_item;
927 fn qualify_const_item<'a, 'tcx>(tcx: TyCtxt<'a, 'tcx, 'tcx>,
930 let mir = &tcx.item_mir(def_id);
931 if mir.return_ty.references_error() {
932 return Qualif::NOT_CONST.bits();
935 let node_id = tcx.hir.as_local_node_id(def_id).unwrap();
936 let param_env = ty::ParameterEnvironment::for_item(tcx, node_id);
938 let mut qualifier = Qualifier::new(tcx, param_env, def_id, mir, Mode::Const);
939 qualifier.qualify_const().bits()
942 pub struct QualifyAndPromoteConstants;
944 impl Pass for QualifyAndPromoteConstants {}
946 impl<'tcx> MirMapPass<'tcx> for QualifyAndPromoteConstants {
947 fn run_pass<'a>(&mut self,
948 tcx: TyCtxt<'a, 'tcx, 'tcx>,
949 hooks: &mut [Box<for<'s> MirPassHook<'s>>])
951 let def_ids = tcx.maps.mir.borrow().keys();
952 for def_id in def_ids {
953 if !def_id.is_local() {
957 let _task = tcx.dep_graph.in_task(DepNode::Mir(def_id));
958 let id = tcx.hir.as_local_node_id(def_id).unwrap();
959 let src = MirSource::from_node(tcx, id);
961 if let MirSource::Const(_) = src {
962 ty::queries::mir_const_qualif::get(tcx, DUMMY_SP, def_id);
966 let mir = &mut tcx.maps.mir.borrow()[&def_id].borrow_mut();
967 tcx.dep_graph.write(DepNode::Mir(def_id));
969 for hook in &mut *hooks {
970 hook.on_mir_pass(tcx, src, mir, self, false);
972 self.run_pass(tcx, src, mir);
973 for hook in &mut *hooks {
974 hook.on_mir_pass(tcx, src, mir, self, true);
980 impl<'tcx> QualifyAndPromoteConstants {
981 fn run_pass<'a>(&mut self, tcx: TyCtxt<'a, 'tcx, 'tcx>,
982 src: MirSource, mir: &mut Mir<'tcx>) {
983 let id = src.item_id();
984 let def_id = tcx.hir.local_def_id(id);
985 let mode = match src {
986 MirSource::Fn(_) => {
987 if is_const_fn(tcx, def_id) {
993 MirSource::Static(_, hir::MutImmutable) => Mode::Static,
994 MirSource::Static(_, hir::MutMutable) => Mode::StaticMut,
995 MirSource::Const(_) |
996 MirSource::Promoted(..) => return
998 let param_env = ty::ParameterEnvironment::for_item(tcx, id);
1000 if mode == Mode::Fn || mode == Mode::ConstFn {
1001 // This is ugly because Qualifier holds onto mir,
1002 // which can't be mutated until its scope ends.
1003 let (temps, candidates) = {
1004 let mut qualifier = Qualifier::new(tcx, param_env,
1006 if mode == Mode::ConstFn {
1007 // Enforce a constant-like CFG for `const fn`.
1008 qualifier.qualify_const();
1010 while let Some((bb, data)) = qualifier.rpo.next() {
1011 qualifier.visit_basic_block_data(bb, data);
1015 (qualifier.temp_promotion_state, qualifier.promotion_candidates)
1018 // Do the actual promotion, now that we know what's viable.
1019 promote_consts::promote_candidates(mir, tcx, temps, candidates);
1021 let mut qualifier = Qualifier::new(tcx, param_env, def_id, mir, mode);
1022 qualifier.qualify_const();
1025 // Statics must be Sync.
1026 if mode == Mode::Static {
1027 let ty = mir.return_ty;
1028 tcx.infer_ctxt((), Reveal::UserFacing).enter(|infcx| {
1029 let cause = traits::ObligationCause::new(mir.span, id, traits::SharedStatic);
1030 let mut fulfillment_cx = traits::FulfillmentContext::new();
1031 fulfillment_cx.register_bound(&infcx, ty,
1032 tcx.require_lang_item(lang_items::SyncTraitLangItem),
1034 if let Err(err) = fulfillment_cx.select_all_or_error(&infcx) {
1035 infcx.report_fulfillment_errors(&err);