From 44e8a9a84bbd89fec2109dfd3d1c77e1a53e2da9 Mon Sep 17 00:00:00 2001
From: Oliver Scherer <github35764891676564198441@oli-obk.de>
Date: Mon, 16 Mar 2020 14:53:22 +0100
Subject: [PATCH 01/12] Fix ui test blessing when a test has an empty stderr
 file after having had content there before the current changes

---
 src/tools/compiletest/src/runtest.rs | 6 +++++-
 1 file changed, 5 insertions(+), 1 deletion(-)

diff --git a/src/tools/compiletest/src/runtest.rs b/src/tools/compiletest/src/runtest.rs
index 8a291a3611efd..39aacd2a2faef 100644
--- a/src/tools/compiletest/src/runtest.rs
+++ b/src/tools/compiletest/src/runtest.rs
@@ -3445,6 +3445,10 @@ impl<'test> TestCx<'test> {
     }
 
     fn delete_file(&self, file: &PathBuf) {
+        if !file.exists() {
+            // Deleting a nonexistant file would error.
+            return;
+        }
         if let Err(e) = fs::remove_file(file) {
             self.fatal(&format!("failed to delete `{}`: {}", file.display(), e,));
         }
@@ -3507,7 +3511,7 @@ impl<'test> TestCx<'test> {
         let examined_content =
             self.load_expected_output_from_path(&examined_path).unwrap_or_else(|_| String::new());
 
-        if examined_path.exists() && canon_content == &examined_content {
+        if canon_content == &examined_content {
             self.delete_file(&examined_path);
         }
     }

From 85e2c324c8c4e4a711fac2d5919d6e5e9bdaabe1 Mon Sep 17 00:00:00 2001
From: Oliver Scherer <github35764891676564198441@oli-obk.de>
Date: Mon, 23 Mar 2020 14:02:58 +0100
Subject: [PATCH 02/12] Rename `Item` to `ConstCx`.

This renaming was already done in some modules via import renaming. It's strictly used as a context, and it contains a `TyCtxt`.
---
 .../transform/check_consts/mod.rs             |   6 +-
 .../transform/check_consts/ops.rs             | 124 +++++++++---------
 .../transform/check_consts/qualifs.rs         |   2 +-
 .../transform/check_consts/resolver.rs        |  30 ++---
 .../transform/check_consts/validation.rs      |  56 ++++----
 src/librustc_mir/transform/mod.rs             |   4 +-
 src/librustc_mir/transform/promote_consts.rs  |  16 +--
 7 files changed, 119 insertions(+), 119 deletions(-)

diff --git a/src/librustc_mir/transform/check_consts/mod.rs b/src/librustc_mir/transform/check_consts/mod.rs
index bce3a506b1dd9..cd4d492c5798e 100644
--- a/src/librustc_mir/transform/check_consts/mod.rs
+++ b/src/librustc_mir/transform/check_consts/mod.rs
@@ -20,7 +20,7 @@ pub mod validation;
 
 /// Information about the item currently being const-checked, as well as a reference to the global
 /// context.
-pub struct Item<'mir, 'tcx> {
+pub struct ConstCx<'mir, 'tcx> {
     pub body: mir::ReadOnlyBodyAndCache<'mir, 'tcx>,
     pub tcx: TyCtxt<'tcx>,
     pub def_id: DefId,
@@ -28,7 +28,7 @@ pub struct Item<'mir, 'tcx> {
     pub const_kind: Option<ConstKind>,
 }
 
-impl Item<'mir, 'tcx> {
+impl ConstCx<'mir, 'tcx> {
     pub fn new(
         tcx: TyCtxt<'tcx>,
         def_id: DefId,
@@ -37,7 +37,7 @@ impl Item<'mir, 'tcx> {
         let param_env = tcx.param_env(def_id);
         let const_kind = ConstKind::for_item(tcx, def_id);
 
-        Item { body, tcx, def_id, param_env, const_kind }
+        ConstCx { body, tcx, def_id, param_env, const_kind }
     }
 
     /// Returns the kind of const context this `Item` represents (`const`, `static`, etc.).
diff --git a/src/librustc_mir/transform/check_consts/ops.rs b/src/librustc_mir/transform/check_consts/ops.rs
index af7af7388bd28..915fe25a44a0e 100644
--- a/src/librustc_mir/transform/check_consts/ops.rs
+++ b/src/librustc_mir/transform/check_consts/ops.rs
@@ -7,7 +7,7 @@ use rustc_session::parse::feature_err;
 use rustc_span::symbol::sym;
 use rustc_span::{Span, Symbol};
 
-use super::{ConstKind, Item};
+use super::{ConstCx, ConstKind};
 
 /// An operation that is not *always* allowed in a const context.
 pub trait NonConstOp: std::fmt::Debug {
@@ -27,19 +27,19 @@ pub trait NonConstOp: std::fmt::Debug {
     ///
     /// By default, it returns `true` if and only if this operation has a corresponding feature
     /// gate and that gate is enabled.
-    fn is_allowed_in_item(&self, item: &Item<'_, '_>) -> bool {
-        Self::feature_gate().map_or(false, |gate| item.tcx.features().enabled(gate))
+    fn is_allowed_in_item(&self, ccx: &ConstCx<'_, '_>) -> bool {
+        Self::feature_gate().map_or(false, |gate| ccx.tcx.features().enabled(gate))
     }
 
-    fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
+    fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
         let mut err = struct_span_err!(
-            item.tcx.sess,
+            ccx.tcx.sess,
             span,
             E0019,
             "{} contains unimplemented expression type",
-            item.const_kind()
+            ccx.const_kind()
         );
-        if item.tcx.sess.teach(&err.get_code().unwrap()) {
+        if ccx.tcx.sess.teach(&err.get_code().unwrap()) {
             err.note(
                 "A function call isn't allowed in the const's initialization expression \
                       because the expression's value must be known at compile-time.",
@@ -66,9 +66,9 @@ impl NonConstOp for Downcast {
 #[derive(Debug)]
 pub struct FnCallIndirect;
 impl NonConstOp for FnCallIndirect {
-    fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
+    fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
         let mut err =
-            item.tcx.sess.struct_span_err(span, "function pointers are not allowed in const fn");
+            ccx.tcx.sess.struct_span_err(span, "function pointers are not allowed in const fn");
         err.emit();
     }
 }
@@ -77,14 +77,14 @@ impl NonConstOp for FnCallIndirect {
 #[derive(Debug)]
 pub struct FnCallNonConst(pub DefId);
 impl NonConstOp for FnCallNonConst {
-    fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
+    fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
         let mut err = struct_span_err!(
-            item.tcx.sess,
+            ccx.tcx.sess,
             span,
             E0015,
             "calls in {}s are limited to constant functions, \
              tuple structs and tuple variants",
-            item.const_kind(),
+            ccx.const_kind(),
         );
         err.emit();
     }
@@ -106,12 +106,12 @@ impl NonConstOp for FnCallOther {
 #[derive(Debug)]
 pub struct FnCallUnstable(pub DefId, pub Symbol);
 impl NonConstOp for FnCallUnstable {
-    fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
+    fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
         let FnCallUnstable(def_id, feature) = *self;
 
-        let mut err = item.tcx.sess.struct_span_err(
+        let mut err = ccx.tcx.sess.struct_span_err(
             span,
-            &format!("`{}` is not yet stable as a const fn", item.tcx.def_path_str(def_id)),
+            &format!("`{}` is not yet stable as a const fn", ccx.tcx.def_path_str(def_id)),
         );
         if nightly_options::is_nightly_build() {
             err.help(&format!("add `#![feature({})]` to the crate attributes to enable", feature));
@@ -125,16 +125,16 @@ pub struct HeapAllocation;
 impl NonConstOp for HeapAllocation {
     const IS_SUPPORTED_IN_MIRI: bool = false;
 
-    fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
+    fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
         let mut err = struct_span_err!(
-            item.tcx.sess,
+            ccx.tcx.sess,
             span,
             E0010,
             "allocations are not allowed in {}s",
-            item.const_kind()
+            ccx.const_kind()
         );
-        err.span_label(span, format!("allocation not allowed in {}s", item.const_kind()));
-        if item.tcx.sess.teach(&err.get_code().unwrap()) {
+        err.span_label(span, format!("allocation not allowed in {}s", ccx.const_kind()));
+        if ccx.tcx.sess.teach(&err.get_code().unwrap()) {
             err.note(
                 "The value of statics and constants must be known at compile time, \
                  and they live for the entire lifetime of a program. Creating a boxed \
@@ -153,23 +153,23 @@ impl NonConstOp for IfOrMatch {
         Some(sym::const_if_match)
     }
 
-    fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
+    fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
         // This should be caught by the HIR const-checker.
-        item.tcx.sess.delay_span_bug(span, "complex control flow is forbidden in a const context");
+        ccx.tcx.sess.delay_span_bug(span, "complex control flow is forbidden in a const context");
     }
 }
 
 #[derive(Debug)]
 pub struct LiveDrop;
 impl NonConstOp for LiveDrop {
-    fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
+    fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
         struct_span_err!(
-            item.tcx.sess,
+            ccx.tcx.sess,
             span,
             E0493,
             "destructors cannot be evaluated at compile-time"
         )
-        .span_label(span, format!("{}s cannot evaluate destructors", item.const_kind()))
+        .span_label(span, format!("{}s cannot evaluate destructors", ccx.const_kind()))
         .emit();
     }
 }
@@ -181,18 +181,18 @@ impl NonConstOp for Loop {
         Some(sym::const_loop)
     }
 
-    fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
+    fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
         // This should be caught by the HIR const-checker.
-        item.tcx.sess.delay_span_bug(span, "complex control flow is forbidden in a const context");
+        ccx.tcx.sess.delay_span_bug(span, "complex control flow is forbidden in a const context");
     }
 }
 
 #[derive(Debug)]
 pub struct CellBorrow;
 impl NonConstOp for CellBorrow {
-    fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
+    fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
         struct_span_err!(
-            item.tcx.sess,
+            ccx.tcx.sess,
             span,
             E0492,
             "cannot borrow a constant which may contain \
@@ -209,19 +209,19 @@ impl NonConstOp for MutBorrow {
         Some(sym::const_mut_refs)
     }
 
-    fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
+    fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
         let mut err = feature_err(
-            &item.tcx.sess.parse_sess,
+            &ccx.tcx.sess.parse_sess,
             sym::const_mut_refs,
             span,
             &format!(
                 "references in {}s may only refer \
                       to immutable values",
-                item.const_kind()
+                ccx.const_kind()
             ),
         );
-        err.span_label(span, format!("{}s require immutable values", item.const_kind()));
-        if item.tcx.sess.teach(&err.get_code().unwrap()) {
+        err.span_label(span, format!("{}s require immutable values", ccx.const_kind()));
+        if ccx.tcx.sess.teach(&err.get_code().unwrap()) {
             err.note(
                 "References in statics and constants may only refer \
                       to immutable values.\n\n\
@@ -244,12 +244,12 @@ impl NonConstOp for MutAddressOf {
         Some(sym::const_mut_refs)
     }
 
-    fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
+    fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
         feature_err(
-            &item.tcx.sess.parse_sess,
+            &ccx.tcx.sess.parse_sess,
             sym::const_mut_refs,
             span,
-            &format!("`&raw mut` is not allowed in {}s", item.const_kind()),
+            &format!("`&raw mut` is not allowed in {}s", ccx.const_kind()),
         )
         .emit();
     }
@@ -270,12 +270,12 @@ impl NonConstOp for Panic {
         Some(sym::const_panic)
     }
 
-    fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
+    fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
         feature_err(
-            &item.tcx.sess.parse_sess,
+            &ccx.tcx.sess.parse_sess,
             sym::const_panic,
             span,
-            &format!("panicking in {}s is unstable", item.const_kind()),
+            &format!("panicking in {}s is unstable", ccx.const_kind()),
         )
         .emit();
     }
@@ -288,12 +288,12 @@ impl NonConstOp for RawPtrComparison {
         Some(sym::const_compare_raw_pointers)
     }
 
-    fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
+    fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
         feature_err(
-            &item.tcx.sess.parse_sess,
+            &ccx.tcx.sess.parse_sess,
             sym::const_compare_raw_pointers,
             span,
-            &format!("comparing raw pointers inside {}", item.const_kind()),
+            &format!("comparing raw pointers inside {}", ccx.const_kind()),
         )
         .emit();
     }
@@ -306,12 +306,12 @@ impl NonConstOp for RawPtrDeref {
         Some(sym::const_raw_ptr_deref)
     }
 
-    fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
+    fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
         feature_err(
-            &item.tcx.sess.parse_sess,
+            &ccx.tcx.sess.parse_sess,
             sym::const_raw_ptr_deref,
             span,
-            &format!("dereferencing raw pointers in {}s is unstable", item.const_kind(),),
+            &format!("dereferencing raw pointers in {}s is unstable", ccx.const_kind(),),
         )
         .emit();
     }
@@ -324,12 +324,12 @@ impl NonConstOp for RawPtrToIntCast {
         Some(sym::const_raw_ptr_to_usize_cast)
     }
 
-    fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
+    fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
         feature_err(
-            &item.tcx.sess.parse_sess,
+            &ccx.tcx.sess.parse_sess,
             sym::const_raw_ptr_to_usize_cast,
             span,
-            &format!("casting pointers to integers in {}s is unstable", item.const_kind(),),
+            &format!("casting pointers to integers in {}s is unstable", ccx.const_kind(),),
         )
         .emit();
     }
@@ -339,22 +339,22 @@ impl NonConstOp for RawPtrToIntCast {
 #[derive(Debug)]
 pub struct StaticAccess;
 impl NonConstOp for StaticAccess {
-    fn is_allowed_in_item(&self, item: &Item<'_, '_>) -> bool {
-        item.const_kind().is_static()
+    fn is_allowed_in_item(&self, ccx: &ConstCx<'_, '_>) -> bool {
+        ccx.const_kind().is_static()
     }
 
-    fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
+    fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
         let mut err = struct_span_err!(
-            item.tcx.sess,
+            ccx.tcx.sess,
             span,
             E0013,
             "{}s cannot refer to statics",
-            item.const_kind()
+            ccx.const_kind()
         );
         err.help(
             "consider extracting the value of the `static` to a `const`, and referring to that",
         );
-        if item.tcx.sess.teach(&err.get_code().unwrap()) {
+        if ccx.tcx.sess.teach(&err.get_code().unwrap()) {
             err.note(
                 "`static` and `const` variables can refer to other `const` variables. \
                     A `const` variable, however, cannot refer to a `static` variable.",
@@ -371,9 +371,9 @@ pub struct ThreadLocalAccess;
 impl NonConstOp for ThreadLocalAccess {
     const IS_SUPPORTED_IN_MIRI: bool = false;
 
-    fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
+    fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
         struct_span_err!(
-            item.tcx.sess,
+            ccx.tcx.sess,
             span,
             E0625,
             "thread-local statics cannot be \
@@ -386,19 +386,19 @@ impl NonConstOp for ThreadLocalAccess {
 #[derive(Debug)]
 pub struct UnionAccess;
 impl NonConstOp for UnionAccess {
-    fn is_allowed_in_item(&self, item: &Item<'_, '_>) -> bool {
+    fn is_allowed_in_item(&self, ccx: &ConstCx<'_, '_>) -> bool {
         // Union accesses are stable in all contexts except `const fn`.
-        item.const_kind() != ConstKind::ConstFn
-            || item.tcx.features().enabled(Self::feature_gate().unwrap())
+        ccx.const_kind() != ConstKind::ConstFn
+            || ccx.tcx.features().enabled(Self::feature_gate().unwrap())
     }
 
     fn feature_gate() -> Option<Symbol> {
         Some(sym::const_fn_union)
     }
 
-    fn emit_error(&self, item: &Item<'_, '_>, span: Span) {
+    fn emit_error(&self, ccx: &ConstCx<'_, '_>, span: Span) {
         feature_err(
-            &item.tcx.sess.parse_sess,
+            &ccx.tcx.sess.parse_sess,
             sym::const_fn_union,
             span,
             "unions in const fn are unstable",
diff --git a/src/librustc_mir/transform/check_consts/qualifs.rs b/src/librustc_mir/transform/check_consts/qualifs.rs
index f38b9d8ef8586..d960c402aeaea 100644
--- a/src/librustc_mir/transform/check_consts/qualifs.rs
+++ b/src/librustc_mir/transform/check_consts/qualifs.rs
@@ -6,7 +6,7 @@ use rustc_middle::mir::*;
 use rustc_middle::ty::{self, AdtDef, Ty};
 use rustc_span::DUMMY_SP;
 
-use super::Item as ConstCx;
+use super::ConstCx;
 
 pub fn in_any_value_of_ty(cx: &ConstCx<'_, 'tcx>, ty: Ty<'tcx>) -> ConstQualifs {
     ConstQualifs {
diff --git a/src/librustc_mir/transform/check_consts/resolver.rs b/src/librustc_mir/transform/check_consts/resolver.rs
index b95a3939389ba..40abd84793645 100644
--- a/src/librustc_mir/transform/check_consts/resolver.rs
+++ b/src/librustc_mir/transform/check_consts/resolver.rs
@@ -8,7 +8,7 @@ use rustc_middle::mir::{self, BasicBlock, Local, Location};
 
 use std::marker::PhantomData;
 
-use super::{qualifs, Item, Qualif};
+use super::{qualifs, ConstCx, Qualif};
 use crate::dataflow;
 
 /// A `Visitor` that propagates qualifs between locals. This defines the transfer function of
@@ -18,7 +18,7 @@ use crate::dataflow;
 /// the `MaybeMutBorrowedLocals` dataflow pass to see if a `Local` may have become qualified via
 /// an indirect assignment or function call.
 struct TransferFunction<'a, 'mir, 'tcx, Q> {
-    item: &'a Item<'mir, 'tcx>,
+    ccx: &'a ConstCx<'mir, 'tcx>,
     qualifs_per_local: &'a mut BitSet<Local>,
 
     _qualif: PhantomData<Q>,
@@ -28,16 +28,16 @@ impl<Q> TransferFunction<'a, 'mir, 'tcx, Q>
 where
     Q: Qualif,
 {
-    fn new(item: &'a Item<'mir, 'tcx>, qualifs_per_local: &'a mut BitSet<Local>) -> Self {
-        TransferFunction { item, qualifs_per_local, _qualif: PhantomData }
+    fn new(ccx: &'a ConstCx<'mir, 'tcx>, qualifs_per_local: &'a mut BitSet<Local>) -> Self {
+        TransferFunction { ccx, qualifs_per_local, _qualif: PhantomData }
     }
 
     fn initialize_state(&mut self) {
         self.qualifs_per_local.clear();
 
-        for arg in self.item.body.args_iter() {
-            let arg_ty = self.item.body.local_decls[arg].ty;
-            if Q::in_any_value_of_ty(self.item, arg_ty) {
+        for arg in self.ccx.body.args_iter() {
+            let arg_ty = self.ccx.body.local_decls[arg].ty;
+            if Q::in_any_value_of_ty(self.ccx, arg_ty) {
                 self.qualifs_per_local.insert(arg);
             }
         }
@@ -72,8 +72,8 @@ where
     ) {
         // We cannot reason about another function's internals, so use conservative type-based
         // qualification for the result of a function call.
-        let return_ty = return_place.ty(*self.item.body, self.item.tcx).ty;
-        let qualif = Q::in_any_value_of_ty(self.item, return_ty);
+        let return_ty = return_place.ty(*self.ccx.body, self.ccx.tcx).ty;
+        let qualif = Q::in_any_value_of_ty(self.ccx, return_ty);
 
         if !return_place.is_indirect() {
             self.assign_qualif_direct(&return_place, qualif);
@@ -108,7 +108,7 @@ where
         location: Location,
     ) {
         let qualif = qualifs::in_rvalue::<Q, _>(
-            self.item,
+            self.ccx,
             &mut |l| self.qualifs_per_local.contains(l),
             rvalue,
         );
@@ -127,7 +127,7 @@ where
 
         if let mir::TerminatorKind::DropAndReplace { value, location: dest, .. } = kind {
             let qualif = qualifs::in_operand::<Q, _>(
-                self.item,
+                self.ccx,
                 &mut |l| self.qualifs_per_local.contains(l),
                 value,
             );
@@ -145,7 +145,7 @@ where
 
 /// The dataflow analysis used to propagate qualifs on arbitrary CFGs.
 pub(super) struct FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q> {
-    item: &'a Item<'mir, 'tcx>,
+    ccx: &'a ConstCx<'mir, 'tcx>,
     _qualif: PhantomData<Q>,
 }
 
@@ -153,15 +153,15 @@ impl<'a, 'mir, 'tcx, Q> FlowSensitiveAnalysis<'a, 'mir, 'tcx, Q>
 where
     Q: Qualif,
 {
-    pub(super) fn new(_: Q, item: &'a Item<'mir, 'tcx>) -> Self {
-        FlowSensitiveAnalysis { item, _qualif: PhantomData }
+    pub(super) fn new(_: Q, ccx: &'a ConstCx<'mir, 'tcx>) -> Self {
+        FlowSensitiveAnalysis { ccx, _qualif: PhantomData }
     }
 
     fn transfer_function(
         &self,
         state: &'a mut BitSet<Local>,
     ) -> TransferFunction<'a, 'mir, 'tcx, Q> {
-        TransferFunction::<Q>::new(self.item, state)
+        TransferFunction::<Q>::new(self.ccx, state)
     }
 }
 
diff --git a/src/librustc_mir/transform/check_consts/validation.rs b/src/librustc_mir/transform/check_consts/validation.rs
index 649cc0a79d636..497b1220eb663 100644
--- a/src/librustc_mir/transform/check_consts/validation.rs
+++ b/src/librustc_mir/transform/check_consts/validation.rs
@@ -20,7 +20,7 @@ use std::ops::Deref;
 use super::ops::{self, NonConstOp};
 use super::qualifs::{self, HasMutInterior, NeedsDrop};
 use super::resolver::FlowSensitiveAnalysis;
-use super::{is_lang_panic_fn, ConstKind, Item, Qualif};
+use super::{is_lang_panic_fn, ConstCx, ConstKind, Qualif};
 use crate::const_eval::{is_const_fn, is_unstable_const_fn};
 use crate::dataflow::MaybeMutBorrowedLocals;
 use crate::dataflow::{self, Analysis};
@@ -37,15 +37,15 @@ struct QualifCursor<'a, 'mir, 'tcx, Q: Qualif> {
 }
 
 impl<Q: Qualif> QualifCursor<'a, 'mir, 'tcx, Q> {
-    pub fn new(q: Q, item: &'a Item<'mir, 'tcx>) -> Self {
-        let cursor = FlowSensitiveAnalysis::new(q, item)
-            .into_engine(item.tcx, &item.body, item.def_id)
+    pub fn new(q: Q, ccx: &'a ConstCx<'mir, 'tcx>) -> Self {
+        let cursor = FlowSensitiveAnalysis::new(q, ccx)
+            .into_engine(ccx.tcx, &ccx.body, ccx.def_id)
             .iterate_to_fixpoint()
-            .into_results_cursor(*item.body);
+            .into_results_cursor(*ccx.body);
 
-        let mut in_any_value_of_ty = BitSet::new_empty(item.body.local_decls.len());
-        for (local, decl) in item.body.local_decls.iter_enumerated() {
-            if Q::in_any_value_of_ty(item, decl.ty) {
+        let mut in_any_value_of_ty = BitSet::new_empty(ccx.body.local_decls.len());
+        for (local, decl) in ccx.body.local_decls.iter_enumerated() {
+            if Q::in_any_value_of_ty(ccx, decl.ty) {
                 in_any_value_of_ty.insert(local);
             }
         }
@@ -91,12 +91,12 @@ impl Qualifs<'a, 'mir, 'tcx> {
             || self.indirectly_mutable(local, location)
     }
 
-    fn in_return_place(&mut self, item: &Item<'_, 'tcx>) -> ConstQualifs {
+    fn in_return_place(&mut self, ccx: &ConstCx<'_, 'tcx>) -> ConstQualifs {
         // Find the `Return` terminator if one exists.
         //
         // If no `Return` terminator exists, this MIR is divergent. Just return the conservative
         // qualifs for the return type.
-        let return_block = item
+        let return_block = ccx
             .body
             .basic_blocks()
             .iter_enumerated()
@@ -107,11 +107,11 @@ impl Qualifs<'a, 'mir, 'tcx> {
             .map(|(bb, _)| bb);
 
         let return_block = match return_block {
-            None => return qualifs::in_any_value_of_ty(item, item.body.return_ty()),
+            None => return qualifs::in_any_value_of_ty(ccx, ccx.body.return_ty()),
             Some(bb) => bb,
         };
 
-        let return_loc = item.body.terminator_loc(return_block);
+        let return_loc = ccx.body.terminator_loc(return_block);
 
         ConstQualifs {
             needs_drop: self.needs_drop(RETURN_PLACE, return_loc),
@@ -121,7 +121,7 @@ impl Qualifs<'a, 'mir, 'tcx> {
 }
 
 pub struct Validator<'a, 'mir, 'tcx> {
-    item: &'a Item<'mir, 'tcx>,
+    ccx: &'a ConstCx<'mir, 'tcx>,
     qualifs: Qualifs<'a, 'mir, 'tcx>,
 
     /// The span of the current statement.
@@ -129,19 +129,19 @@ pub struct Validator<'a, 'mir, 'tcx> {
 }
 
 impl Deref for Validator<'_, 'mir, 'tcx> {
-    type Target = Item<'mir, 'tcx>;
+    type Target = ConstCx<'mir, 'tcx>;
 
     fn deref(&self) -> &Self::Target {
-        &self.item
+        &self.ccx
     }
 }
 
 impl Validator<'a, 'mir, 'tcx> {
-    pub fn new(item: &'a Item<'mir, 'tcx>) -> Self {
-        let Item { tcx, body, def_id, param_env, .. } = *item;
+    pub fn new(ccx: &'a ConstCx<'mir, 'tcx>) -> Self {
+        let ConstCx { tcx, body, def_id, param_env, .. } = *ccx;
 
-        let needs_drop = QualifCursor::new(NeedsDrop, item);
-        let has_mut_interior = QualifCursor::new(HasMutInterior, item);
+        let needs_drop = QualifCursor::new(NeedsDrop, ccx);
+        let has_mut_interior = QualifCursor::new(HasMutInterior, ccx);
 
         // We can use `unsound_ignore_borrow_on_drop` here because custom drop impls are not
         // allowed in a const.
@@ -156,11 +156,11 @@ impl Validator<'a, 'mir, 'tcx> {
 
         let qualifs = Qualifs { needs_drop, has_mut_interior, indirectly_mutable };
 
-        Validator { span: item.body.span, item, qualifs }
+        Validator { span: ccx.body.span, ccx, qualifs }
     }
 
     pub fn check_body(&mut self) {
-        let Item { tcx, body, def_id, const_kind, .. } = *self.item;
+        let ConstCx { tcx, body, def_id, const_kind, .. } = *self.ccx;
 
         let use_min_const_fn_checks = (const_kind == Some(ConstKind::ConstFn)
             && crate::const_eval::is_min_const_fn(tcx, def_id))
@@ -175,7 +175,7 @@ impl Validator<'a, 'mir, 'tcx> {
             }
         }
 
-        check_short_circuiting_in_const_local(self.item);
+        check_short_circuiting_in_const_local(self.ccx);
 
         if body.is_cfg_cyclic() {
             // We can't provide a good span for the error here, but this should be caught by the
@@ -196,7 +196,7 @@ impl Validator<'a, 'mir, 'tcx> {
     }
 
     pub fn qualifs_in_return_place(&mut self) -> ConstQualifs {
-        self.qualifs.in_return_place(self.item)
+        self.qualifs.in_return_place(self.ccx)
     }
 
     /// Emits an error at the given `span` if an expression cannot be evaluated in the current
@@ -345,7 +345,7 @@ impl Visitor<'tcx> for Validator<'_, 'mir, 'tcx> {
             | Rvalue::Ref(_, BorrowKind::Shallow, ref place)
             | Rvalue::AddressOf(Mutability::Not, ref place) => {
                 let borrowed_place_has_mut_interior = qualifs::in_place::<HasMutInterior, _>(
-                    &self.item,
+                    &self.ccx,
                     &mut |local| self.qualifs.has_mut_interior(local, location),
                     place.as_ref(),
                 );
@@ -591,8 +591,8 @@ fn error_min_const_fn_violation(tcx: TyCtxt<'_>, span: Span, msg: Cow<'_, str>)
         .emit();
 }
 
-fn check_short_circuiting_in_const_local(item: &Item<'_, 'tcx>) {
-    let body = item.body;
+fn check_short_circuiting_in_const_local(ccx: &ConstCx<'_, 'tcx>) {
+    let body = ccx.body;
 
     if body.control_flow_destroyed.is_empty() {
         return;
@@ -601,12 +601,12 @@ fn check_short_circuiting_in_const_local(item: &Item<'_, 'tcx>) {
     let mut locals = body.vars_iter();
     if let Some(local) = locals.next() {
         let span = body.local_decls[local].source_info.span;
-        let mut error = item.tcx.sess.struct_span_err(
+        let mut error = ccx.tcx.sess.struct_span_err(
             span,
             &format!(
                 "new features like let bindings are not permitted in {}s \
                 which also use short circuiting operators",
-                item.const_kind(),
+                ccx.const_kind(),
             ),
         );
         for (span, kind) in body.control_flow_destroyed.iter() {
diff --git a/src/librustc_mir/transform/mod.rs b/src/librustc_mir/transform/mod.rs
index 18b3e88c86fee..6b75b25d85b2a 100644
--- a/src/librustc_mir/transform/mod.rs
+++ b/src/librustc_mir/transform/mod.rs
@@ -194,7 +194,7 @@ fn mir_const_qualif(tcx: TyCtxt<'_>, def_id: DefId) -> ConstQualifs {
         return Default::default();
     }
 
-    let item = check_consts::Item {
+    let ccx = check_consts::ConstCx {
         body: body.unwrap_read_only(),
         tcx,
         def_id,
@@ -202,7 +202,7 @@ fn mir_const_qualif(tcx: TyCtxt<'_>, def_id: DefId) -> ConstQualifs {
         param_env: tcx.param_env(def_id),
     };
 
-    let mut validator = check_consts::validation::Validator::new(&item);
+    let mut validator = check_consts::validation::Validator::new(&ccx);
     validator.check_body();
 
     // We return the qualifs in the return place for every MIR body, even though it is only used
diff --git a/src/librustc_mir/transform/promote_consts.rs b/src/librustc_mir/transform/promote_consts.rs
index 34fa12e1b5683..8163d15e9d4f7 100644
--- a/src/librustc_mir/transform/promote_consts.rs
+++ b/src/librustc_mir/transform/promote_consts.rs
@@ -30,7 +30,7 @@ use std::cell::Cell;
 use std::{cmp, iter, mem, usize};
 
 use crate::const_eval::{is_const_fn, is_unstable_const_fn};
-use crate::transform::check_consts::{is_lang_panic_fn, qualifs, ConstKind, Item};
+use crate::transform::check_consts::{is_lang_panic_fn, qualifs, ConstCx, ConstKind};
 use crate::transform::{MirPass, MirSource};
 
 /// A `MirPass` for promotion.
@@ -265,7 +265,7 @@ pub fn collect_temps_and_candidates(
 ///
 /// This wraps an `Item`, and has access to all fields of that `Item` via `Deref` coercion.
 struct Validator<'a, 'tcx> {
-    item: Item<'a, 'tcx>,
+    ccx: ConstCx<'a, 'tcx>,
     temps: &'a IndexVec<Local, TempState>,
 
     /// Explicit promotion happens e.g. for constant arguments declared via
@@ -278,10 +278,10 @@ struct Validator<'a, 'tcx> {
 }
 
 impl std::ops::Deref for Validator<'a, 'tcx> {
-    type Target = Item<'a, 'tcx>;
+    type Target = ConstCx<'a, 'tcx>;
 
     fn deref(&self) -> &Self::Target {
-        &self.item
+        &self.ccx
     }
 }
 
@@ -414,7 +414,7 @@ impl<'tcx> Validator<'_, 'tcx> {
                 let statement = &self.body[loc.block].statements[loc.statement_index];
                 match &statement.kind {
                     StatementKind::Assign(box (_, rhs)) => qualifs::in_rvalue::<Q, _>(
-                        &self.item,
+                        &self.ccx,
                         &mut |l| self.qualif_local::<Q>(l),
                         rhs,
                     ),
@@ -431,7 +431,7 @@ impl<'tcx> Validator<'_, 'tcx> {
                 match &terminator.kind {
                     TerminatorKind::Call { .. } => {
                         let return_ty = self.body.local_decls[local].ty;
-                        Q::in_any_value_of_ty(&self.item, return_ty)
+                        Q::in_any_value_of_ty(&self.ccx, return_ty)
                     }
                     kind => {
                         span_bug!(terminator.source_info.span, "{:?} not promotable", kind);
@@ -724,7 +724,7 @@ pub fn validate_candidates(
     temps: &IndexVec<Local, TempState>,
     candidates: &[Candidate],
 ) -> Vec<Candidate> {
-    let mut validator = Validator { item: Item::new(tcx, def_id, body), temps, explicit: false };
+    let mut validator = Validator { ccx: ConstCx::new(tcx, def_id, body), temps, explicit: false };
 
     candidates
         .iter()
@@ -1161,7 +1161,7 @@ crate fn should_suggest_const_in_array_repeat_expressions_attribute<'tcx>(
     let mut rpo = traversal::reverse_postorder(&body);
     let (temps, _) = collect_temps_and_candidates(tcx, &body, &mut rpo);
     let validator =
-        Validator { item: Item::new(tcx, mir_def_id, body), temps: &temps, explicit: false };
+        Validator { ccx: ConstCx::new(tcx, mir_def_id, body), temps: &temps, explicit: false };
 
     let should_promote = validator.validate_operand(operand).is_ok();
     let feature_flag = tcx.features().const_in_array_repeat_expressions;

From 77345ccf711038dc26fc93b8b67428f3139d6283 Mon Sep 17 00:00:00 2001
From: Oliver Scherer <github35764891676564198441@oli-obk.de>
Date: Thu, 2 Apr 2020 16:14:11 +0200
Subject: [PATCH 03/12] Use ConstCx in more places

---
 src/librustc_mir/borrow_check/type_check/mod.rs | 16 +++++++++++-----
 src/librustc_mir/transform/check_consts/mod.rs  |  9 +++++++++
 src/librustc_mir/transform/promote_consts.rs    | 17 +++++++----------
 3 files changed, 27 insertions(+), 15 deletions(-)

diff --git a/src/librustc_mir/borrow_check/type_check/mod.rs b/src/librustc_mir/borrow_check/type_check/mod.rs
index 1d66bd13c6fe6..0a8958f07ff75 100644
--- a/src/librustc_mir/borrow_check/type_check/mod.rs
+++ b/src/librustc_mir/borrow_check/type_check/mod.rs
@@ -42,7 +42,10 @@ use rustc_trait_selection::traits::{self, ObligationCause, PredicateObligations}
 use crate::dataflow::move_paths::MoveData;
 use crate::dataflow::MaybeInitializedPlaces;
 use crate::dataflow::ResultsCursor;
-use crate::transform::promote_consts::should_suggest_const_in_array_repeat_expressions_attribute;
+use crate::transform::{
+    check_consts::ConstCx,
+    promote_consts::should_suggest_const_in_array_repeat_expressions_attribute,
+};
 
 use crate::borrow_check::{
     borrow_set::BorrowSet,
@@ -1997,14 +2000,17 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
                         let span = body.source_info(location).span;
                         let ty = operand.ty(*body, tcx);
                         if !self.infcx.type_is_copy_modulo_regions(self.param_env, ty, span) {
+                            let ccx = ConstCx::new_with_param_env(
+                                tcx,
+                                self.mir_def_id,
+                                body,
+                                self.param_env,
+                            );
                             // To determine if `const_in_array_repeat_expressions` feature gate should
                             // be mentioned, need to check if the rvalue is promotable.
                             let should_suggest =
                                 should_suggest_const_in_array_repeat_expressions_attribute(
-                                    tcx,
-                                    self.mir_def_id,
-                                    body,
-                                    operand,
+                                    ccx, operand,
                                 );
                             debug!("check_rvalue: should_suggest={:?}", should_suggest);
 
diff --git a/src/librustc_mir/transform/check_consts/mod.rs b/src/librustc_mir/transform/check_consts/mod.rs
index cd4d492c5798e..115523b1f7e05 100644
--- a/src/librustc_mir/transform/check_consts/mod.rs
+++ b/src/librustc_mir/transform/check_consts/mod.rs
@@ -35,6 +35,15 @@ impl ConstCx<'mir, 'tcx> {
         body: mir::ReadOnlyBodyAndCache<'mir, 'tcx>,
     ) -> Self {
         let param_env = tcx.param_env(def_id);
+        Self::new_with_param_env(tcx, def_id, body, param_env)
+    }
+
+    pub fn new_with_param_env(
+        tcx: TyCtxt<'tcx>,
+        def_id: DefId,
+        body: mir::ReadOnlyBodyAndCache<'mir, 'tcx>,
+        param_env: ty::ParamEnv<'tcx>,
+    ) -> Self {
         let const_kind = ConstKind::for_item(tcx, def_id);
 
         ConstCx { body, tcx, def_id, param_env, const_kind }
diff --git a/src/librustc_mir/transform/promote_consts.rs b/src/librustc_mir/transform/promote_consts.rs
index 8163d15e9d4f7..ff4a21aba03a9 100644
--- a/src/librustc_mir/transform/promote_consts.rs
+++ b/src/librustc_mir/transform/promote_consts.rs
@@ -1153,22 +1153,19 @@ pub fn promote_candidates<'tcx>(
 /// Feature attribute should be suggested if `operand` can be promoted and the feature is not
 /// enabled.
 crate fn should_suggest_const_in_array_repeat_expressions_attribute<'tcx>(
-    tcx: TyCtxt<'tcx>,
-    mir_def_id: DefId,
-    body: ReadOnlyBodyAndCache<'_, 'tcx>,
+    ccx: ConstCx<'_, 'tcx>,
     operand: &Operand<'tcx>,
 ) -> bool {
-    let mut rpo = traversal::reverse_postorder(&body);
-    let (temps, _) = collect_temps_and_candidates(tcx, &body, &mut rpo);
-    let validator =
-        Validator { ccx: ConstCx::new(tcx, mir_def_id, body), temps: &temps, explicit: false };
+    let mut rpo = traversal::reverse_postorder(&ccx.body);
+    let (temps, _) = collect_temps_and_candidates(ccx.tcx, &ccx.body, &mut rpo);
+    let validator = Validator { ccx, temps: &temps, explicit: false };
 
     let should_promote = validator.validate_operand(operand).is_ok();
-    let feature_flag = tcx.features().const_in_array_repeat_expressions;
+    let feature_flag = validator.ccx.tcx.features().const_in_array_repeat_expressions;
     debug!(
-        "should_suggest_const_in_array_repeat_expressions_flag: mir_def_id={:?} \
+        "should_suggest_const_in_array_repeat_expressions_flag: def_id={:?} \
             should_promote={:?} feature_flag={:?}",
-        mir_def_id, should_promote, feature_flag
+        validator.ccx.def_id, should_promote, feature_flag
     );
     should_promote && !feature_flag
 }

From ee868e0193cf99cea54cb9bab5c53795bfb2c00d Mon Sep 17 00:00:00 2001
From: Oliver Scherer <github35764891676564198441@oli-obk.de>
Date: Thu, 2 Apr 2020 16:32:01 +0200
Subject: [PATCH 04/12] Use ConstCx in the promoted collector

---
 src/librustc_mir/transform/promote_consts.rs | 38 ++++++++++----------
 1 file changed, 20 insertions(+), 18 deletions(-)

diff --git a/src/librustc_mir/transform/promote_consts.rs b/src/librustc_mir/transform/promote_consts.rs
index ff4a21aba03a9..95842d337f457 100644
--- a/src/librustc_mir/transform/promote_consts.rs
+++ b/src/librustc_mir/transform/promote_consts.rs
@@ -61,11 +61,16 @@ impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> {
 
         let def_id = src.def_id();
 
-        let mut rpo = traversal::reverse_postorder(body);
-        let (temps, all_candidates) = collect_temps_and_candidates(tcx, body, &mut rpo);
+        let read_only_body = read_only!(body);
+
+        let mut rpo = traversal::reverse_postorder(&read_only_body);
+
+        let ccx = ConstCx::new(tcx, def_id, read_only_body);
+
+        let (temps, all_candidates) = collect_temps_and_candidates(&ccx, &mut rpo);
 
         let promotable_candidates =
-            validate_candidates(tcx, read_only!(body), def_id, &temps, &all_candidates);
+            validate_candidates(tcx, read_only_body, def_id, &temps, &all_candidates);
 
         let promoted = promote_candidates(def_id, body, tcx, temps, promotable_candidates);
         self.promoted_fragments.set(promoted);
@@ -140,8 +145,7 @@ fn args_required_const(tcx: TyCtxt<'_>, def_id: DefId) -> Option<Vec<usize>> {
 }
 
 struct Collector<'a, 'tcx> {
-    tcx: TyCtxt<'tcx>,
-    body: &'a Body<'tcx>,
+    ccx: &'a ConstCx<'a, 'tcx>,
     temps: IndexVec<Local, TempState>,
     candidates: Vec<Candidate>,
     span: Span,
@@ -151,7 +155,7 @@ impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
     fn visit_local(&mut self, &index: &Local, context: PlaceContext, location: Location) {
         debug!("visit_local: index={:?} context={:?} location={:?}", index, context, location);
         // We're only interested in temporaries and the return place
-        match self.body.local_kind(index) {
+        match self.ccx.body.local_kind(index) {
             LocalKind::Temp | LocalKind::ReturnPointer => {}
             LocalKind::Arg | LocalKind::Var => return,
         }
@@ -204,7 +208,7 @@ impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
             Rvalue::Ref(..) => {
                 self.candidates.push(Candidate::Ref(location));
             }
-            Rvalue::Repeat(..) if self.tcx.features().const_in_array_repeat_expressions => {
+            Rvalue::Repeat(..) if self.ccx.tcx.features().const_in_array_repeat_expressions => {
                 // FIXME(#49147) only promote the element when it isn't `Copy`
                 // (so that code that can copy it at runtime is unaffected).
                 self.candidates.push(Candidate::Repeat(location));
@@ -217,10 +221,10 @@ impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
         self.super_terminator_kind(kind, location);
 
         if let TerminatorKind::Call { ref func, .. } = *kind {
-            if let ty::FnDef(def_id, _) = func.ty(self.body, self.tcx).kind {
-                let fn_sig = self.tcx.fn_sig(def_id);
+            if let ty::FnDef(def_id, _) = func.ty(*self.ccx.body, self.ccx.tcx).kind {
+                let fn_sig = self.ccx.tcx.fn_sig(def_id);
                 if let Abi::RustIntrinsic | Abi::PlatformIntrinsic = fn_sig.abi() {
-                    let name = self.tcx.item_name(def_id);
+                    let name = self.ccx.tcx.item_name(def_id);
                     // FIXME(eddyb) use `#[rustc_args_required_const(2)]` for shuffles.
                     if name.as_str().starts_with("simd_shuffle") {
                         self.candidates.push(Candidate::Argument { bb: location.block, index: 2 });
@@ -229,7 +233,7 @@ impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
                     }
                 }
 
-                if let Some(constant_args) = args_required_const(self.tcx, def_id) {
+                if let Some(constant_args) = args_required_const(self.ccx.tcx, def_id) {
                     for index in constant_args {
                         self.candidates.push(Candidate::Argument { bb: location.block, index });
                     }
@@ -244,16 +248,14 @@ impl<'tcx> Visitor<'tcx> for Collector<'_, 'tcx> {
 }
 
 pub fn collect_temps_and_candidates(
-    tcx: TyCtxt<'tcx>,
-    body: &Body<'tcx>,
+    ccx: &ConstCx<'mir, 'tcx>,
     rpo: &mut ReversePostorder<'_, 'tcx>,
 ) -> (IndexVec<Local, TempState>, Vec<Candidate>) {
     let mut collector = Collector {
-        tcx,
-        body,
-        temps: IndexVec::from_elem(TempState::Undefined, &body.local_decls),
+        temps: IndexVec::from_elem(TempState::Undefined, &ccx.body.local_decls),
         candidates: vec![],
-        span: body.span,
+        span: ccx.body.span,
+        ccx,
     };
     for (bb, data) in rpo {
         collector.visit_basic_block_data(bb, data);
@@ -1157,7 +1159,7 @@ crate fn should_suggest_const_in_array_repeat_expressions_attribute<'tcx>(
     operand: &Operand<'tcx>,
 ) -> bool {
     let mut rpo = traversal::reverse_postorder(&ccx.body);
-    let (temps, _) = collect_temps_and_candidates(ccx.tcx, &ccx.body, &mut rpo);
+    let (temps, _) = collect_temps_and_candidates(&ccx, &mut rpo);
     let validator = Validator { ccx, temps: &temps, explicit: false };
 
     let should_promote = validator.validate_operand(operand).is_ok();

From 29aebf498dff698dd20f37e0f2fccf7bcc01bde5 Mon Sep 17 00:00:00 2001
From: Oliver Scherer <github35764891676564198441@oli-obk.de>
Date: Thu, 2 Apr 2020 16:38:50 +0200
Subject: [PATCH 05/12] Use `ConstCx` for `validate_candidates`

---
 src/librustc_mir/borrow_check/type_check/mod.rs |  2 +-
 src/librustc_mir/transform/promote_consts.rs    | 17 +++++++----------
 2 files changed, 8 insertions(+), 11 deletions(-)

diff --git a/src/librustc_mir/borrow_check/type_check/mod.rs b/src/librustc_mir/borrow_check/type_check/mod.rs
index 0a8958f07ff75..3ad3cfe5ab41f 100644
--- a/src/librustc_mir/borrow_check/type_check/mod.rs
+++ b/src/librustc_mir/borrow_check/type_check/mod.rs
@@ -2010,7 +2010,7 @@ impl<'a, 'tcx> TypeChecker<'a, 'tcx> {
                             // be mentioned, need to check if the rvalue is promotable.
                             let should_suggest =
                                 should_suggest_const_in_array_repeat_expressions_attribute(
-                                    ccx, operand,
+                                    &ccx, operand,
                                 );
                             debug!("check_rvalue: should_suggest={:?}", should_suggest);
 
diff --git a/src/librustc_mir/transform/promote_consts.rs b/src/librustc_mir/transform/promote_consts.rs
index 95842d337f457..578a6abfeba2e 100644
--- a/src/librustc_mir/transform/promote_consts.rs
+++ b/src/librustc_mir/transform/promote_consts.rs
@@ -69,8 +69,7 @@ impl<'tcx> MirPass<'tcx> for PromoteTemps<'tcx> {
 
         let (temps, all_candidates) = collect_temps_and_candidates(&ccx, &mut rpo);
 
-        let promotable_candidates =
-            validate_candidates(tcx, read_only_body, def_id, &temps, &all_candidates);
+        let promotable_candidates = validate_candidates(&ccx, &temps, &all_candidates);
 
         let promoted = promote_candidates(def_id, body, tcx, temps, promotable_candidates);
         self.promoted_fragments.set(promoted);
@@ -267,7 +266,7 @@ pub fn collect_temps_and_candidates(
 ///
 /// This wraps an `Item`, and has access to all fields of that `Item` via `Deref` coercion.
 struct Validator<'a, 'tcx> {
-    ccx: ConstCx<'a, 'tcx>,
+    ccx: &'a ConstCx<'a, 'tcx>,
     temps: &'a IndexVec<Local, TempState>,
 
     /// Explicit promotion happens e.g. for constant arguments declared via
@@ -720,13 +719,11 @@ impl<'tcx> Validator<'_, 'tcx> {
 
 // FIXME(eddyb) remove the differences for promotability in `static`, `const`, `const fn`.
 pub fn validate_candidates(
-    tcx: TyCtxt<'tcx>,
-    body: ReadOnlyBodyAndCache<'_, 'tcx>,
-    def_id: DefId,
+    ccx: &ConstCx<'_, '_>,
     temps: &IndexVec<Local, TempState>,
     candidates: &[Candidate],
 ) -> Vec<Candidate> {
-    let mut validator = Validator { ccx: ConstCx::new(tcx, def_id, body), temps, explicit: false };
+    let mut validator = Validator { ccx, temps, explicit: false };
 
     candidates
         .iter()
@@ -740,9 +737,9 @@ pub fn validate_candidates(
             let is_promotable = validator.validate_candidate(candidate).is_ok();
             match candidate {
                 Candidate::Argument { bb, index } if !is_promotable => {
-                    let span = body[bb].terminator().source_info.span;
+                    let span = ccx.body[bb].terminator().source_info.span;
                     let msg = format!("argument {} is required to be a constant", index + 1);
-                    tcx.sess.span_err(span, &msg);
+                    ccx.tcx.sess.span_err(span, &msg);
                 }
                 _ => (),
             }
@@ -1155,7 +1152,7 @@ pub fn promote_candidates<'tcx>(
 /// Feature attribute should be suggested if `operand` can be promoted and the feature is not
 /// enabled.
 crate fn should_suggest_const_in_array_repeat_expressions_attribute<'tcx>(
-    ccx: ConstCx<'_, 'tcx>,
+    ccx: &ConstCx<'_, 'tcx>,
     operand: &Operand<'tcx>,
 ) -> bool {
     let mut rpo = traversal::reverse_postorder(&ccx.body);

From f5c33151ecec3434b8e032a656d8f57982c21e11 Mon Sep 17 00:00:00 2001
From: Oliver Scherer <github35764891676564198441@oli-obk.de>
Date: Mon, 6 Apr 2020 18:37:26 +0200
Subject: [PATCH 06/12] Catch and fix explicit promotions that fail to actually
 promote

---
 src/librustc_mir/transform/promote_consts.rs | 8 ++++++++
 1 file changed, 8 insertions(+)

diff --git a/src/librustc_mir/transform/promote_consts.rs b/src/librustc_mir/transform/promote_consts.rs
index 578a6abfeba2e..feff5989d0ec3 100644
--- a/src/librustc_mir/transform/promote_consts.rs
+++ b/src/librustc_mir/transform/promote_consts.rs
@@ -735,6 +735,14 @@ pub fn validate_candidates(
             // and `#[rustc_args_required_const]` arguments here.
 
             let is_promotable = validator.validate_candidate(candidate).is_ok();
+
+            if validator.explicit && !is_promotable {
+                ccx.tcx.sess.delay_span_bug(
+                    ccx.body.span,
+                    "Explicit promotion requested, but failed to promote",
+                );
+            }
+
             match candidate {
                 Candidate::Argument { bb, index } if !is_promotable => {
                     let span = ccx.body[bb].terminator().source_info.span;

From 316a401488ab7048159f9819a521d6cf2957b6c8 Mon Sep 17 00:00:00 2001
From: Oliver Scherer <github35764891676564198441@oli-obk.de>
Date: Thu, 16 Apr 2020 15:06:17 +0200
Subject: [PATCH 07/12] Document our sanity assertion around explicit promotion

---
 src/librustc_mir/transform/promote_consts.rs | 4 ++++
 1 file changed, 4 insertions(+)

diff --git a/src/librustc_mir/transform/promote_consts.rs b/src/librustc_mir/transform/promote_consts.rs
index feff5989d0ec3..9b9ab77f74153 100644
--- a/src/librustc_mir/transform/promote_consts.rs
+++ b/src/librustc_mir/transform/promote_consts.rs
@@ -736,6 +736,10 @@ pub fn validate_candidates(
 
             let is_promotable = validator.validate_candidate(candidate).is_ok();
 
+            // If we use explicit validation, we carry the risk of turning a legitimate run-time
+            // operation into a failing compile-time operation. Make sure that does not happen
+            // by asserting that there is no possible run-time behavior here in case promotion
+            // fails.
             if validator.explicit && !is_promotable {
                 ccx.tcx.sess.delay_span_bug(
                     ccx.body.span,

From 7fe41279c5b6cca8c16f94f12ef4bf8811943599 Mon Sep 17 00:00:00 2001
From: Amanieu d'Antras <amanieu@gmail.com>
Date: Fri, 17 Apr 2020 19:53:31 +0100
Subject: [PATCH 08/12] Make -Zprofile set codegen-units to 1

---
 src/librustc_session/config.rs | 12 +++++++++++-
 1 file changed, 11 insertions(+), 1 deletion(-)

diff --git a/src/librustc_session/config.rs b/src/librustc_session/config.rs
index aaf30c583e263..ba2a4d1d56f23 100644
--- a/src/librustc_session/config.rs
+++ b/src/librustc_session/config.rs
@@ -1655,7 +1655,7 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
     let output_types = parse_output_types(&debugging_opts, matches, error_format);
 
     let mut cg = build_codegen_options(matches, error_format);
-    let (disable_thinlto, codegen_units) = should_override_cgus_and_disable_thinlto(
+    let (disable_thinlto, mut codegen_units) = should_override_cgus_and_disable_thinlto(
         &output_types,
         matches,
         error_format,
@@ -1672,6 +1672,16 @@ pub fn build_session_options(matches: &getopts::Matches) -> Options {
             "can't instrument with gcov profiling when compiling incrementally",
         );
     }
+    if debugging_opts.profile {
+        match codegen_units {
+            Some(1) => {}
+            None => codegen_units = Some(1),
+            Some(_) => early_error(
+                error_format,
+                "can't instrument with gcov profiling with multiple codegen units",
+            ),
+        }
+    }
 
     if cg.profile_generate.enabled() && cg.profile_use.is_some() {
         early_error(

From c7899a027ee7b563664a2f6b2967e1f96e2e619a Mon Sep 17 00:00:00 2001
From: Shea Levy <shea@shealevy.com>
Date: Fri, 17 Apr 2020 17:51:32 -0400
Subject: [PATCH 09/12] Remove unused abs_path method from
 rustc_span::source_map::FileLoader

---
 src/librustc_span/source_map.rs | 12 ------------
 1 file changed, 12 deletions(-)

diff --git a/src/librustc_span/source_map.rs b/src/librustc_span/source_map.rs
index 49e2144b3e380..d27aae0d6ed9b 100644
--- a/src/librustc_span/source_map.rs
+++ b/src/librustc_span/source_map.rs
@@ -20,7 +20,6 @@ use std::path::{Path, PathBuf};
 use std::sync::atomic::Ordering;
 
 use log::debug;
-use std::env;
 use std::fs;
 use std::io;
 
@@ -64,9 +63,6 @@ pub trait FileLoader {
     /// Query the existence of a file.
     fn file_exists(&self, path: &Path) -> bool;
 
-    /// Returns an absolute path to a file, if possible.
-    fn abs_path(&self, path: &Path) -> Option<PathBuf>;
-
     /// Read the contents of an UTF-8 file into memory.
     fn read_file(&self, path: &Path) -> io::Result<String>;
 }
@@ -79,14 +75,6 @@ impl FileLoader for RealFileLoader {
         fs::metadata(path).is_ok()
     }
 
-    fn abs_path(&self, path: &Path) -> Option<PathBuf> {
-        if path.is_absolute() {
-            Some(path.to_path_buf())
-        } else {
-            env::current_dir().ok().map(|cwd| cwd.join(path))
-        }
-    }
-
     fn read_file(&self, path: &Path) -> io::Result<String> {
         fs::read_to_string(path)
     }

From 58ad251ea83ccf069a7957b87bd614194bf7f663 Mon Sep 17 00:00:00 2001
From: Yuki Okushi <huyuumi.dev@gmail.com>
Date: Sat, 18 Apr 2020 13:01:54 +0900
Subject: [PATCH 10/12] Move `MapInPlace` to rustc_data_structures

---
 src/librustc_ast/lib.rs                                         | 1 -
 src/librustc_ast/mut_visit.rs                                   | 2 +-
 src/librustc_builtin_macros/deriving/generic/mod.rs             | 2 +-
 src/librustc_data_structures/lib.rs                             | 1 +
 .../util => librustc_data_structures}/map_in_place.rs           | 2 --
 src/librustc_expand/config.rs                                   | 2 +-
 src/librustc_expand/expand.rs                                   | 2 +-
 7 files changed, 5 insertions(+), 7 deletions(-)
 rename src/{librustc_ast/util => librustc_data_structures}/map_in_place.rs (98%)

diff --git a/src/librustc_ast/lib.rs b/src/librustc_ast/lib.rs
index 1687f828f240f..4ba062625a40d 100644
--- a/src/librustc_ast/lib.rs
+++ b/src/librustc_ast/lib.rs
@@ -33,7 +33,6 @@ pub mod util {
     pub mod comments;
     pub mod lev_distance;
     pub mod literal;
-    pub mod map_in_place;
     pub mod parser;
 }
 
diff --git a/src/librustc_ast/mut_visit.rs b/src/librustc_ast/mut_visit.rs
index a72a60c30b28a..e66b358c4ac7f 100644
--- a/src/librustc_ast/mut_visit.rs
+++ b/src/librustc_ast/mut_visit.rs
@@ -11,8 +11,8 @@ use crate::ast::*;
 use crate::ptr::P;
 use crate::token::{self, Token};
 use crate::tokenstream::*;
-use crate::util::map_in_place::MapInPlace;
 
+use rustc_data_structures::map_in_place::MapInPlace;
 use rustc_data_structures::sync::Lrc;
 use rustc_span::source_map::{respan, Spanned};
 use rustc_span::Span;
diff --git a/src/librustc_builtin_macros/deriving/generic/mod.rs b/src/librustc_builtin_macros/deriving/generic/mod.rs
index 9338f9afbbb31..3a96c5aa8ed4f 100644
--- a/src/librustc_builtin_macros/deriving/generic/mod.rs
+++ b/src/librustc_builtin_macros/deriving/generic/mod.rs
@@ -184,8 +184,8 @@ use std::vec;
 use rustc_ast::ast::{self, BinOpKind, EnumDef, Expr, Generics, Ident, PatKind};
 use rustc_ast::ast::{GenericArg, GenericParamKind, VariantData};
 use rustc_ast::ptr::P;
-use rustc_ast::util::map_in_place::MapInPlace;
 use rustc_attr as attr;
+use rustc_data_structures::map_in_place::MapInPlace;
 use rustc_expand::base::{Annotatable, ExtCtxt};
 use rustc_session::parse::ParseSess;
 use rustc_span::source_map::respan;
diff --git a/src/librustc_data_structures/lib.rs b/src/librustc_data_structures/lib.rs
index d0180911567c7..d412eaeff7424 100644
--- a/src/librustc_data_structures/lib.rs
+++ b/src/librustc_data_structures/lib.rs
@@ -67,6 +67,7 @@ pub mod fx;
 pub mod graph;
 pub mod jobserver;
 pub mod macros;
+pub mod map_in_place;
 pub mod obligation_forest;
 pub mod owning_ref;
 pub mod ptr_key;
diff --git a/src/librustc_ast/util/map_in_place.rs b/src/librustc_data_structures/map_in_place.rs
similarity index 98%
rename from src/librustc_ast/util/map_in_place.rs
rename to src/librustc_data_structures/map_in_place.rs
index a237a6e6162c0..5dd9fc6e8bc08 100644
--- a/src/librustc_ast/util/map_in_place.rs
+++ b/src/librustc_data_structures/map_in_place.rs
@@ -1,5 +1,3 @@
-// FIXME(Centril): Move to rustc_data_structures.
-
 use smallvec::{Array, SmallVec};
 use std::ptr;
 
diff --git a/src/librustc_expand/config.rs b/src/librustc_expand/config.rs
index 72c09f35dfa55..d79dabb509267 100644
--- a/src/librustc_expand/config.rs
+++ b/src/librustc_expand/config.rs
@@ -4,9 +4,9 @@ use rustc_ast::ast::{self, AttrItem, Attribute, MetaItem};
 use rustc_ast::attr::HasAttrs;
 use rustc_ast::mut_visit::*;
 use rustc_ast::ptr::P;
-use rustc_ast::util::map_in_place::MapInPlace;
 use rustc_attr as attr;
 use rustc_data_structures::fx::FxHashMap;
+use rustc_data_structures::map_in_place::MapInPlace;
 use rustc_errors::{error_code, struct_span_err, Applicability, Handler};
 use rustc_feature::{Feature, Features, State as FeatureState};
 use rustc_feature::{
diff --git a/src/librustc_expand/expand.rs b/src/librustc_expand/expand.rs
index 7473c890c5ab9..2618c758ca5da 100644
--- a/src/librustc_expand/expand.rs
+++ b/src/librustc_expand/expand.rs
@@ -13,10 +13,10 @@ use rustc_ast::mut_visit::*;
 use rustc_ast::ptr::P;
 use rustc_ast::token;
 use rustc_ast::tokenstream::TokenStream;
-use rustc_ast::util::map_in_place::MapInPlace;
 use rustc_ast::visit::{self, AssocCtxt, Visitor};
 use rustc_ast_pretty::pprust;
 use rustc_attr::{self as attr, is_builtin_attr, HasAttrs};
+use rustc_data_structures::map_in_place::MapInPlace;
 use rustc_errors::{Applicability, PResult};
 use rustc_feature::Features;
 use rustc_parse::parser::Parser;

From 9f23b2d36bf31b89a107b83a37665af08f6c0fb3 Mon Sep 17 00:00:00 2001
From: Amanieu d'Antras <amanieu@gmail.com>
Date: Fri, 17 Apr 2020 21:21:49 +0100
Subject: [PATCH 11/12] Add an option to inhibit automatic injection of
 profiler_builtins

---
 src/librustc_metadata/creader.rs | 4 +++-
 src/librustc_session/options.rs  | 2 ++
 2 files changed, 5 insertions(+), 1 deletion(-)

diff --git a/src/librustc_metadata/creader.rs b/src/librustc_metadata/creader.rs
index 3e5d7b8efd530..fe8fbd50627d3 100644
--- a/src/librustc_metadata/creader.rs
+++ b/src/librustc_metadata/creader.rs
@@ -686,7 +686,9 @@ impl<'a> CrateLoader<'a> {
     }
 
     fn inject_profiler_runtime(&mut self) {
-        if self.sess.opts.debugging_opts.profile || self.sess.opts.cg.profile_generate.enabled() {
+        if (self.sess.opts.debugging_opts.profile || self.sess.opts.cg.profile_generate.enabled())
+            && !self.sess.opts.debugging_opts.no_profiler_runtime
+        {
             info!("loading profiler");
 
             let name = Symbol::intern("profiler_builtins");
diff --git a/src/librustc_session/options.rs b/src/librustc_session/options.rs
index 8cd6ca86f4689..94e65093e71b2 100644
--- a/src/librustc_session/options.rs
+++ b/src/librustc_session/options.rs
@@ -890,6 +890,8 @@ options! {DebuggingOptions, DebuggingSetter, basic_debugging_options,
         "extra arguments to prepend to the linker invocation (space separated)"),
     profile: bool = (false, parse_bool, [TRACKED],
                      "insert profiling code"),
+    no_profiler_runtime: bool = (false, parse_bool, [TRACKED],
+        "don't automatically inject the profiler_builtins crate"),
     relro_level: Option<RelroLevel> = (None, parse_relro_level, [TRACKED],
         "choose which RELRO level to use"),
     nll_facts: bool = (false, parse_bool, [UNTRACKED],

From 1a461598280f3f0ed047c89d1f2ec10be354e609 Mon Sep 17 00:00:00 2001
From: Yuki Okushi <huyuumi.dev@gmail.com>
Date: Sun, 19 Apr 2020 01:03:43 +0900
Subject: [PATCH 12/12] Explain why we shouldn't add inline attr to into_vec

---
 src/liballoc/slice.rs | 3 +++
 1 file changed, 3 insertions(+)

diff --git a/src/liballoc/slice.rs b/src/liballoc/slice.rs
index c13e90a3d7081..53477288b59ee 100644
--- a/src/liballoc/slice.rs
+++ b/src/liballoc/slice.rs
@@ -140,6 +140,9 @@ mod hack {
     use crate::string::ToString;
     use crate::vec::Vec;
 
+    // We shouldn't add inline attribute to this since this is used in
+    // `vec!` macro mostly and causes perf regression. See #71204 for
+    // discussion and perf results.
     pub fn into_vec<T>(b: Box<[T]>) -> Vec<T> {
         unsafe {
             let len = b.len();