]> git.lizzy.rs Git - rust.git/blobdiff - src/constant.rs
Rollup merge of #81618 - bjorn3:sync_cg_clif-2021-02-01, r=bjorn3
[rust.git] / src / constant.rs
index d1248110d06cd553a6797fff476fcccf754d8823..5702832bcb67d99ac60baa6cb5bbd75bcedc5908 100644 (file)
@@ -1,3 +1,5 @@
+//! Handling of `static`s, `const`s and promoted allocations
+
 use rustc_span::DUMMY_SP;
 
 use rustc_data_structures::fx::FxHashSet;
@@ -7,7 +9,6 @@
     read_target_uint, AllocId, Allocation, ConstValue, ErrorHandled, GlobalAlloc, Pointer, Scalar,
 };
 use rustc_middle::ty::{Const, ConstKind};
-use rustc_target::abi::Align;
 
 use cranelift_codegen::ir::GlobalValueData;
 use cranelift_module::*;
@@ -27,7 +28,7 @@ enum TodoItem {
 }
 
 impl ConstantCx {
-    pub(crate) fn finalize(mut self, tcx: TyCtxt<'_>, module: &mut Module<impl Backend>) {
+    pub(crate) fn finalize(mut self, tcx: TyCtxt<'_>, module: &mut impl Module) {
         //println!("todo {:?}", self.todo);
         define_all_allocs(tcx, module, &mut self);
         //println!("done {:?}", self.done);
@@ -35,9 +36,9 @@ pub(crate) fn finalize(mut self, tcx: TyCtxt<'_>, module: &mut Module<impl Backe
     }
 }
 
-pub(crate) fn check_constants(fx: &mut FunctionCx<'_, '_, impl Backend>) {
+pub(crate) fn check_constants(fx: &mut FunctionCx<'_, '_, impl Module>) {
     for constant in &fx.mir.required_consts {
-        let const_ = fx.monomorphize(&constant.literal);
+        let const_ = fx.monomorphize(constant.literal);
         match const_.val {
             ConstKind::Value(_) => {}
             ConstKind::Unevaluated(def, ref substs, promoted) => {
@@ -75,7 +76,7 @@ pub(crate) fn codegen_static(constants_cx: &mut ConstantCx, def_id: DefId) {
 }
 
 pub(crate) fn codegen_tls_ref<'tcx>(
-    fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
+    fx: &mut FunctionCx<'_, 'tcx, impl Module>,
     def_id: DefId,
     layout: TyAndLayout<'tcx>,
 ) -> CValue<'tcx> {
@@ -88,7 +89,7 @@ pub(crate) fn codegen_tls_ref<'tcx>(
 }
 
 fn codegen_static_ref<'tcx>(
-    fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
+    fx: &mut FunctionCx<'_, 'tcx, impl Module>,
     def_id: DefId,
     layout: TyAndLayout<'tcx>,
 ) -> CPlace<'tcx> {
@@ -99,17 +100,20 @@ fn codegen_static_ref<'tcx>(
     let global_ptr = fx.bcx.ins().global_value(fx.pointer_type, local_data_id);
     assert!(!layout.is_unsized(), "unsized statics aren't supported");
     assert!(
-        matches!(fx.bcx.func.global_values[local_data_id], GlobalValueData::Symbol { tls: false, ..}),
+        matches!(
+            fx.bcx.func.global_values[local_data_id],
+            GlobalValueData::Symbol { tls: false, .. }
+        ),
         "tls static referenced without Rvalue::ThreadLocalRef"
     );
     CPlace::for_ptr(crate::pointer::Pointer::new(global_ptr), layout)
 }
 
-pub(crate) fn trans_constant<'tcx>(
-    fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
+pub(crate) fn codegen_constant<'tcx>(
+    fx: &mut FunctionCx<'_, 'tcx, impl Module>,
     constant: &Constant<'tcx>,
 ) -> CValue<'tcx> {
-    let const_ = fx.monomorphize(&constant.literal);
+    let const_ = fx.monomorphize(constant.literal);
     let const_val = match const_.val {
         ConstKind::Value(const_val) => const_val,
         ConstKind::Unevaluated(def, ref substs, promoted) if fx.tcx.is_static(def.did) => {
@@ -130,11 +134,9 @@ pub(crate) fn trans_constant<'tcx>(
             {
                 Ok(const_val) => const_val,
                 Err(_) => {
-                    if promoted.is_none() {
-                        fx.tcx
-                            .sess
-                            .span_err(constant.span, "erroneous constant encountered");
-                    }
+                    fx.tcx
+                        .sess
+                        .span_err(constant.span, "erroneous constant encountered");
                     return crate::trap::trap_unreachable_ret_value(
                         fx,
                         fx.layout_of(const_.ty),
@@ -150,11 +152,11 @@ pub(crate) fn trans_constant<'tcx>(
         | ConstKind::Error(_) => unreachable!("{:?}", const_),
     };
 
-    trans_const_value(fx, const_val, const_.ty)
+    codegen_const_value(fx, const_val, const_.ty)
 }
 
-pub(crate) fn trans_const_value<'tcx>(
-    fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
+pub(crate) fn codegen_const_value<'tcx>(
+    fx: &mut FunctionCx<'_, 'tcx, impl Module>,
     const_val: ConstValue<'tcx>,
     ty: Ty<'tcx>,
 ) -> CValue<'tcx> {
@@ -162,10 +164,7 @@ pub(crate) fn trans_const_value<'tcx>(
     assert!(!layout.is_unsized(), "sized const value");
 
     if layout.is_zst() {
-        return CValue::by_ref(
-            crate::Pointer::const_addr(fx, i64::try_from(layout.align.pref.bytes()).unwrap()),
-            layout,
-        );
+        return CValue::by_ref(crate::Pointer::dangling(layout.align.pref), layout);
     }
 
     match const_val {
@@ -185,10 +184,7 @@ pub(crate) fn trans_const_value<'tcx>(
             }
 
             match x {
-                Scalar::Raw { data, size } => {
-                    assert_eq!(u64::from(size), layout.size.bytes());
-                    return CValue::const_val(fx, layout, data);
-                }
+                Scalar::Int(int) => CValue::const_val(fx, layout, int),
                 Scalar::Ptr(ptr) => {
                     let alloc_kind = fx.tcx.get_global_alloc(ptr.alloc_id);
                     let base_addr = match alloc_kind {
@@ -197,7 +193,6 @@ pub(crate) fn trans_const_value<'tcx>(
                             let data_id = data_id_for_alloc_id(
                                 &mut fx.cx.module,
                                 ptr.alloc_id,
-                                alloc.align,
                                 alloc.mutability,
                             );
                             let local_data_id =
@@ -225,11 +220,14 @@ pub(crate) fn trans_const_value<'tcx>(
                         }
                         None => bug!("missing allocation {:?}", ptr.alloc_id),
                     };
-                    let val = fx
-                        .bcx
-                        .ins()
-                        .iadd_imm(base_addr, i64::try_from(ptr.offset.bytes()).unwrap());
-                    return CValue::by_val(val, layout);
+                    let val = if ptr.offset.bytes() != 0 {
+                        fx.bcx
+                            .ins()
+                            .iadd_imm(base_addr, i64::try_from(ptr.offset.bytes()).unwrap())
+                    } else {
+                        base_addr
+                    };
+                    CValue::by_val(val, layout)
                 }
             }
         }
@@ -252,12 +250,12 @@ pub(crate) fn trans_const_value<'tcx>(
 }
 
 fn pointer_for_allocation<'tcx>(
-    fx: &mut FunctionCx<'_, 'tcx, impl Backend>,
+    fx: &mut FunctionCx<'_, 'tcx, impl Module>,
     alloc: &'tcx Allocation,
 ) -> crate::pointer::Pointer {
     let alloc_id = fx.tcx.create_memory_alloc(alloc);
     fx.cx.constants_cx.todo.push(TodoItem::Alloc(alloc_id));
-    let data_id = data_id_for_alloc_id(&mut fx.cx.module, alloc_id, alloc.align, alloc.mutability);
+    let data_id = data_id_for_alloc_id(&mut fx.cx.module, alloc_id, alloc.mutability);
 
     let local_data_id = fx.cx.module.declare_data_in_func(data_id, &mut fx.bcx.func);
     #[cfg(debug_assertions)]
@@ -266,40 +264,36 @@ fn pointer_for_allocation<'tcx>(
     crate::pointer::Pointer::new(global_ptr)
 }
 
-fn data_id_for_alloc_id<B: Backend>(
-    module: &mut Module<B>,
+fn data_id_for_alloc_id(
+    module: &mut impl Module,
     alloc_id: AllocId,
-    align: Align,
     mutability: rustc_hir::Mutability,
 ) -> DataId {
     module
         .declare_data(
-            &format!("__alloc_{}", alloc_id.0),
+            &format!(".L__alloc_{:x}", alloc_id.0),
             Linkage::Local,
             mutability == rustc_hir::Mutability::Mut,
             false,
-            Some(align.bytes() as u8),
         )
         .unwrap()
 }
 
 fn data_id_for_static(
     tcx: TyCtxt<'_>,
-    module: &mut Module<impl Backend>,
+    module: &mut impl Module,
     def_id: DefId,
     definition: bool,
 ) -> DataId {
     let rlinkage = tcx.codegen_fn_attrs(def_id).linkage;
     let linkage = if definition {
         crate::linkage::get_static_linkage(tcx, def_id)
+    } else if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
+        || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
+    {
+        Linkage::Preemptible
     } else {
-        if rlinkage == Some(rustc_middle::mir::mono::Linkage::ExternalWeak)
-            || rlinkage == Some(rustc_middle::mir::mono::Linkage::WeakAny)
-        {
-            Linkage::Preemptible
-        } else {
-            Linkage::Import
-        }
+        Linkage::Import
     };
 
     let instance = Instance::mono(tcx, def_id).polymorphize(tcx);
@@ -325,7 +319,6 @@ fn data_id_for_static(
             linkage,
             is_mutable,
             attrs.flags.contains(CodegenFnAttrFlags::THREAD_LOCAL),
-            Some(align.try_into().unwrap()),
         )
         .unwrap();
 
@@ -340,15 +333,10 @@ fn data_id_for_static(
 
         let ref_name = format!("_rust_extern_with_linkage_{}", symbol_name);
         let ref_data_id = module
-            .declare_data(
-                &ref_name,
-                Linkage::Local,
-                true,
-                false,
-                Some(align.try_into().unwrap()),
-            )
+            .declare_data(&ref_name, Linkage::Local, false, false)
             .unwrap();
         let mut data_ctx = DataContext::new();
+        data_ctx.set_align(align);
         let data = module.declare_data_in_data(data_id, &mut data_ctx);
         data_ctx.define(
             std::iter::repeat(0)
@@ -368,7 +356,7 @@ fn data_id_for_static(
     }
 }
 
-fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut Module<impl Backend>, cx: &mut ConstantCx) {
+fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut impl Module, cx: &mut ConstantCx) {
     while let Some(todo_item) = cx.todo.pop() {
         let (data_id, alloc, section_name) = match todo_item {
             TodoItem::Alloc(alloc_id) => {
@@ -377,7 +365,7 @@ fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut Module<impl Backend>, cx: &mu
                     GlobalAlloc::Memory(alloc) => alloc,
                     GlobalAlloc::Function(_) | GlobalAlloc::Static(_) => unreachable!(),
                 };
-                let data_id = data_id_for_alloc_id(module, alloc_id, alloc.align, alloc.mutability);
+                let data_id = data_id_for_alloc_id(module, alloc_id, alloc.mutability);
                 (data_id, alloc, None)
             }
             TodoItem::Static(def_id) => {
@@ -388,12 +376,7 @@ fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut Module<impl Backend>, cx: &mu
                     .link_section
                     .map(|s| s.as_str());
 
-                let const_ = tcx.const_eval_poly(def_id).unwrap();
-
-                let alloc = match const_ {
-                    ConstValue::ByRef { alloc, offset } if offset.bytes() == 0 => alloc,
-                    _ => bug!("static const eval returned {:#?}", const_),
-                };
+                let alloc = tcx.eval_static_initializer(def_id).unwrap();
 
                 let data_id = data_id_for_static(tcx, module, def_id, true);
                 (data_id, alloc, section_name)
@@ -406,6 +389,7 @@ fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut Module<impl Backend>, cx: &mu
         }
 
         let mut data_ctx = DataContext::new();
+        data_ctx.set_align(alloc.align.bytes());
 
         if let Some(section_name) = section_name {
             // FIXME set correct segment for Mach-O files
@@ -439,7 +423,7 @@ fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut Module<impl Backend>, cx: &mu
                 }
                 GlobalAlloc::Memory(target_alloc) => {
                     cx.todo.push(TodoItem::Alloc(reloc));
-                    data_id_for_alloc_id(module, reloc, target_alloc.align, target_alloc.mutability)
+                    data_id_for_alloc_id(module, reloc, target_alloc.mutability)
                 }
                 GlobalAlloc::Static(def_id) => {
                     if tcx
@@ -464,7 +448,8 @@ fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut Module<impl Backend>, cx: &mu
             data_ctx.write_data_addr(offset.bytes() as u32, global_value, addend as i64);
         }
 
-        module.define_data(data_id, &data_ctx).unwrap();
+        // FIXME don't duplicate definitions in lazy jit mode
+        let _ = module.define_data(data_id, &data_ctx);
         cx.done.insert(data_id);
     }
 
@@ -472,13 +457,13 @@ fn define_all_allocs(tcx: TyCtxt<'_>, module: &mut Module<impl Backend>, cx: &mu
 }
 
 pub(crate) fn mir_operand_get_const_val<'tcx>(
-    fx: &FunctionCx<'_, 'tcx, impl Backend>,
+    fx: &FunctionCx<'_, 'tcx, impl Module>,
     operand: &Operand<'tcx>,
 ) -> Option<&'tcx Const<'tcx>> {
     match operand {
         Operand::Copy(_) | Operand::Move(_) => None,
         Operand::Constant(const_) => Some(
-            fx.monomorphize(&const_.literal)
+            fx.monomorphize(const_.literal)
                 .eval(fx.tcx, ParamEnv::reveal_all()),
         ),
     }